Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 2 commits into from
Jan 12, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 24 additions & 5 deletions pep-0613.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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
=========

Expand Down