Search code examples
pythonpython-3.xconstantsglobal

Global Constants in Python3


I have some code which was written in Python2.7 and I need to convert it to Python3. My problem is that I used this https://code.activestate.com/recipes/65207-constants-in-python/ to create a function which stored all of my constants and make them available globally, it also prevented them from being changed. That code does not work in Python3, what is the best replacement? Thanks Mick Here is an example that runs in 2.7 but fails if I change the print statements and run in 3

# const.py
class _const:
    class ConstError(TypeError): pass
    def __setattr__(self,name,value):
        if self.__dict__.has_key(name):
            raise self.ConstError, "Can't rebind const(%s) look at the log, it should only be set in constants.py"%name
        self.__dict__[name]=value
import sys
sys.modules[__name__]=_const()


#constants.py
import const as gc
gc.PASS = 0
gc.FAIL = -1
gc.INT_VAL = 1234
gc.STR_VAL = 'This is a string'

# test.py
import const as gc    # global constants class
from constants import *   # constants values
print 'INT_VAL is ',  gc.INT_VAL
print 'STR_VAL is ',  gc.STR_VAL

Solution

  • I quickly ported the old const.py. Be aware that it won't work if it's not in a file named const.py!

    class _const:
        class ConstError(TypeError): pass
        def __setattr__(self,name,value):
            if name in self.__dict__:
                raise self.ConstError(f"Can't rebind const({name})")
            self.__dict__[name]=value
    import sys
    sys.modules[__name__]=_const()
    

    Changes:

    • added parentheses to ConstError constructor in raise
    • changed string formatting to f-string (unnecessary change, can be reverted if needed)
    • replaced __haskey__ with in