In this post, we will see how to resolve PyCharm incorrectly assumes object is instance of BaseClass after calling issubclass()
Question:I am running this test with Python 3.10.9 and PyCharm 2022.2.1 (Community Edition). This is an issue with PyCharm, not Python itself.
In my example code, I use a generator method that takes in a class type as an argument, and constructs the class. I want to make sure the class type that is passed is a subclass of
BaseClass, so I use
issubclass(class_type, BaseClass), PyCharm now thinks that the constructed object is a
BaseClassobject. The constructor call has a warning because it is looking at the wrong constructor, and the
new_subclass.barcall in Main has a warning because it doesn’t see
BaseClass, even though it is a
SubClassobject as verified by the Python output.
Does anybody know why this would be happening? It seems like a PyCharm error to me, I have no idea why simply calling
issubclasswould make PyCharm assume the object is the BaseClass. Without the call to
issubclass, PyCharm has no issues understanding that it is an instance of
Thanks in advance for any help.
Best Answer:I suspect it’s not really a bug, but a side effect of not providing any type hints. PyCharm starts with the assumption that
class_typeas the type
Any, meaning any value could be assigned to the name and that value can be used with any operation, regardless of type.
So what does PyCharm do with the
assertstatement? It tries to apply type narrowing, assigning
class_typea more specific type than
Anywhen the assertion is true. The most general type that makes the assertion
BaseClass, so in the code that follows the assertion, it assumes that
class_typehas the type
Any. (If the assertion failed, it doesn’t need to assume anything, because none of the following code would execute.)
Once the type has been narrowed to
BaseClass, the rest of the warnings are self-explanatory.
BaseClassisn’t provide the argument
BaseClass.__init__expects, and direct instances of
At runtime, everything is fine because there are no assumptions about the type of
class_type; it is
SubClass, and so the code executes as expected.
That said, I don’t have PyCharm installed to test.
mypydoes nothing, which leads me to suspect that PyCharm is being overly aggressive in performing type narrowing compared to
mypy. What happens if you provide explicit type hints, for example,
assertstatement, but since the type hint already implies that
Tcould be bound to
BaseClassor a subclass of
BaseClass, no type narrowing should be necessary or applied.
If you have better answer, please add a comment about this, thank you!