Skip to content

Derived class type error on Callable #3358

Answered by erictraut
gwww asked this question in Q&A
Discussion options

You must be logged in to vote

This is a great use case for the new Self type introduced in PEP 673.

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 B that you defined above. However, you need to use it within a class or a function so it has an associated scope.

class Base:
    def __init__(self: B) -> None:
        self._callbacks: list[Callable[[B, dict[str, Any]], None]] = []

    def add_callback(self: 

Replies: 1 comment 4 replies

Comment options

You must be logged in to vote
4 replies
@gwww
Comment options

@erictraut
Comment options

@gwww
Comment options

@erictraut
Comment options

Answer selected by gwww
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants