pythonumlgraphvizpylintpyreverse

Pyreverse: how to add return types for methods and properties when generating uml reports?


I am successfully generating UML reports from Python modules using pyreverse and graphviz. I can see that pylint is smart enough to say for some properties what is the output data type, but not for all and none for the methods.

The source code:

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

The output pdf

enter image description here

I have looked into pylint docstyle checker but it looked irrelevant for my problem.

Is it possible to explicitly specify using either a type hint through comment, docstring or somehow else what data type will be returned by each method and attribute so that they will be shown in the pdf report?


Solution

  • In Python 3.5 or later, you could use the built-in typings module; in Python 2 or older versions of Python 3, mypy is your only option. A good IDE (PyCharm, for example), will actually tell you if you're making errors if all of your classes are well-annotated.

    Extracting type information is pretty painful, but starts with reading the __annotations__ attribute on classes that have type hints (see PEP-0484).

    Your example, fully type-hinted using Python 3.5 or later:

    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