I would like to create a typing special form that takes a non-type, say integer, as an argument, similar to the 2nd argument of typing.Annotated
.
For example, I’d like foo[5]
to be the same type annotation as Annotated[int, 5]
.
There are many ways that don’t fail at runtime, but are rejected by the type checker. I’m using mypy 1.11.1 – latest version at this time.
import typing
class foo:
def __class_getitem__(cls, param: int):
return typing.Annotated[int, param]
foo5 : foo[5]
mypy doesn’t like it:
"foo" expects no type arguments, but 1 given [type-arg]
Invalid type: try using Literal[5] instead? [valid-type]
Using _SpecialForm
:
@typing._SpecialForm
def bar(_self, param : int):
return typing.Annotated[int, param]
bar5 : bar[5]
Nope:
Too many arguments for "_SpecialForm" [call-arg]
Function "ex_typing_1.bar" is not valid as a type [valid-type]
Perhaps you need "Callable[...]" or a callback protocol?
Invalid type: try using Literal[5] instead? [valid-type]
Even the parenthesized syntax I don’t care much for is no-go:
def baz(param : int):
return typing.Annotated[int, param]
baz5 : baz(5)
Sez mypy:
Invalid type comment or annotation [valid-type]
Suggestion: use baz[...] instead of baz(...)