Duplicate class members in pyreverse UML class diagram due to type-hinting

228 Views Asked by At

I'm using pyreverse to create UML class diagrams for my code base. On classes which are type-hinted using class variables (recommended according to (https://stackoverflow.com/a/59784221/14901431) the members appear twice since they are initialized in the init method.

Here is an example code:

class Example:
    var_a: int
    var_b: str
    
    def __init__(self, var_a, var_b) -> None:
        self.var_a = var_a
        self.var_b = var_b

This is the resulting UML diagram:

enter image description here

I have not seen any solution for this in the documentation. Any ideas on how to keep working with this type-hinting method and get UML diagrams without duplicates?

1

There are 1 best solutions below

0
Christophe On

This is a known issue of pyreverse:

  • Issue #8046 -> Opened in January, and still unresolved
  • Issue #8189 -> Opened in February, and still unresolved ==> EDIT: corrected on 24 September 2023.

There are two issues, depending on whether a value is assigned at class level or there is only a type annotation at class level. The co-author of pyreverse explains in the issue log the subtle difference: the value assignment at class level would cause two pair of variables exist: one at instance level and one at class level. This is why the first issue is categorised as enhancement and the second as bug.

Once the issues are resolved, Your code should produce a class with only two instance variables and the right annotation, whereas the following code would produce duplicate variables, but one of each duplicate would be marked as static (class variable):

class Example:
    var_a: int = 5 
    var_b: str = "six"
    
    def __init__(self, var_a, var_b) -> None:
        self.var_a = var_a
        self.var_b = var_b
        
    def test(self):
        print (self.var_a, self.var_b)
    
    @classmethod
    def classtest(cls):
        print (cls.var_a, cls.var_b)

The bad news is that there seem currently to be no ongoing work to solve those issues. So, meanwhile, the the workaround would probably be to comment out the definition at class level and embedded the type annotation in the init. I agree that this is far from ideal.

EDIT: Good news! The bug was corrected in September 2023. Your code now generates the correct diagram (I just tested it):

a class with no duplicate members

The enhancement is still open. The other case now generates a diagram without duplicates, not taking into account the subtitlity of Python's expected class instance.