python-attrs / python-attrs/attrs
How should I type my validators?
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 5.8k
- Forks
- 480
- Avg merge
- 2h 15m
- Merged PRs (30d)
- 2
Description
I'm trying to add some types to some attrs-using code that uses validators.
Here's a minimal example of such:
from typing import Any, TypeVar
from attr import Attribute
T = TypeVar("T")
def my_validator(instance: Any, attribute: Attribute[T], value: T) -> Any:
pass
The type is derived by looking at attr/validators.pyi and attr/__init__.pyi.
The code type-checks fine, but fails to execute:
jml@hope:~
$ mypy --strict attribute.py
jml@hope:~
$ python attribute.py
Traceback (most recent call last):
File "attribute.py", line 8, in <module>
def my_validator(instance: Any, attribute: Attribute[T], value: T) -> Any:
TypeError: 'type' object is not subscriptable
If I remove the [T], the opposite happens:
jml@hope:~
$ mypy --strict attribute.py
attribute.py:8: error: Missing type parameters for generic type
jml@hope:~
$ python attribute.py
What type should my validators have?
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 comparing the generic declarations in attr/validators.pyi and attr/init.pyi with the runtime Attribute behavior shown by attribute.py. Run both mypy --strict attribute.py and python attribute.py; done means validators have types that satisfy strict checking without raising the reported runtime TypeError.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- developer-experience
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100