【问题标题】:Pyreverse: how to add return types for methods and properties when generating uml reports?Pyreverse:生成 uml 报告时如何为方法和属性添加返回类型?
【发布时间】:2019-06-16 11:33:25
【问题描述】:

我正在使用pyreversegraphviz 成功地从Python 模块生成UML 报告。我可以看到pylint 足够聪明,可以针对某些属性说出输出数据类型是什么,但不是针对所有属性,也没有针对方法。

源代码:

def get_int():
    return 555

def get_math_int():
    return math.pow(2, 5)

class ClassFoo(object):
    def __init__(self, x, y):
        self.attr1 = "hello"
        self.attr2 = get_int()
        self.attr3 = get_math_int()

    def spam(self):
        return 77

class ClassBar(object):
    def __init__(self, x, y):
        self.attr4 = "hello"

    def spam(self):
        return 99

输出pdf

我已经查看了pylint docstyle checker,但它看起来与我的问题无关。

是否可以通过注释、文档字符串或其他方式使用类型提示显式指定每个方法和属性将返回的数据类型,以便它们显示在 pdf 报告中?

【问题讨论】:

    标签: python uml graphviz pylint pyreverse


    【解决方案1】:

    在 Python 3.5 或更高版本中,您可以使用内置的typings module;在 Python 2 或更早版本的 Python 3 中,mypy 是您唯一的选择。一个好的 IDE(例如 PyCharm)实际上会告诉你如果你所有的类都被很好的注释,你是否犯了错误。

    提取类型信息非常痛苦,但首先要读取具有类型提示的类的__annotations__ 属性(请参阅PEP-0484)。

    您的示例,完全使用 Python 3.5 或更高版本进行类型提示:

    from typing import Any
    
    def get_int() -> int:
        return 555
    
    def get_math_int() -> int:
        return math.pow(2, 5)
    
    class ClassFoo(object):
        def __init__(self, x: Any, y: Any):
            self.attr1 = "hello"
            self.attr2 = get_int()
            self.attr3 = get_math_int()
    
        def spam(self) -> int:
            return 77
    
    class ClassBar(object):
        def __init__(self, x: Any, y: Any):
            self.attr4 = "hello"
    
        def spam(self) -> int:
            return 99
    

    【讨论】:

    • 对不起,如果我不清楚。这是否有助于 pyreverse 在 pdf 报告中添加方法和属性的返回类型?
    • 不幸的是,根据这个问题不会很快:github.com/PyCQA/pylint/issues/1548。长期做到这一点的最好方法是在你开始依赖它们时添加类型提示,而不是尝试对类型进行逆向工程,尤其是现在 Python 能够更明确地说明类型(至少对于工具的好处)。
    • 感谢您发布问题!我明白你的意思,说得好。将 pyreverse 生成的 pdf 报告中的类型用于参考目的真是太好了。
    猜你喜欢
    • 1970-01-01
    • 2021-10-28
    • 2020-12-17
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    • 2011-02-03
    相关资源
    最近更新 更多