Support override for `attr-defined` errors (something like a promise to mypy that the attr is defined going forward)
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Feature
There are cases where mypy spits out an attr-defined error when accessing bar.foo; these can be ignore per-use with a # type: ignore[attr-defined], however, there doesn't currently seem to be a way to tell mypy that bar does indeed define foo.
In this case, it'd be nice if there was a way to tell mypy that bar does define foo, so that bar.foo can be used without spamming # type: ignore[attr-defined] comments everywhere.
How this is done I don't have an opinion about, but for example, it could be something like: # type: bar.foo: int.
Pitch
There are multiple useful cases of this:
-
Although this is not the primary motivation, it would cover the case brought up here: https://github.com/python/mypy/issues/15085
-
This could allow type hinting for attributes added after a class definition. One example would be for users who enjoy using a
TRACElog level with the logging module. That is, if a user adds aTRACElogging level to theloggingmodule such as shown here: https://stackoverflow.com/questions/2183233/how-to-add-a-custom-loglevel-to-pythons-logging-facility
In this instance, this would allow use oflogging.traceandlogging.TRACEwithout requiring#type: ignore[attr-defined]used at every occurrence.
In general, this handles the case where you have something like:
class A:
pass
A.B = "foo" # Some comment to promise mypy that A has an attr named B defined
- Additionally, this can allow users to better handle when 3rd party libraries do not play nice with
mypy. For example:
from cryptography.hazmat.primitives.serialization import load_ssh_private_key
This gives an attr-defined warning, although this import statement works just fine.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by tracing how mypy reports attr-defined diagnostics and handles per-use type: ignore[attr-defined] comments. Define the proposed promise syntax and its scope using the examples in the issue, then add tests showing that promised attributes no longer produce repeated errors while unrelated missing attributes still do.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100