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

Typing issue (stubs) for converter with default #518

Open
Funth0mas opened this issue Mar 13, 2019 · 1 comment
Open

Typing issue (stubs) for converter with default #518

Funth0mas opened this issue Mar 13, 2019 · 1 comment
Labels
Bug Typing Typing/stub/Mypy/PyRight related bugs.

Comments

@Funth0mas
Copy link

When using attr.ibute with both converter and default, wrong expectations is applied on default type (with mypy == 0.670). Mypy dev say it's an issue in attr stubs.

The valid code

import attr
import typing

def to_int(x: typing.Any) -> int:
    return int(x)

@attr.s
class C:
    a: int = attr.ib(converter=to_int, default="1")

results in:

main.py:9: error: Incompatible types in assignment (expression has type "str", variable has type "int")
main.py:9: error: Argument "converter" has incompatible type "Callable[[Any], int]"; expected "Optional[Callable[[Any], str]]"

The result is not right, because the converter is applied on default value as well.

Of course the hotfix is to convert the default value manually.

@ljluestc
Copy link

import attr
import typing

def to_int(x: typing.Any) -> int:
return int(x)

@attr.s
class C:
a: int = attr.ib(converter=to_int, default="1") # Manually specify the default as a string
a: int = attr.ib(converter=to_int, default=1) # Manually specify the default as an integer

Example usage

obj1 = C() # 'a' will have a default value of 1 as an integer
obj2 = C("42") # 'a' will be converted to an integer using the converter

print(obj1.a)
print(obj2.a)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Typing Typing/stub/Mypy/PyRight related bugs.
Projects
None yet
Development

No branches or pull requests

4 participants