Skip to content

Commit 3ec824a

Browse files
PEP 613: Loosen class scope restriction of explicit TypeAlias (#2154)
Per discussion on typing-sig https://mail.python.org/archives/list/[email protected]/thread/CGOO7GPPECGMLFDUDXSSXTRADI4BXYCS/ Co-authored-by: CAM Gerlach <[email protected]>
1 parent 4d55ea9 commit 3ec824a

File tree

1 file changed

+24
-5
lines changed

1 file changed

+24
-5
lines changed

pep-0613.rst

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,17 @@ across the codebase can be suppressed.
9595
Scope Restrictions:
9696
*******************
9797

98+
::
99+
100+
class Foo:
101+
x = ClassName
102+
y: TypeAlias = ClassName
103+
z: Type[ClassName] = ClassName
104+
105+
Type aliases are valid within class scope, both implicitly (``x``) and
106+
explicitly (``y``). If the line should be interpreted as a class
107+
variable, it must be explicitly annotated (``z``).
108+
98109
::
99110

100111
x = ClassName
@@ -103,7 +114,7 @@ Scope Restrictions:
103114

104115
The outer ``x`` is a valid type alias, but type checkers must error if the
105116
inner ``x`` is ever used as a type because type aliases cannot be defined
106-
inside a nested scope.
117+
inside of a function.
107118
This is confusing because the alias declaration rule is not explicit, and because
108119
a type error will not be thrown on the location of the inner type alias declaration
109120
but rather on every one of its subsequent use cases.
@@ -116,10 +127,10 @@ but rather on every one of its subsequent use cases.
116127
def bar() -> None:
117128
x: TypeAlias = ClassName
118129

119-
With explicit aliases, the outer assignment is still a valid type variable,
120-
and the inner assignment can either be a valid local variable or a clear error,
121-
communicating to the author that type aliases cannot be defined inside a nested
122-
scope.
130+
With explicit aliases, the outer assignment is still a valid type variable.
131+
Inside ``foo``, the inner assignment should be interpreted as ``x: Type[ClassName]``.
132+
Inside ``bar``, the type checker should raise a clear error, communicating
133+
to the author that type aliases cannot be defined inside a function.
123134

124135

125136
Specification
@@ -200,6 +211,14 @@ appealing because it still sticks with the ``MyType = int`` assignment
200211
syntax, and adds some information for the type checker purely as an annotation.
201212

202213

214+
Version History
215+
===============
216+
217+
* 2021-11-16
218+
219+
* Allow TypeAlias inside class scope
220+
221+
203222
Copyright
204223
=========
205224

0 commit comments

Comments
 (0)