Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit cb02891

Browse files
fix callable enum narrowing (#21946)
Fixes ##17222 Narrowing an enum to a literal(with `==` or `match`) gives a `LiteralType`, which was not being checked when type checking a call. This PR add a `LiteralType` branch to `check_call` that will delegate to its `fallback` instance.
1 parent ae39cdb commit cb02891

2 files changed

Lines changed: 36 additions & 0 deletions

File tree

mypy/checkexpr.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1657,6 +1657,18 @@ def check_call(
16571657
object_type,
16581658
original_type=callee,
16591659
)
1660+
elif isinstance(callee, LiteralType):
1661+
return self.check_call(
1662+
callee.fallback,
1663+
args,
1664+
arg_kinds,
1665+
context,
1666+
arg_names,
1667+
callable_node,
1668+
callable_name,
1669+
object_type,
1670+
original_type=original_type,
1671+
)
16601672
elif isinstance(callee, UninhabitedType):
16611673
ret = UninhabitedType()
16621674
ret.ambiguous = callee.ambiguous

test-data/unit/check-enum.test

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2983,3 +2983,27 @@ def f(x: SE | None) -> None:
29832983
else:
29842984
reveal_type(x) # N: Revealed type is "__main__.SE | None"
29852985
[builtins fixtures/primitives.pyi]
2986+
2987+
2988+
[case testCallableEnumNarrowing]
2989+
# See: https://github.com/python/mypy/issues/17222
2990+
2991+
import enum
2992+
2993+
class Foo(enum.Enum):
2994+
FOO1 = enum.auto()
2995+
FOO2 = enum.auto()
2996+
2997+
def __call__(self) -> str:
2998+
return self.name
2999+
3000+
foo = Foo.FOO1
3001+
3002+
match foo:
3003+
case Foo.FOO1:
3004+
foo()
3005+
reveal_type(foo) # N: Revealed type is "Literal[__main__.Foo.FOO1]"
3006+
case _:
3007+
foo()
3008+
reveal_type(foo) # N: Revealed type is "Literal[__main__.Foo.FOO2]"
3009+
[builtins fixtures/primitives.pyi]

0 commit comments

Comments
 (0)