Closed rayzchen closed 3 years ago
I can't tell how you're calling AddComponent
. Could you provide a more complete sample that demonstrates where you're seeing the problem?
You've defined a TypeVar T
that is bound to Baz
, which means that the TypeVar constraint solver will verify that the argument corresponding to parameter class_
is the Baz
class or some class that derives from it.
Here's an example that demonstrates how this works.
from typing import TypeVar, Type
class Baz:
T = TypeVar("T", bound="Baz")
def AddComponent(self, class_: Type[T]) -> T:
...
class SubclassOfBaz(Baz):
...
result = Baz().AddComponent(SubclassOfBaz)
reveal_type(result) # SubclassOfBaz
Oh, I thought Type[T]
was just a generic class which you could reference with T
. For example:
from typing import TypeVar, Type
class Baz:
T = TypeVar("T", bound="Baz")
def AddComponent(self, class_: Type[T]) -> T:
...
result = Baz().AddComponent(int)
reveal_type(result) # int
EDIT: Just checked the docs of Mypy, seems that bound
restricts it to subclasses only. Still, removing bound
doesn't fix anything and the return type is still T@AddComponent
according to vscode.
Ahhhh, a reload fixed the problem. I'm having a bad day today... just opened two issues that were resolved with a reload. I really need to get a better computer that doesn't take 5 minutes to reload vscode. 😩 At least I learned that bound
restricts TypeVars to a subclass of a specific type.
Environment data
Expected behaviour
Return value is of the type I specified
Actual behaviour
Return value is of type
T@AddComponent
Logs
Code Snippet / Additional information
When I call AddComponent, it returns a variable of type T@AddComponent Shouldn't Pylance recognise T as being the class type?