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)
| 34 | |
| 35 | |
| 36 | def 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") |
nothing calls this directly
no test coverage detected
searching dependent graphs…