Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/proto/enums.py: 60%
68 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-08 06:45 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-08 06:45 +0000
1# Copyright 2019 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.
15import enum
17from google.protobuf import descriptor_pb2
19from proto import _file_info
20from proto import _package_info
21from proto.marshal.rules.enums import EnumRule
24class ProtoEnumMeta(enum.EnumMeta):
25 """A metaclass for building and registering protobuf enums."""
27 def __new__(mcls, name, bases, attrs):
28 # Do not do any special behavior for `proto.Enum` itself.
29 if bases[0] == enum.IntEnum:
30 return super().__new__(mcls, name, bases, attrs)
32 # Get the essential information about the proto package, and where
33 # this component belongs within the file.
34 package, marshal = _package_info.compile(name, attrs)
36 # Determine the local path of this proto component within the file.
37 local_path = tuple(attrs.get("__qualname__", name).split("."))
39 # Sanity check: We get the wrong full name if a class is declared
40 # inside a function local scope; correct this.
41 if "<locals>" in local_path:
42 ix = local_path.index("<locals>")
43 local_path = local_path[: ix - 1] + local_path[ix + 1 :]
45 # Determine the full name in protocol buffers.
46 full_name = ".".join((package,) + local_path).lstrip(".")
47 filename = _file_info._FileInfo.proto_file_name(
48 attrs.get("__module__", name.lower())
49 )
51 # Retrieve any enum options.
52 # We expect something that looks like an EnumOptions message,
53 # either an actual instance or a dict-like representation.
54 pb_options = "_pb_options"
55 opts = attrs.pop(pb_options, {})
56 # This is the only portable way to remove the _pb_options name
57 # from the enum attrs.
58 # In 3.7 onwards, we can define an _ignore_ attribute and do some
59 # mucking around with that.
60 if pb_options in attrs._member_names:
61 if isinstance(attrs._member_names, list):
62 idx = attrs._member_names.index(pb_options)
63 attrs._member_names.pop(idx)
64 else: # Python 3.11.0b3
65 del attrs._member_names[pb_options]
67 # Make the descriptor.
68 enum_desc = descriptor_pb2.EnumDescriptorProto(
69 name=name,
70 # Note: the superclass ctor removes the variants, so get them now.
71 # Note: proto3 requires that the first variant value be zero.
72 value=sorted(
73 (
74 descriptor_pb2.EnumValueDescriptorProto(name=name, number=number)
75 # Minor hack to get all the enum variants out.
76 for name, number in attrs.items()
77 if isinstance(number, int)
78 ),
79 key=lambda v: v.number,
80 ),
81 options=opts,
82 )
84 file_info = _file_info._FileInfo.maybe_add_descriptor(filename, package)
85 if len(local_path) == 1:
86 file_info.descriptor.enum_type.add().MergeFrom(enum_desc)
87 else:
88 file_info.nested_enum[local_path] = enum_desc
90 # Run the superclass constructor.
91 cls = super().__new__(mcls, name, bases, attrs)
93 # We can't just add a "_meta" element to attrs because the Enum
94 # machinery doesn't know what to do with a non-int value.
95 # The pb is set later, in generate_file_pb
96 cls._meta = _EnumInfo(full_name=full_name, pb=None)
98 file_info.enums[full_name] = cls
100 # Register the enum with the marshal.
101 marshal.register(cls, EnumRule(cls))
103 # Generate the descriptor for the file if it is ready.
104 if file_info.ready(new_class=cls):
105 file_info.generate_file_pb(new_class=cls, fallback_salt=full_name)
107 # Done; return the class.
108 return cls
111class Enum(enum.IntEnum, metaclass=ProtoEnumMeta):
112 """A enum object that also builds a protobuf enum descriptor."""
114 def _comparable(self, other):
115 # Avoid 'isinstance' to prevent other IntEnums from matching
116 return type(other) in (type(self), int)
118 def __hash__(self):
119 return hash(self.value)
121 def __eq__(self, other):
122 if not self._comparable(other):
123 return NotImplemented
125 return self.value == int(other)
127 def __ne__(self, other):
128 if not self._comparable(other):
129 return NotImplemented
131 return self.value != int(other)
133 def __lt__(self, other):
134 if not self._comparable(other):
135 return NotImplemented
137 return self.value < int(other)
139 def __le__(self, other):
140 if not self._comparable(other):
141 return NotImplemented
143 return self.value <= int(other)
145 def __ge__(self, other):
146 if not self._comparable(other):
147 return NotImplemented
149 return self.value >= int(other)
151 def __gt__(self, other):
152 if not self._comparable(other):
153 return NotImplemented
155 return self.value > int(other)
158class _EnumInfo:
159 def __init__(self, *, full_name: str, pb):
160 self.full_name = full_name
161 self.pb = pb