-
Suppose I have a class that allows a field to be either a boolean or a bound method returning a boolean: from __future__ import annotations
from typing import Callable
class Parent(object):
foo: Callable[[], bool] | bool
def print_foo(self):
print(self.foo() if callable(self.foo) else self.foo)
class Child(Parent):
def foo(self) -> bool:
return True
class Child2(Parent):
foo = False
Child().print_foo()
Child2().print_foo()
# prints:
# True
# False In the above example, the subclass
If I remove the union, and allow foo to only be a bound method, mypy is happy: # This works
class Parent(object):
foo: Callable[[], bool]
class Child(Parent):
def foo(self) -> bool:
return True But as soon as I add What am I doing wrong, and how can I fix the type annotation? For context, this is a toy example, the actual issue is in django-stubs here: typeddjango/django-stubs#1755 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I think the method isn't compatible with Defining 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 True
class Child2(Parent):
foo = False
Child().print_foo()
Child2().print_foo() This seems to be somewhat mypy-specific. If I check the same code with pyright, I get errors. |
Beta Was this translation helpful? Give feedback.
I think the method isn't compatible with
foo: Callable[[], bool]
, because that meansfoo
is a read-write attribute, but mypy thinks of methods as read-only. For example,Child().foo = lambda: True
gives an error. SoChild
doesn't have all of the functionality (writingfoo
) that everyParent
instance is supposed to have.Defining
foo
as a read-only attribute using@property
works for me: