From cd64d860559c1bfefad6d60550da4da97f9b75cf Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Mon, 24 Jan 2022 10:05:46 +0000 Subject: [PATCH] Fix two type inference bugs related to enum value attributes A few bugs in type operations were exposed by #11962. This fixes them. Fix #12051, but other use cases are affected as well. First, when we erase last known values in an union with multiple Instance types, make sure that the resulting union doesn't have duplicate erased types. The duplicate items weren't incorrect as such, but they could cause overly complex error messages and potentially slow type checking performance. Second, make the join of a union type and Any commutative. Previously the result dependend on the order of the operands, which was clearly incorrect. --- mypy/erasetype.py | 9 +++++++++ mypy/join.py | 6 +++--- test-data/unit/check-enum.test | 18 ++++++++++++++++++ 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/mypy/erasetype.py b/mypy/erasetype.py index 3301325eb0a1..f8466c15bf03 100644 --- a/mypy/erasetype.py +++ b/mypy/erasetype.py @@ -161,3 +161,12 @@ def visit_type_alias_type(self, t: TypeAliasType) -> Type: # Type aliases can't contain literal values, because they are # always constructed as explicit types. return t + + def visit_union_type(self, t: UnionType) -> Type: + new = super().visit_union_type(t) + new = get_proper_type(new) + if isinstance(new, UnionType): + from mypy.typeops import make_simplified_union + # Erasure can result in many duplicate items; remove them. + new = make_simplified_union(new.items) + return new diff --git a/mypy/join.py b/mypy/join.py index d298b495fdc5..161c65ea800c 100644 --- a/mypy/join.py +++ b/mypy/join.py @@ -175,15 +175,15 @@ def join_types(s: Type, t: Type, instance_joiner: Optional[InstanceJoiner] = Non s = mypy.typeops.true_or_false(s) t = mypy.typeops.true_or_false(t) + if isinstance(s, UnionType) and not isinstance(t, UnionType): + s, t = t, s + if isinstance(s, AnyType): return s if isinstance(s, ErasedType): return t - if isinstance(s, UnionType) and not isinstance(t, UnionType): - s, t = t, s - if isinstance(s, NoneType) and not isinstance(t, NoneType): s, t = t, s diff --git a/test-data/unit/check-enum.test b/test-data/unit/check-enum.test index 2af57da9cbdc..a7c8ef15e474 100644 --- a/test-data/unit/check-enum.test +++ b/test-data/unit/check-enum.test @@ -1868,3 +1868,21 @@ class WithOverload(enum.IntEnum): class SubWithOverload(WithOverload): # Should pass pass [builtins fixtures/tuple.pyi] + +[case testEnumtValueUnionSimplification] +from enum import IntEnum +from typing import Any + +class C(IntEnum): + X = 0 + Y = 1 + Z = 2 + +def f1(c: C) -> None: + x = {'x': c.value} + reveal_type(x) # N: Revealed type is "builtins.dict[builtins.str*, builtins.int]" + +def f2(c: C, a: Any) -> None: + x = {'x': c.value, 'y': a} + reveal_type(x) # N: Revealed type is "builtins.dict[builtins.str*, Any]" +[builtins fixtures/dict.pyi]