Errors when using type parameter defaults #10909
-
|
Best expressed through code examples, with questions in comments. Code sample in pyright playground from typing import Any
class Bar[T=None]:
...
class AnotherBar[D]:
...
class MyClass[D, T=None]:
def foo(self) -> type[Bar[T]]:
return Bar # type error: "type[Bar[None]]" is not assignable to "type[Bar[T@MyClass]]"
def another_foo(self) -> type[Bar[T]]:
return Bar[T] # no type error, but this returns a Generic alias, not a type object
# Why is this allowed? How can I enforce a type object return?
def yet_another_foo(self) -> type[AnotherBar[D]]:
return AnotherBar # no type error when no type default is used
def workaround(self) -> type[Bar[Any]]:
return Bar # no error, but slight loss in type specification |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
If you provide an explicit specialization for a generic class (e.g. The fact that |
Beta Was this translation helpful? Give feedback.
If you provide an explicit specialization for a generic class (e.g.
Bar[T]orBar[Any]), then the type checker will honor that specialization. If you don't provide an explicit specialization, then the type checker will assume the default value for the argument. If no such default is specified, the default becomesAny.The fact that
Bar[T]orBar[Any]is represented as aGenericAliasat runtime is an implementation detail of the type system in Python. For all intents and purposes it acts like the original class object. For example,reveal_type(list[int])will revealtype[list[int]. It's notGenericAlias. You won't seeGenericAliasappear anywhere within the Python typing spec.