code completion based on a hierarchy of properties

27 Views Asked by At

I want to create a class that has the following structure:

ClassName
    UpperLevel
        Element_A:
           val_1 = 'example'
        Element_B: Tuple(str, str)
        Element_C: Tuple(str, str)
    LowerLevel
        Element_D: Tuple(str, str)
        Element_E: Tuple(str, str)

so that I can type: ClassName.UpperLevel. and the IDE will recommend me Element_A, Element_B, Element_C.

I have the following:

class Element:
    def __init__(self, val_1, val_2):
        self.val_1: str = val_1
        self.val_2: str = val_2


class Example:
    def __init__(self):
        self.upper_level.Element_A = Element(r'example1', r'example2')
        self.upper_level.Element_B = Element(r'example1', r'example2')
        self.upper_level.Element_C = Element(r'example1', r'example2')

        self.lower_level.Element_D = Element(r'example1', r'example2')
        self.lower_level.Element_F = Element(r'example1', r'example2')

Note that the whole hierarchy is defined, meaning that I know all of the "levels" and "elements" beforehand, I do not need to create the dynamically in reality.

Why does this not work?
Do I need to have another class for Level?

1

There are 1 best solutions below

1
Guy On

To create a single Level class with different properties you can use SimpleNamespace

from types import SimpleNamespace


class Element:
    def __init__(self, val_1, val_2):
        self.val_1: str = val_1
        self.val_2: str = val_2


class Example:
    def __init__(self):
        upper_level = {'Element_A': Element(r'example1A', r'example2A'),
                       'Element_B': Element(r'example1B', r'example2B'),
                       'Element_C': Element(r'example1C', r'example2C')}
        self.upper_level = SimpleNamespace(**upper_level)

        lower_level = {'Element_D': Element(r'example1D', r'example2D'),
                       'Element_F': Element(r'example1F', r'example2F')}
        self.lower_level = SimpleNamespace(**lower_level)


example = Example()
print(example.upper_level.Element_A.val_1) # example1A
print(example.lower_level.Element_F.val_2) # example2F