close
The Wayback Machine - https://web.archive.org/web/20201127231711/https://github.com/python-attrs/attrs/issues/524
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How should I type my validators? #524

Open
jml opened this issue Apr 3, 2019 · 1 comment
Open

How should I type my validators? #524

jml opened this issue Apr 3, 2019 · 1 comment

Comments

@jml
Copy link

@jml jml commented Apr 3, 2019

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?

@oremanj
Copy link
Contributor

@oremanj oremanj commented Apr 3, 2019

Looks like Attribute is generic in the stubs but not in the runtime code. This isn't an issue that's unique to attrs, and there's an entry about it in the mypy manual: https://mypy.readthedocs.io/en/latest/common_issues.html#using-classes-that-are-generic-in-stubs-but-not-at-runtime

In this case the easiest fix is probably to escape the type hint by writing it in quotes: attribute: "Attribute[T]". Or if you're on 3.7+, consider from __future__ import annotations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
3 participants
You can’t perform that action at this time.