1

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.

atbug
  • 818
  • 6
  • 26
  • Why not use environment variables? If the environment variables are not set then perhaps use sensible defaults or something – loganasherjones Mar 08 '17 at 12:44
  • Possible duplicate of [how to set global const variables in python](http://stackoverflow.com/questions/18224991/how-to-set-global-const-variables-in-python) – Tzomas Mar 08 '17 at 12:45

2 Answers2

1

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

Misachi
  • 81
  • 3
  • 8
0

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.

cdarke
  • 42,728
  • 8
  • 80
  • 84