atbug
atbug

Reputation: 838

How to elegantly deal with global configuration in python package

I am writing a package that needs some global constant variables. Although constant, these variables can be changed before doing anything else. For example, nproc is the number of processors used. Since allowing global variables to change is dangerous, these variables should be locked after the package is imported.

The only method I come up with is to read a configuration file. However, as a python package (not an application), it is really weird that a configuration file is needed.

What's the correct way to handle such global configuration?

Edit:

it is important to notice that these variables is not something like pi that will never change. It can be changed but should be constant during the usage of this package.

Upvotes: 1

Views: 2593

Answers (2)

cdarke
cdarke

Reputation: 44444

You could create a class where the variables are set at initialisation time, and then use @property to declare a getter but not a setter. For example:

# For Python 2, inherit from object
# (otherwise @property will not work)

class MyGlobals():

    # Possibly declare defaults here
    def __init__(self, nproc, var1, var2):
        self.__nproc = nproc
        self.__var1  = var1
        self.__var2  = var2

    @property
    def nproc(self):
        return self.__nproc

    @property
    def var1(self):
        return self.__var1

    @property
    def var2(self):
        return self.__var2



myg = MyGlobals(4, "hello", "goodbye")

print(myg.nproc, myg.var1, myg.var2)

myg.nproc = 42

Gives:

4 hello goodbye
Traceback (most recent call last):
  File "gash.py", line 29, in <module>
    myg.nproc = 42
AttributeError: can't set attribute

The MyGlobals class would probably be placed in a module.

Upvotes: 0

Misachi
Misachi

Reputation: 81

If what you mean is separating variables from source code then maybe I'd suggest python-decouple. I hope this helps

Upvotes: 1

Related Questions