reportUninitializedInstanceVariable
: a false positive, and a false negative
#4687
Labels
as designed
Not a bug, working as intended
Describe the bug
reportUninitializedInstanceVariable
appears to emit false-positive errors for subclasses ofargparse.Namespace
, and does not emit errors where it should for classes decorated with@dataclass(init=False)
.To Reproduce
Create the following Python file in an empty directory, and run pyright on it:
Here is the output if you execute this Python file:
Expected behavior
No error should be reported for the
Args
class, because it is not expected for subclasses ofargparse.Namespace
to define__init__
methods. The primary reason (the only reason I know of) to subclassargparse.Namespace
is to create custom classes of which instances can be passed toargparse.ArgumentParser.parse_args
. It would be unidiomatic for subclasses ofargparse.Namespace
to define__init__
methods, since attributes onNamespace
objects are dynamically set in the call toargparse.ArgumentParser.parse_args()
. The only reason why the instance variable is being declared at all in the above example is to provide a modicum of type safety: otherwise, the inferred type ofargs.x
will beAny
, which is undesirable.The false positive can be suppressed with a
type: ignore
or apyright: ignore
, but this is pretty tedious, and very ugly, if you have anargparse.Namespace
subclass with many attributes:In python/typeshed#9793, we encountered this problem, and found a workaround for this issue: replace the
argparse.Namespace
with aninit=False
dataclass, since using a dataclass provides similar behaviour to subclassingargparse.Namespace
. In other words, we applied this diff:However, while this was a useful workaround to avoid the false-positive for
argparse.Namespace
subclasses, it illustrates thatreportUninitializedInstanceVariable
does not provide safety guarantees for dataclasses that don't have__init__
methods. This is a false negative in its own right: pyright should probably treat@dataclass(init=False)
classes just like ordinary classes that don't have__init__
methods when it comes to this check.The text was updated successfully, but these errors were encountered: