Allow method assignment in body of type extending typing.NamedTuple
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
this currently works for non-namedtuple classes (both runtime and mypy-time):
class C:
x: int
__hash__ = object.__hash__
and it works for typing.NamedTuple at runtime:
from typing import NamedTuple
class C(NamedTuple):
x: int
__hash__ = object.__hash__
$ python3 -i t2.py
>>> c = C(1)
>>> hash(c)
-9223363269847169460
>>> object.__hash__(c)
-9223363269847169460
>>> tuple.__hash__(c)
3430019387558
but fails at type-checking time:
$ mypy --version && python --version --version
mypy 0.770
Python 3.6.8 (default, Oct 7 2019, 12:59:55)
[GCC 8.3.0]
$ mypy t2.py
t2.py:7: error: NamedTuple field name cannot start with an underscore: __hash__
t2.py:7: error: Invalid statement in NamedTuple definition; expected "field_name: field_type [= default]"
Found 2 errors in 1 file (checked 1 source file)
concrete usecase: __hash__ is in the critical path (~13%) for some code I'm writing and the extra layer of function which calls into object.__hash__'s overhead is significant:
# mypy is ok with this
from typing import NamedTuple
class C(NamedTuple):
x: int
def __hash__(self) -> int:
return object.__hash__(self)
I'd be happy to hack on this given some pointers :)
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
Reproduce the issue with the t2.py examples and run mypy on the file to confirm the two diagnostics for hash. Trace how NamedTuple class bodies distinguish fields from method assignments, then make the assignment type-check while preserving validation for invalid field declarations.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100