-
I have searched through these discussions and issues and have not found the answer to the following. I receive this error on line 25 below (error line marked with comment):
On this code:
Note the unused
I have tried multiple variations of TypeVar and Type, and probably a few others I can't remember at the moment. The above code runs and produces the expected result. Any suggestions would be gratefully received! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
This is a great use case for the new from typing_extensions import Self
class Base:
def __init__(self) -> None:
self._callbacks: list[Callable[[Self, dict[str, Any]], None]] = []
def add_callback(self, callback: Callable[[Self, dict[str, Any]], None]) -> None:
self._callbacks.append(callback) If you don't want to depend on the Self type, you could use a bound TypeVar, like the class Base:
def __init__(self: B) -> None:
self._callbacks: list[Callable[[B, dict[str, Any]], None]] = []
def add_callback(self: B, callback: Callable[[B, dict[str, Any]], None]) -> None:
self._callbacks.append(callback) This approach generates a warning that Another solution is to avoid all generics and change the def class_call_me(self, instance: Base, some_dict: dict[str, Any]) -> None:
assert isinstance(instance, Derived)
print(instance, some_dict) |
Beta Was this translation helpful? Give feedback.
This is a great use case for the new
Self
type introduced in PEP 673.If you don't want to depend on the Self type, you could use a bound TypeVar, like the
B
that you defined above. However, you need to use it within a class or a function so it has an associated scope.