Is it possible to use type comments (# type: ...
) for PEP 695 instead? These have the advantage of being both non-intrusive (minimal or no effect on either runtime code and readability, no changes to standard Python syntax) and recognised by the compiler already.
The following is a syntax error when parsed with ast.parse(<source code>, type_comments=True)
, because type: ...
is not allowed to be on a single line on its own:
# type: int
This leaves an opportunity to use the line above a function or class declaration (or either on top or below @decorators
) as a place to bind type variables to the definition underneath.
Proposed syntax (taken from various examples in PEP 695):
# Upper bound
# type: [T: str]
class ClassA:
def method1(self) -> T: ...
# Type variable in function signature
# type: [T]
def func(a: T, b: T) -> T: ...
# Constrained type specification (string quotes omitted for forward reference)
# type: [T: (ForwardReference, bytes)]
class ClassB: ...
# Parameterisation
# type: [T]
class ClassA(BaseClass[T], param=Foo[T]): ...
This has some of the same drawbacks as the rejected idea PEP 695: Prefix Clause, especially regarding scope clarity. However, some of the feedback on this thread about the information-denseness of the current proposal suggests that there is a fine balance between clarity of scope and a flood of square brackets appearing in a class or function declaration, and there’s not much consensus on where to draw the line.