Class with only `__init_subclass__` raises `attr-defined`
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Hello! I dug around the issue tracker to try and find any references to this kind of issue, but didn't find anything relevant. Apologies if this is a duplicate, but it seemed like it was unique enough for a report.
Bug Report
When adding a type hint to a mixin class's function, an error is raised. Previously, the function was untyped so was not being evaluated (i.e. not in --strict mode).
To Reproduce
I boiled it down to a simpler example. The contents of main.py:
class HasEvents:
def __init_subclass__(cls, /, **kwargs):
super().__init_subclass__(**kwargs)
cls.foo = [] # this type doesn't appear to matter
return cls
def record_event(self, *, some_other_arg: str):
event = self.foo.append(some_other_arg) # <== error here
# do something else with `event`...
return event
https://mypy-play.net/?mypy=1.2.0&python=3.11&gist=90a1e568fd9630201f21c28f94167138
https://gist.github.com/mypy-play/90a1e568fd9630201f21c28f94167138
Actual Behavior
main.py:8: error: "HasEvents" has no attribute "Event" [attr-defined]
I found that changing __init_subclass__ to __init__ passes.
Your Environment
I tried a variety of Python and mypy versions from the playground to see if it was new, and went back to Python 3.7 and mypy 0.750 - so versions, flags and command line options have been isolated from the equation.
Pull request part of the greater project, where I disabled the check: pypi/warehouse@bc76ecf (#13593)
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 with the minimal main.py reproduction and the behavior of init_subclass when checking self.foo in record_event. Trace the relevant type-checking path and compare it with the working init variant. Done means the reproduced case no longer reports an attr-defined error while existing checks remain correct.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100