Skip to content

Commit

Permalink
[PEP 695] Don't crash when redefining something as a type alias (#17335)
Browse files Browse the repository at this point in the history
Generate an error instead.

Work on #15238.
  • Loading branch information
JukkaL committed Jun 6, 2024
1 parent 6682563 commit f989414
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
9 changes: 8 additions & 1 deletion mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -5323,6 +5323,14 @@ def visit_type_alias_stmt(self, s: TypeAliasStmt) -> None:
all_type_params_names = [p.name for p in s.type_args]

try:
existing = self.current_symbol_table().get(s.name.name)
if existing and not (
isinstance(existing.node, TypeAlias)
or (isinstance(existing.node, PlaceholderNode) and existing.node.line == s.line)
):
self.already_defined(s.name.name, s, existing, "Name")
return

tag = self.track_incomplete_refs()
res, alias_tvars, depends_on, qualified_tvars, empty_tuple_index = self.analyze_alias(
s.name.name,
Expand Down Expand Up @@ -5378,7 +5386,6 @@ def visit_type_alias_stmt(self, s: TypeAliasStmt) -> None:
python_3_12_type_alias=True,
)

existing = self.current_symbol_table().get(s.name.name)
if (
existing
and isinstance(existing.node, (PlaceholderNode, TypeAlias))
Expand Down
36 changes: 36 additions & 0 deletions test-data/unit/check-python312.test
Original file line number Diff line number Diff line change
Expand Up @@ -1453,3 +1453,39 @@ class E[T]:
reveal_type(E[str]().a) # N: Revealed type is "builtins.list[Any]"
[builtins fixtures/tuple.pyi]
[typing fixtures/typing-full.pyi]

[case testPEP695RedefineAsTypeAlias1]
# flags: --enable-incomplete-feature=NewGenericSyntax
class C: pass
type C = int # E: Name "C" already defined on line 2

A = 0
type A = str # E: Name "A" already defined on line 5
reveal_type(A) # N: Revealed type is "builtins.int"

[case testPEP695RedefineAsTypeAlias2]
# flags: --enable-incomplete-feature=NewGenericSyntax
from m import D
type D = int # E: Name "D" already defined (possibly by an import)
a: D
reveal_type(a) # N: Revealed type is "m.D"
[file m.py]
class D: pass

[case testPEP695RedefineAsTypeAlias3]
# flags: --enable-incomplete-feature=NewGenericSyntax
D = list["Forward"]
type D = int # E: Name "D" already defined on line 2
Forward = str
x: D
reveal_type(x) # N: Revealed type is "builtins.list[builtins.str]"

[case testPEP695MultiDefinitionsForTypeAlias]
# flags: --enable-incomplete-feature=NewGenericSyntax
if int():
type A[T] = list[T]
else:
type A[T] = str # E: Name "A" already defined on line 3
x: T # E: Name "T" is not defined
a: A[int]
reveal_type(a) # N: Revealed type is "builtins.list[builtins.int]"

0 comments on commit f989414

Please sign in to comment.