Unexpected behavior regarding variable that can contain instance of base class or subclass #8144
-
Code sample in pyright playground # pyright: strict
class BaseClass:
pass
class SubClass(BaseClass):
pass
foo = SubClass()
def fn(bar: BaseClass) -> None:
baz: BaseClass = foo or bar
reveal_type(baz)
if isinstance(baz, SubClass):
print("hello") In the example above, I find this confusing, because when I see I'm trying to enable |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I think I figured it out - I think that the issue in my specific situation is that (in the version of the code I'm actually working on) |
Beta Was this translation helpful? Give feedback.
I think I figured it out -
foo
is truthy, and pyright knows thatfoo or bar
will always evaluate tofoo
, which is an instance ofSubClass
. Whoops!I think that the issue in my specific situation is that (in the version of the code I'm actually working on)
foo
can actually beSubClass | None
in practice, and is mis-annotated as beingSubClass
because we don't have very many pyright checks set up yet. Updating its annotation toSubClass | None
resolves thereportUnnecessaryIsInstance
error :)