Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/proto/enums.py: 56%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
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 elif isinstance(attrs._member_names, set): # PyPy
65 attrs._member_names.discard(pb_options)
66 else: # Python 3.11.0b3
67 del attrs._member_names[pb_options]
69 # Make the descriptor.
70 enum_desc = descriptor_pb2.EnumDescriptorProto(
71 name=name,
72 # Note: the superclass ctor removes the variants, so get them now.
73 # Note: proto3 requires that the first variant value be zero.
74 value=sorted(
75 (
76 descriptor_pb2.EnumValueDescriptorProto(name=name, number=number)
77 # Minor hack to get all the enum variants out.
78 # Use the `_member_names` property to get only the enum members
79 # See https://github.com/googleapis/proto-plus-python/issues/490
80 for name, number in attrs.items()
81 if name in attrs._member_names and isinstance(number, int)
82 ),
83 key=lambda v: v.number,
84 ),
85 options=opts,
86 )
88 file_info = _file_info._FileInfo.maybe_add_descriptor(filename, package)
89 if len(local_path) == 1:
90 file_info.descriptor.enum_type.add().MergeFrom(enum_desc)
91 else:
92 file_info.nested_enum[local_path] = enum_desc
94 # Run the superclass constructor.
95 cls = super().__new__(mcls, name, bases, attrs)
97 # We can't just add a "_meta" element to attrs because the Enum
98 # machinery doesn't know what to do with a non-int value.
99 # The pb is set later, in generate_file_pb
100 cls._meta = _EnumInfo(full_name=full_name, pb=None)
102 file_info.enums[full_name] = cls
104 # Register the enum with the marshal.
105 marshal.register(cls, EnumRule(cls))
107 # Generate the descriptor for the file if it is ready.
108 if file_info.ready(new_class=cls):
109 file_info.generate_file_pb(new_class=cls, fallback_salt=full_name)
111 # Done; return the class.
112 return cls
115class Enum(enum.IntEnum, metaclass=ProtoEnumMeta):
116 """A enum object that also builds a protobuf enum descriptor."""
118 def _comparable(self, other):
119 # Avoid 'isinstance' to prevent other IntEnums from matching
120 return type(other) in (type(self), int)
122 def __hash__(self):
123 return hash(self.value)
125 def __eq__(self, other):
126 if not self._comparable(other):
127 return NotImplemented
129 return self.value == int(other)
131 def __ne__(self, other):
132 if not self._comparable(other):
133 return NotImplemented
135 return self.value != int(other)
137 def __lt__(self, other):
138 if not self._comparable(other):
139 return NotImplemented
141 return self.value < int(other)
143 def __le__(self, other):
144 if not self._comparable(other):
145 return NotImplemented
147 return self.value <= int(other)
149 def __ge__(self, other):
150 if not self._comparable(other):
151 return NotImplemented
153 return self.value >= int(other)
155 def __gt__(self, other):
156 if not self._comparable(other):
157 return NotImplemented
159 return self.value > int(other)
162class _EnumInfo:
163 def __init__(self, *, full_name: str, pb):
164 self.full_name = full_name
165 self.pb = pb