Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add type hints for init argument in attrs class

Is there a way of separating the type hints for an init arg to the type hint of an attribute?

Please let me better explain myself by example. If in a regular class I'd do something like:

from math import ceil
from typing import Union
    
class Foo:
    def __init__(self, bar: Union[int, float]):
        self.bar: List[str] = ['example'] * ceil(bar)

What is the equivalent in attrs? Perhaps this?

import attr

@attr.s
class Baz:
    bar: List[str] = attr.ib(converter=lambda bar_: ['example'] * ceil(bar_))

I think not because when I tried the followings I got no matching result:

Baz.__init__.__annotations__  # Returned: {'return': None}
signature(Baz)  # Returned: <Signature (bar) -> None>


Foo.__init__.__annotations__  # Returned: {'bar': typing.Union[int, float]}
signature(Foo)  # Returned: <Signature (bar: Union[int, float])>

Is there a way of signaling attrs to these type hints into the init method it creates?

Tried also to search in the docs for a solution but maybe I missed it.

like image 588
NI6 Avatar asked Sep 01 '25 03:09

NI6


1 Answers

I think you’re hitting a bug that has been fixed recently-ish (what even is time at this point): https://github.com/python-attrs/attrs/pull/710

So, if I’m not mistaken, the 21.2.0 attrs release will fix your problem. You will have to add a type annotation to your converter though.

like image 89
hynek Avatar answered Sep 02 '25 16:09

hynek