Skip to content

Commit fb3ad76

Browse files
authored
refactor: simplify AutoStrEnum definition (#458)
With now only Python 3.6 supported, we can use the _generate_next_value() hook instead of metaclass magic.
1 parent 99ef1d2 commit fb3ad76

File tree

1 file changed

+9
-32
lines changed
  • google/cloud/bigquery/magics/line_arg_parser

1 file changed

+9
-32
lines changed

google/cloud/bigquery/magics/line_arg_parser/lexer.py

+9-32
Original file line numberDiff line numberDiff line change
@@ -136,51 +136,28 @@
136136
)
137137

138138

139-
# The _generate_next_value_() enum hook is only available in Python 3.6+, thus we
140-
# need to do some acrobatics to implement an "auto str enum" base class. Implementation
141-
# based on the recipe provided by the very author of the Enum library:
142-
# https://stackoverflow.com/a/32313954/5040035
143-
class StrEnumMeta(enum.EnumMeta):
144-
@classmethod
145-
def __prepare__(metacls, name, bases, **kwargs):
146-
# Having deterministic enum members definition order is nice.
147-
return OrderedDict()
139+
class AutoStrEnum(str, enum.Enum):
140+
"""Base enum class for for name=value str enums."""
148141

149-
def __new__(metacls, name, bases, oldclassdict):
150-
# Scan through the declared enum members and convert any value that is a plain
151-
# empty tuple into a `str` of the name instead.
152-
newclassdict = enum._EnumDict()
153-
for key, val in oldclassdict.items():
154-
if val == ():
155-
val = key
156-
newclassdict[key] = val
157-
return super(StrEnumMeta, metacls).__new__(metacls, name, bases, newclassdict)
142+
def _generate_next_value_(name, start, count, last_values):
143+
return name
158144

159145

160-
# The @six.add_metaclass decorator does not work, Enum complains about _sunder_ names,
161-
# and we cannot use class syntax directly, because the Python 3 version would cause
162-
# a syntax error under Python 2.
163-
AutoStrEnum = StrEnumMeta(
164-
"AutoStrEnum",
165-
(str, enum.Enum),
166-
{"__doc__": "Base enum class for for name=value str enums."},
167-
)
168-
169146
TokenType = AutoStrEnum(
170147
"TokenType",
171148
[
172-
(name, name)
149+
(name, enum.auto())
173150
for name in itertools.chain.from_iterable(token_types.values())
174151
if not name.startswith("GOTO_")
175152
],
176153
)
177154

178155

179156
class LexerState(AutoStrEnum):
180-
PARSE_POS_ARGS = () # parsing positional arguments
181-
PARSE_NON_PARAMS_OPTIONS = () # parsing options other than "--params"
182-
PARSE_PARAMS_OPTION = () # parsing the "--params" option
183-
STATE_END = ()
157+
PARSE_POS_ARGS = enum.auto() # parsing positional arguments
158+
PARSE_NON_PARAMS_OPTIONS = enum.auto() # parsing options other than "--params"
159+
PARSE_PARAMS_OPTION = enum.auto() # parsing the "--params" option
160+
STATE_END = enum.auto()
184161

185162

186163
class Lexer(object):

0 commit comments

Comments
 (0)