Skip to content
Advertisement

Constants module, ran once

So I’m building a constants module that stores in dict some strings:

class Labels():
     Table = {"value1" : "value1" , ...}
     
     Table_2 = {"value1" : "value1" , ...}

Now to improve the module I want to retrieve the constants automatically, to reduce future maintenance. For this I use a method called get_constants() which returns a dict with the constants. So the module will be:

class Labels():
 Table = get_constants("1")

 Table_2 = get_constants("2")

Now to improve the performance I only want the methods to be ran once and not every time I need a constant. Any sugestions?

Advertisement

Answer

class Labels:
    Test = get_constants("1")
    Test2 = get_constants("2")

already does what you want. When you import the module the first time, the class Labels will be defined as part of defining the module, and as part of the process of defining the class, get_constants will be called and its return value will be saved as the value of each class attribute.

If you import the module more than once, the import system detects that it already exists (a reference to it is saved in sys.module), so it will not be defined a second time.

Later, when you access the class attributes, the dicts will already be there.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement