diff --git a/mypy/plugins/attrs.py b/mypy/plugins/attrs.py index 1593c73cd2bfe..d0f224dc56e8c 100644 --- a/mypy/plugins/attrs.py +++ b/mypy/plugins/attrs.py @@ -39,6 +39,7 @@ SymbolTableNode, TempNode, TupleExpr, + TypeAlias, TypeApplication, TypeInfo, TypeVarExpr, @@ -458,8 +459,8 @@ def _analyze_class( if isinstance(node, PlaceholderNode): # This node is not ready yet. continue - assert isinstance(node, Var), node - node.is_initialized_in_class = False + if isinstance(node, Var): + node.is_initialized_in_class = False # Traverse the MRO and collect attributes from the parents. taken_attr_names = set(own_attrs) @@ -571,6 +572,18 @@ def _attributes_from_assignment( if attr: yield attr elif auto_attribs and stmt.type and stmt.new_syntax and not is_class_var(lhs): + name = unmangle(lhs.name) + sym = ctx.cls.info.names.get(name) + if sym is not None: + node = sym.node + if isinstance(node, TypeAlias): + ctx.api.fail( + "Type aliases inside attrs class definitions are not supported at runtime", + node, + ) + continue + if not isinstance(node, Var): + continue yield _attribute_from_auto_attrib(ctx, class_kw_only, lhs, rvalue, stmt) @@ -629,6 +642,14 @@ def _attribute_from_attrib_maker( stmt: AssignmentStmt, ) -> Attribute | None: """Return an Attribute from the assignment or None if you can't make one.""" + name = unmangle(lhs.name) + sym = ctx.cls.info.names.get(name) + if sym is not None and isinstance(sym.node, TypeAlias): + ctx.api.fail( + "Type aliases inside attrs class definitions are not supported at runtime", sym.node + ) + return None + if auto_attribs and not stmt.new_syntax: # auto_attribs requires an annotation on *every* attr.ib. assert lhs.node is not None diff --git a/test-data/unit/check-plugin-attrs.test b/test-data/unit/check-plugin-attrs.test index 7d453dcf84d01..a8305c48341e5 100644 --- a/test-data/unit/check-plugin-attrs.test +++ b/test-data/unit/check-plugin-attrs.test @@ -2512,3 +2512,24 @@ Parent(run_type = None) c = Child(run_type = None) reveal_type(c.run_type) # N: Revealed type is "builtins.int | None" [builtins fixtures/plugin_attrs.pyi] + +[case testTypeAliasInAttrsDoesNotCrash] +from typing_extensions import TypeAlias +from attrs import define + +@define +class Foo: + x: int + +@define +class One: + S: TypeAlias = Foo # E: Type aliases inside attrs class definitions are not supported at runtime + +a = One() +reveal_type(a.S) # N: Revealed type is "def (x: builtins.int) -> __main__.Foo" + +@define +class Bad: + S: TypeAlias = 42 # E: Type aliases inside attrs class definitions are not supported at runtime \ + # E: Invalid type: try using Literal[42] instead? +[builtins fixtures/plugin_attrs.pyi]