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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With