Skip to content

How should I type my validators? #524

@jml

Description

@jml

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    DocumentationTypingTyping/stub/Mypy/PyRight related bugs.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions