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

71 statements  

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. 

14 

15import enum 

16 

17from google.protobuf import descriptor_pb2 

18 

19from proto import _file_info 

20from proto import _package_info 

21from proto.marshal.rules.enums import EnumRule 

22 

23 

24class ProtoEnumMeta(enum.EnumMeta): 

25 """A metaclass for building and registering protobuf enums.""" 

26 

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) 

31 

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) 

35 

36 # Determine the local path of this proto component within the file. 

37 local_path = tuple(attrs.get("__qualname__", name).split(".")) 

38 

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 :] 

44 

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 ) 

50 

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 # TODO: Use _ignore_ attribute to ignore _pb_options (Issue #16911) 

59 if pb_options in attrs._member_names: 

60 if isinstance(attrs._member_names, list): 

61 idx = attrs._member_names.index(pb_options) 

62 attrs._member_names.pop(idx) 

63 elif isinstance(attrs._member_names, set): # PyPy 

64 attrs._member_names.discard(pb_options) 

65 else: # Python 3.11.0b3 

66 del attrs._member_names[pb_options] 

67 

68 # Make the descriptor. 

69 enum_desc = descriptor_pb2.EnumDescriptorProto( 

70 name=name, 

71 # Note: the superclass ctor removes the variants, so get them now. 

72 # Note: proto3 requires that the first variant value be zero. 

73 value=sorted( 

74 ( 

75 descriptor_pb2.EnumValueDescriptorProto(name=name, number=number) 

76 # Minor hack to get all the enum variants out. 

77 # Use the `_member_names` property to get only the enum members 

78 # See https://github.com/googleapis/proto-plus-python/issues/490 

79 for name, number in attrs.items() 

80 if name in attrs._member_names and isinstance(number, int) 

81 ), 

82 key=lambda v: v.number, 

83 ), 

84 options=opts, 

85 ) 

86 

87 file_info = _file_info._FileInfo.maybe_add_descriptor(filename, package) 

88 if len(local_path) == 1: 

89 file_info.descriptor.enum_type.add().MergeFrom(enum_desc) 

90 else: 

91 file_info.nested_enum[local_path] = enum_desc 

92 

93 # Run the superclass constructor. 

94 cls = super().__new__(mcls, name, bases, attrs) 

95 

96 # We can't just add a "_meta" element to attrs because the Enum 

97 # machinery doesn't know what to do with a non-int value. 

98 # The pb is set later, in generate_file_pb 

99 cls._meta = _EnumInfo(full_name=full_name, pb=None) 

100 

101 file_info.enums[full_name] = cls 

102 

103 # Register the enum with the marshal. 

104 marshal.register(cls, EnumRule(cls)) 

105 

106 # Generate the descriptor for the file if it is ready. 

107 if file_info.ready(new_class=cls): 

108 file_info.generate_file_pb(new_class=cls, fallback_salt=full_name) 

109 

110 # Done; return the class. 

111 return cls 

112 

113 

114class Enum(enum.IntEnum, metaclass=ProtoEnumMeta): 

115 """A enum object that also builds a protobuf enum descriptor.""" 

116 

117 def _comparable(self, other): 

118 # Avoid 'isinstance' to prevent other IntEnums from matching 

119 return type(other) in (type(self), int) 

120 

121 def __hash__(self): 

122 return hash(self.value) 

123 

124 def __eq__(self, other): 

125 if not self._comparable(other): 

126 return NotImplemented 

127 

128 return self.value == int(other) 

129 

130 def __ne__(self, other): 

131 if not self._comparable(other): 

132 return NotImplemented 

133 

134 return self.value != int(other) 

135 

136 def __lt__(self, other): 

137 if not self._comparable(other): 

138 return NotImplemented 

139 

140 return self.value < int(other) 

141 

142 def __le__(self, other): 

143 if not self._comparable(other): 

144 return NotImplemented 

145 

146 return self.value <= int(other) 

147 

148 def __ge__(self, other): 

149 if not self._comparable(other): 

150 return NotImplemented 

151 

152 return self.value >= int(other) 

153 

154 def __gt__(self, other): 

155 if not self._comparable(other): 

156 return NotImplemented 

157 

158 return self.value > int(other) 

159 

160 

161class _EnumInfo: 

162 def __init__(self, *, full_name: str, pb): 

163 self.full_name = full_name 

164 self.pb = pb