【问题标题】:How do I type hint a list of types for a composite class in python?如何在python中键入提示复合类的类型列表?
【发布时间】:2019-07-08 16:27:52
【问题描述】:

由于一些我无法控制的架构原因,我经常使用并希望完整代码完成的对象是在源代码中已经存在的静态功能之上的几个功能的动态组合。

import lgb.reqs.plan
# Various imports which dynamically extend the smallform
import lgb_extensions.water_extras
import lgb_extensions.toolkit_extras

d = c.req[0]  # type: lgb.reqs.plan.smallform 
d = d  # type: lgb_extensions.water_extras.common
d = d  # type: lgb_extensions.toolkit_extras.common

# Now I get the autocomplete on d as I type "d."
d.

我发现重新分配d 方法效果很好,但感觉不对。有没有办法用元组或其他东西输入提示?我试过了,还是不明白。

我发现 jupyter notebook 非常适合自动补全,如果我真的需要探索未知代码库,我会跳入 ipython 或 notebook 会话,但在这种情况下,我对代码非常熟悉基础,只是希望自动完成功能更好,因为我永远记不起什么叫什么。如果这很重要,我主要在 pycharm 或 atom 中。上面的解决方案已经解决了我的问题如果只有几个扩展,但是当我有 10 个扩展对象时它不起作用。在我的常用案例中,我有大约 20 个东西扩展了我想要自动完成的对象。

【问题讨论】:

    标签: python pycharm atom-editor type-hinting


    【解决方案1】:

    您也许可以在此处使用Union。这更多是因为一个名称在不同的情况下可以包含不同的类型。

    例如。

    from typing import Union
    
    a = f() # type: Union[str, int]
    d. # now get autocompletion for str and int from IDEs
    

    【讨论】:

    • 丑陋,要实现的那一行大约有 800 个字符,但效果很好。太棒了,谢谢。
    猜你喜欢
    • 2023-03-28
    • 2022-10-04
    • 2017-03-28
    • 1970-01-01
    • 2020-02-28
    • 2021-08-03
    • 2021-06-06
    • 2022-11-16
    • 2021-12-15
    相关资源
    最近更新 更多