|
28 | 28 | LiteralType,
|
29 | 29 | ProperType,
|
30 | 30 | Type,
|
| 31 | + TypeVarType, |
| 32 | + UnionType, |
31 | 33 | get_proper_type,
|
32 | 34 | is_named_instance,
|
33 | 35 | )
|
@@ -297,3 +299,62 @@ def _extract_underlying_field_name(typ: Type) -> str | None:
|
297 | 299 | # as a string.
|
298 | 300 | assert isinstance(underlying_literal.value, str)
|
299 | 301 | return underlying_literal.value
|
| 302 | + |
| 303 | + |
| 304 | +def enum_new_callback(ctx: mypy.plugin.FunctionContext) -> Type: |
| 305 | + """This plugin refines the return type of `__new__`, ensuring reconstructed |
| 306 | + Enums are idempotent. |
| 307 | +
|
| 308 | + By default, mypy will infer that `Foo(Foo.x)` is of type `Foo`. This plugin |
| 309 | + ensures types are not loosened, meaning with this plugin enabled |
| 310 | + `Foo(Foo.x)` is of type `Literal[Foo.x]?`. |
| 311 | +
|
| 312 | + This means with this plugin: |
| 313 | + ``` |
| 314 | + reveal_type(Foo(Foo.x)) # mypy reveals Literal[Foo.x]? |
| 315 | + ``` |
| 316 | +
|
| 317 | + This plugin works by adjusting the return type of `__new__` to be the given |
| 318 | + argument type, if and only if `__new__` comes from `enum.Enum`. |
| 319 | +
|
| 320 | + This plugin supports arguments that are Final, Literial, Union of Literials |
| 321 | + and generic TypeVars. |
| 322 | + """ |
| 323 | + base_ret = ctx.default_return_type |
| 324 | + enum_inst = get_proper_type(base_ret) |
| 325 | + if not isinstance(enum_inst, Instance): |
| 326 | + return base_ret |
| 327 | + |
| 328 | + info: TypeInfo = enum_inst.type |
| 329 | + if not info.is_enum: |
| 330 | + return base_ret |
| 331 | + |
| 332 | + if _implements_new(info): |
| 333 | + return base_ret |
| 334 | + |
| 335 | + if not ctx.args or not ctx.args[0] or not ctx.arg_types or not ctx.arg_types[0]: |
| 336 | + return base_ret |
| 337 | + |
| 338 | + arg0_t = get_proper_type(ctx.arg_types[0][0]) |
| 339 | + |
| 340 | + if isinstance(arg0_t, Instance) and arg0_t.type is info: |
| 341 | + return arg0_t |
| 342 | + elif isinstance(arg0_t, LiteralType) and arg0_t.fallback.type is info: |
| 343 | + return arg0_t |
| 344 | + elif isinstance(arg0_t, UnionType): |
| 345 | + |
| 346 | + def is_memeber(given_t: ProperType) -> bool: |
| 347 | + return (isinstance(given_t, Instance) and given_t.type is info) or ( |
| 348 | + isinstance(given_t, LiteralType) and given_t.fallback.type is info |
| 349 | + ) |
| 350 | + |
| 351 | + items = [get_proper_type(it) for it in arg0_t.items] |
| 352 | + if items and all(is_memeber(item) for item in items): |
| 353 | + return arg0_t |
| 354 | + elif (isinstance(arg0_t, TypeVarType)) and isinstance( |
| 355 | + get_proper_type(arg0_t.upper_bound), Instance |
| 356 | + ): |
| 357 | + if arg0_t.upper_bound.type is info: |
| 358 | + return arg0_t |
| 359 | + |
| 360 | + return base_ret |
0 commit comments