Skip to content

Commit

Permalink
PEP 613: Loosen class scope restriction of explicit TypeAlias (#2154)
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
nipunn1313 and CAM-Gerlach authored Jan 12, 2022
1 parent 4d55ea9 commit 3ec824a
Showing 1 changed file with 24 additions and 5 deletions.
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

0 comments on commit 3ec824a

Please sign in to comment.