【问题标题】:Add type hints for init argument in attrs class在 attrs 类中为 init 参数添加类型提示
【发布时间】:2021-05-24 18:34:41
【问题描述】:

有没有办法将 init arg 的类型提示与属性的类型提示分开?

请让我通过例子更好地解释自己。如果在普通课堂上,我会做这样的事情:

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

attrs 中的等价物是什么?也许是这个?

import attr

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

我认为不是因为当我尝试以下操作时我没有得到匹配的结果:

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])>

有没有办法将这些类型提示的 attrs 信号发送到它创建的 init 方法中?

还尝试在docs 中搜索解决方案,但也许我错过了。

【问题讨论】:

    标签: python python-attrs


    【解决方案1】:

    我认为您遇到了一个最近修复的错误(此时甚至是时间):https://github.com/python-attrs/attrs/pull/710

    所以,如果我没记错的话,21.2.0 attrs 版本将解决您的问题。不过,您必须向转换器添加类型注释。

    【讨论】:

      猜你喜欢
      • 2020-02-28
      • 2023-04-06
      • 2019-02-20
      • 2011-11-09
      • 2016-01-27
      • 2019-02-25
      • 2022-10-18
      • 2017-02-03
      • 1970-01-01
      相关资源
      最近更新 更多