mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Add support for classmethod converters in attrs plugin

Open tombo315 opened this issue 6 years ago • 3 comments

import attr

@attr.s
class Bar:
    b = attr.ib()

    @classmethod
    def make(cls, one: int) -> 'Bar':
        return cls(one)


@attr.s
class Foo:
    a = attr.ib(converter=Bar.make)

error: Unsupported converter, only named functions and types are currently supported

Attrs is perfectly happy with make

>>> Foo(1)
Foo(a=Bar(b=1))

Granted the converter limitations are a known issue, I couldn't find this use-case covered anywhere.

tombo315 avatar Nov 08 '19 23:11 tombo315

Sounds like a reasonable idea.

ilevkivskyi avatar Nov 09 '19 10:11 ilevkivskyi

Surprised this doesn't already work. Class methods are the best way to construct many types, and are recommended by attrs. Is it especially hard to do this?

alexchandel avatar Jun 25 '23 04:06 alexchandel

Superficially looking at the code, it appears that every "case" has very specific code handling it. I haven't dug deep to understand why it's this way.

ikonst avatar Jun 26 '23 02:06 ikonst

If PEP 712 is accepted and implemented in mypy, this functionality will come "for free" because attrs uses dataclass_transform.

erictraut avatar Aug 11 '23 02:08 erictraut