Debian Codegraph @

proto/marshal/rules/wrappers.py

raw
1 # Copyright 2018 Google LLC
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # https://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 from google.protobuf import wrappers_pb2
16
17
18 class WrapperRule:
19 """A marshal for converting the protobuf wrapper classes to Python.
20
21 This class converts between ``google.protobuf.BoolValue``,
22 ``google.protobuf.StringValue``, and their siblings to the appropriate
23 Python equivalents.
24
25 These are effectively similar to the protobuf primitives except
26 that None becomes a possible value.
27 """
28
29 def to_python(self, value, *, absent: bool = None):
30 if isinstance(value, self._proto_type):
31 if absent:
32 return None
33 return value.value
34 return value
35
36 def to_proto(self, value):
37 if isinstance(value, self._python_type):
38 return self._proto_type(value=value)
39 return value
40
41
42 class DoubleValueRule(WrapperRule):
43 _proto_type = wrappers_pb2.DoubleValue
44 _python_type = float
45
46
47 class FloatValueRule(WrapperRule):
48 _proto_type = wrappers_pb2.FloatValue
49 _python_type = float
50
51
52 class Int64ValueRule(WrapperRule):
53 _proto_type = wrappers_pb2.Int64Value
54 _python_type = int
55
56
57 class UInt64ValueRule(WrapperRule):
58 _proto_type = wrappers_pb2.UInt64Value
59 _python_type = int
60
61
62 class Int32ValueRule(WrapperRule):
63 _proto_type = wrappers_pb2.Int32Value
64 _python_type = int
65
66
67 class UInt32ValueRule(WrapperRule):
68 _proto_type = wrappers_pb2.UInt32Value
69 _python_type = int
70
71
72 class BoolValueRule(WrapperRule):
73 _proto_type = wrappers_pb2.BoolValue
74 _python_type = bool
75
76
77 class StringValueRule(WrapperRule):
78 _proto_type = wrappers_pb2.StringValue
79 _python_type = str
80
81
82 class BytesValueRule(WrapperRule):
83 _proto_type = wrappers_pb2.BytesValue
84 _python_type = bytes