-
-
Notifications
You must be signed in to change notification settings - Fork 372
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
Typing with converters not working #519
Comments
That mypy bug appears to have been fixed, but I'm seeing something that looks like a similar problem with @berquist, did you get anywhere with a workaround? Or have you seen any other mypy issues that look relevant? (I'm struggling to find any) my minimal example with `dict`import attrs
@attrs.frozen
class C:
foo: dict = attrs.field(factory=dict, converter=dict)
C(foo={"a": 1}) $ mypy t.py
t.py:9: error: Argument "foo" to "C" has incompatible type "dict[str, int]"; expected "_VT | SupportsKeysAndGetItem[_KT, _VT] | SupportsKeysAndGetItem[str, _VT] | Iterable[tuple[_KT, _VT]] | Iterable[tuple[str, _VT]] | Iterable[list[str]] | Iterable[list[bytes]]" [arg-type]
Found 1 error in 1 file (checked 1 source file) $ python --version
Python 3.11.5
$ pip freeze
attrs==23.1.0
mypy==1.5.1
mypy-extensions==1.0.0
typing_extensions==4.7.1 |
I just ran into the same problem in an essentially analogous situation to @berquist's. (Hiya, Eric! Been a while, hope all is well.) I was able to satisfy mypy by wrapping the Toy example:
mypy output:
And no typing error on Python 3.11.7 on Debian WSL2 I don't know if this is a good or right way to address this, but it's semantically correct and makes mypy happy, sooooo.... ¯\_(ツ)_/¯ |
Hi @bskinn, you need to use a dedicate converter function for typing to work correctly, because The following code works with Python 3.12 and mypy 1.8: from typing import Any, Self, Type
import attrs
def to_int(v: Any) -> list[int]:
return [int(item) for item in v]
@attrs.define(kw_only=True)
class ClassConverter:
my_list: list[int] = attrs.field(converter=to_int)
@classmethod
def evolve_my_list(cls: Type[Self], new_list: list[int]) -> Self:
return cls(my_list=new_list)
@attrs.define(kw_only=True)
class LambdaConverter:
my_list: list[int] = attrs.field(converter=lambda v: list(v))
@classmethod
def evolve_my_list(cls: Type[Self], new_list: list[int]) -> Self:
return cls(my_list=new_list) |
Thanks, @sscherfke! I was wondering if a function with an explicit internal And you're right, for that toy example, (FWIW I also need runtime checks to be sure that the incoming argument is actually |
Using attrs 19.1.0 on Python 3.6.7,
gives
This may be related to python/mypy#5738, but the issue goes back as far as mypy 0.610.
The text was updated successfully, but these errors were encountered: