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, _package_info
20from proto.marshal.rules.enums import EnumRule
23class ProtoEnumMeta(enum.EnumMeta):
24 """A metaclass for building and registering protobuf enums."""
26 def __new__(mcls, name, bases, attrs):
27 # Do not do any special behavior for `proto.Enum` itself.
28 if bases[0] == enum.IntEnum:
29 return super().__new__(mcls, name, bases, attrs)
31 # Get the essential information about the proto package, and where
32 # this component belongs within the file.
33 package, marshal = _package_info.compile(name, attrs)
35 # Determine the local path of this proto component within the file.
36 local_path = tuple(attrs.get("__qualname__", name).split("."))
38 # Sanity check: We get the wrong full name if a class is declared
39 # inside a function local scope; correct this.
40 if "<locals>" in local_path:
41 ix = local_path.index("<locals>")
42 local_path = local_path[: ix - 1] + local_path[ix + 1 :]
44 # Determine the full name in protocol buffers.
45 full_name = ".".join((package,) + local_path).lstrip(".")
46 filename = _file_info._FileInfo.proto_file_name(
47 attrs.get("__module__", name.lower())
48 )
50 # Retrieve any enum options.
51 # We expect something that looks like an EnumOptions message,
52 # either an actual instance or a dict-like representation.
53 pb_options = "_pb_options"
54 opts = attrs.pop(pb_options, {})
55 # This is the only portable way to remove the _pb_options name
56 # from the enum attrs.
57 # TODO: Use _ignore_ attribute to ignore _pb_options (Issue #16911)
58 if pb_options in attrs._member_names:
59 if isinstance(attrs._member_names, list):
60 idx = attrs._member_names.index(pb_options)
61 attrs._member_names.pop(idx)
62 elif isinstance(attrs._member_names, set): # PyPy
63 attrs._member_names.discard(pb_options)
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 # Use the `_member_names` property to get only the enum members
77 # See https://github.com/googleapis/proto-plus-python/issues/490
78 for name, number in attrs.items()
79 if name in attrs._member_names and isinstance(number, int)
80 ),
81 key=lambda v: v.number,
82 ),
83 options=opts,
84 )
86 file_info = _file_info._FileInfo.maybe_add_descriptor(filename, package)
87 if len(local_path) == 1:
88 file_info.descriptor.enum_type.add().MergeFrom(enum_desc)
89 else:
90 file_info.nested_enum[local_path] = enum_desc
92 # Run the superclass constructor.
93 cls = super().__new__(mcls, name, bases, attrs)
95 # We can't just add a "_meta" element to attrs because the Enum
96 # machinery doesn't know what to do with a non-int value.
97 # The pb is set later, in generate_file_pb
98 cls._meta = _EnumInfo(full_name=full_name, pb=None)
100 file_info.enums[full_name] = cls
102 # Register the enum with the marshal.
103 marshal.register(cls, EnumRule(cls))
105 # Generate the descriptor for the file if it is ready.
106 if file_info.ready(new_class=cls):
107 file_info.generate_file_pb(new_class=cls, fallback_salt=full_name)
109 # Done; return the class.
110 return cls
113class Enum(enum.IntEnum, metaclass=ProtoEnumMeta):
114 """A enum object that also builds a protobuf enum descriptor."""
116 def _comparable(self, other):
117 # Avoid 'isinstance' to prevent other IntEnums from matching
118 return type(other) in (type(self), int)
120 def __hash__(self):
121 return hash(self.value)
123 def __eq__(self, other):
124 if not self._comparable(other):
125 return NotImplemented
127 return self.value == int(other)
129 def __ne__(self, other):
130 if not self._comparable(other):
131 return NotImplemented
133 return self.value != int(other)
135 def __lt__(self, other):
136 if not self._comparable(other):
137 return NotImplemented
139 return self.value < int(other)
141 def __le__(self, other):
142 if not self._comparable(other):
143 return NotImplemented
145 return self.value <= int(other)
147 def __ge__(self, other):
148 if not self._comparable(other):
149 return NotImplemented
151 return self.value >= int(other)
153 def __gt__(self, other):
154 if not self._comparable(other):
155 return NotImplemented
157 return self.value > int(other)
160class _EnumInfo:
161 def __init__(self, *, full_name: str, pb):
162 self.full_name = full_name
163 self.pb = pb