Skip to content

How to annotate class instance variable / bound method? #1648

Answered by Akuli
cuu508 asked this question in Q&A
Discussion options

You must be logged in to vote

I think the method isn't compatible with foo: Callable[[], bool], because that means foo is a read-write attribute, but mypy thinks of methods as read-only. For example, Child().foo = lambda: True gives an error. So Child doesn't have all of the functionality (writing foo) that every Parent instance is supposed to have.

Defining foo as a read-only attribute using @property works for me:

from typing import Callable, ClassVar

class Parent(object):
    @property
    def foo(self) -> Callable[[], bool] | bool:
        raise NotImplementedError

    def print_foo(self):
        print(self.foo() if callable(self.foo) else self.foo)

class Child(Parent):
    def foo(self) -> bool:
        return 

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by cuu508
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