Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.10/site-packages/proto/enums.py: 59%

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

68 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 # 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] 

66 

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 ) 

85 

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 

91 

92 # Run the superclass constructor. 

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

94 

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) 

99 

100 file_info.enums[full_name] = cls 

101 

102 # Register the enum with the marshal. 

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

104 

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) 

108 

109 # Done; return the class. 

110 return cls 

111 

112 

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

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

115 

116 def _comparable(self, other): 

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

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

119 

120 def __hash__(self): 

121 return hash(self.value) 

122 

123 def __eq__(self, other): 

124 if not self._comparable(other): 

125 return NotImplemented 

126 

127 return self.value == int(other) 

128 

129 def __ne__(self, other): 

130 if not self._comparable(other): 

131 return NotImplemented 

132 

133 return self.value != int(other) 

134 

135 def __lt__(self, other): 

136 if not self._comparable(other): 

137 return NotImplemented 

138 

139 return self.value < int(other) 

140 

141 def __le__(self, other): 

142 if not self._comparable(other): 

143 return NotImplemented 

144 

145 return self.value <= int(other) 

146 

147 def __ge__(self, other): 

148 if not self._comparable(other): 

149 return NotImplemented 

150 

151 return self.value >= int(other) 

152 

153 def __gt__(self, other): 

154 if not self._comparable(other): 

155 return NotImplemented 

156 

157 return self.value > int(other) 

158 

159 

160class _EnumInfo: 

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

162 self.full_name = full_name 

163 self.pb = pb