MCPcopy Index your code
hub / github.com/python/mypy / _extract_underlying_field_name

Function _extract_underlying_field_name

mypy/plugins/enums.py:273–299  ·  view source on GitHub ↗

If the given type corresponds to some Enum instance, returns the original name of that enum. For example, if we receive in the type corresponding to 'SomeEnum.FOO', we return the string "SomeEnum.Foo". This helper takes advantage of the fact that Enum instances are valid to use insi

(typ: Type)

Source from the content-addressed store, hash-verified

271
272
273def _extract_underlying_field_name(typ: Type) -> str | None:
274 """If the given type corresponds to some Enum instance, returns the
275 original name of that enum. For example, if we receive in the type
276 corresponding to 'SomeEnum.FOO', we return the string "SomeEnum.Foo".
277
278 This helper takes advantage of the fact that Enum instances are valid
279 to use inside Literal[...] types. An expression like 'SomeEnum.FOO' is
280 actually represented by an Instance type with a Literal enum fallback.
281
282 We can examine this Literal fallback to retrieve the string.
283 """
284 typ = get_proper_type(typ)
285 if not isinstance(typ, Instance):
286 return None
287
288 if not typ.type.is_enum:
289 return None
290
291 underlying_literal = typ.last_known_value
292 if underlying_literal is None:
293 return None
294
295 # The checks above have verified this LiteralType is representing an enum value,
296 # which means the 'value' field is guaranteed to be the name of the enum field
297 # as a string.
298 assert isinstance(underlying_literal.value, str)
299 return underlying_literal.value

Callers 2

enum_name_callbackFunction · 0.85
enum_value_callbackFunction · 0.85

Calls 2

get_proper_typeFunction · 0.90
isinstanceFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…