python-attrs / python-attrs/attrs
Typing fails when list of validators where one is custom and one is built in
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 5.8k
- Forks
- 480
- Avg merge
- 2h 15m
- Merged PRs (30d)
- 2
Description
Hi!
I am trying to add multiple validators to a field, which works fine as long as they are both from the attrs library or both written by me. When I mix them up mypy gives me an error. Am I doing something wrong here or is this an issue in the library? Here is a snippet to reproduce the issue:
from typing import Any
from attr import validators, Attribute
import attr
def is_not_empty(instance: Any, attribute: "Attribute[str]", value: str) -> Any:
if not value.strip():
raise ValueError("Is not empty")
@attr.s
class MyClass:
thing1: str = attr.ib(validator=[validators.max_len(10), is_not_empty]) # Mypy complains from this
thing2: str = attr.ib(validator=[validators.max_len(10)]) # This is fine
thing3: str = attr.ib(validator=[is_not_empty]) # Fine as well
thing4: str = attr.ib(validator=[is_not_empty, is_not_empty]) # Even this is fine
This is the error I get from mypy:
snippet.py:14: error: Argument "validator" has incompatible type "list[function]"; expected "Callable[[Any, Attribute[<nothing>], <nothing>], Any] | Sequence[Callable[[Any, Attribute[<nothing>], <nothing>], Any]] | None" [arg-type]
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 running the provided MyClass snippet with mypy and inspect attrs' validator type annotations and related typing tests. Done means a field combining validators.max_len(10) with a custom validator type-checks without the reported arg-type error, while the existing validator cases continue to work.
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
- 38/100