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

Function enum_name_callback

mypy/plugins/enums.py:36–57  ·  view source on GitHub ↗

This plugin refines the 'name' attribute in enums to act as if they were declared to be final. For example, the expression 'MyEnum.FOO.name' normally is inferred to be of type 'str'. This plugin will instead make the inferred type be a 'str' where the last known value is 'Liter

(ctx: mypy.plugin.AttributeContext)

Source from the content-addressed store, hash-verified

34
35
36def enum_name_callback(ctx: mypy.plugin.AttributeContext) -> Type:
37 """This plugin refines the 'name' attribute in enums to act as if
38 they were declared to be final.
39
40 For example, the expression 'MyEnum.FOO.name' normally is inferred
41 to be of type 'str'.
42
43 This plugin will instead make the inferred type be a 'str' where the
44 last known value is 'Literal["FOO"]'. This means it would be legal to
45 use 'MyEnum.FOO.name' in contexts that expect a Literal type, just like
46 any other Final variable or attribute.
47
48 This plugin assumes that the provided context is an attribute access
49 matching one of the strings found in 'ENUM_NAME_ACCESS'.
50 """
51 enum_field_name = _extract_underlying_field_name(ctx.type)
52 if enum_field_name is None:
53 return ctx.default_attr_type
54 else:
55 str_type = ctx.api.named_generic_type("builtins.str", [])
56 literal_type = LiteralType(enum_field_name, fallback=str_type)
57 return str_type.copy_modified(last_known_value=literal_type)
58
59
60_T = TypeVar("_T")

Callers

nothing calls this directly

Calls 4

LiteralTypeClass · 0.90
named_generic_typeMethod · 0.45
copy_modifiedMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…