PEP 613: Loosen class scope restriction of explicit TypeAlias (#2154)

Per discussion on typing-sig
https://mail.python.org/archives/list/typing-sig@python.org/thread/CGOO7GPPECGMLFDUDXSSXTRADI4BXYCS/

Co-authored-by: CAM Gerlach <CAM.Gerlach@Gerlach.CAM>
This commit is contained in:
Nipunn Koorapati 2022-01-12 13:28:17 -08:00 committed by GitHub
parent 4d55ea96be
commit 3ec824affd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 24 additions and 5 deletions

View File

@ -95,6 +95,17 @@ across the codebase can be suppressed.
Scope Restrictions:
*******************
::
class Foo:
x = ClassName
y: TypeAlias = ClassName
z: Type[ClassName] = ClassName
Type aliases are valid within class scope, both implicitly (``x``) and
explicitly (``y``). If the line should be interpreted as a class
variable, it must be explicitly annotated (``z``).
::
x = ClassName
@ -103,7 +114,7 @@ Scope Restrictions:
The outer ``x`` is a valid type alias, but type checkers must error if the
inner ``x`` is ever used as a type because type aliases cannot be defined
inside a nested scope.
inside of a function.
This is confusing because the alias declaration rule is not explicit, and because
a type error will not be thrown on the location of the inner type alias declaration
but rather on every one of its subsequent use cases.
@ -116,10 +127,10 @@ but rather on every one of its subsequent use cases.
def bar() -> None:
x: TypeAlias = ClassName
With explicit aliases, the outer assignment is still a valid type variable,
and the inner assignment can either be a valid local variable or a clear error,
communicating to the author that type aliases cannot be defined inside a nested
scope.
With explicit aliases, the outer assignment is still a valid type variable.
Inside ``foo``, the inner assignment should be interpreted as ``x: Type[ClassName]``.
Inside ``bar``, the type checker should raise a clear error, communicating
to the author that type aliases cannot be defined inside a function.
Specification
@ -200,6 +211,14 @@ appealing because it still sticks with the ``MyType = int`` assignment
syntax, and adds some information for the type checker purely as an annotation.
Version History
===============
* 2021-11-16
* Allow TypeAlias inside class scope
Copyright
=========