Ben Clifford
Ben Clifford

Reputation: 1418

mypy isn't detecting uninitialised attributes

This code checks with mypy's default invocation:


class A:

  myattr: str


class B(A):
  otherattr: str

but both A().myattr and B().myattr raise an attribute error: AttributeError: 'A' object has no attribute 'myattr'

Is there a way to get mypy to report this?

This is with Python 3.7.2, mypy 0.670

Upvotes: 1

Views: 725

Answers (2)

Ben Clifford
Ben Clifford

Reputation: 1418

I found I could get most of what I wanted (in my real world use case) by defining a Protocol rather than a regular superclass: mypy does detect uninitialised attributes defined there.

Upvotes: 1

Andrew McDowell
Andrew McDowell

Reputation: 2980

I think the answer is currently no.

There is some discussion about adding this as a feature here:

https://github.com/python/mypy/issues/4019

But doesn't look like there's been any updates recently. Perhaps worth commenting there if you have a strong use case for doing it, and what error you'd expect to see, i.e. would you want the error to be that you're accessing an initialised variable or that the variable isn't initialised in the class init or new constructors?

Upvotes: 1

Related Questions