Skip to content

Cannot get attrs.Converter() with takes_self pass through mypy #1378

@nyoxi

Description

@nyoxi

I've been playing with the attrs.Converter() but I am unable to get it type-checked with mypy when using takes_self. Now I am not considering (the obvious) Unsupported converter, only named functions, types and lambdas are currently supported error. What I am struggling with is how to annotate the self. The following code:

def str2int(s: str|int, self_: "C") -> int:
    return int(s)

@attrs.define
class C:
    x: int = attrs.field(
        converter=attrs.Converter(str2int, takes_self=True)
    )

Leads to the following error:

error: No overload variant of "Converter" matches argument types "Callable[[str | int, C], int]", "bool"  [call-overload]
note: Possible overload variants:
note:     def [In, Out] Converter(self, converter: Callable[[In], Out]) -> Converter[In, Out]
note:     def [In, Out] Converter(self, converter: Callable[[In, AttrsInstance, Attribute[Any]], Out], *, takes_self: Literal[True], takes_field: Literal[True]) -> Converter[In, Out]
note:     def [In, Out] Converter(self, converter: Callable[[In, Attribute[Any]], Out], *, takes_field: Literal[True]) -> Converter[In, Out]
note:     def [In, Out] Converter(self, converter: Callable[[In, AttrsInstance], Out], *, takes_self: Literal[True]) -> Converter[In, Out]

Is this just my own ignorance or an issue with attrs or mypy?

I am using:

  • attrs 24.2.0
  • mypy 1.13.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions