python-attrs / python-attrs/attrs

Typing issue (stubs) for converter with default

Open
#518 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Typing
Dominant language
Python
Stars
5.8k
Forks
480
Avg merge
2h 15m
Merged PRs (30d)
2

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the issue with the provided Python example and mypy 0.670, then inspect the attrs stubs involved in attr.ib typing for converter and default. Done means the example no longer produces the reported assignment and converter errors, with the corrected behavior covered by a regression test.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.