Fix Python – Importing a long list of constants to a Python file


Asked By – Ken

In Python, is there an analogue of the C preprocessor statement such as?:

#define MY_CONSTANT 50

Also, I have a large list of constants I’d like to import to several classes. Is there an analogue of declaring the constants as a long sequence of statements like the above in a .py file and importing it to another .py file?


The file reads:

#!/usr/bin/env python
# encoding: utf-8


And reads:

#!/usr/bin/env python
# encoding: utf-8

import sys
import os

import Constants

class myExample:
    def __init__(self):
        self.someValueOne = Constants.MY_CONSTANT_ONE + 1
        self.someValueTwo = Constants.MY_CONSTANT_TWO + 1

if __name__ == '__main__':
    x = MyClass()


From the compiler,

NameError: “global name
‘MY_CONSTANT_ONE’ is not defined”

function init in myExample at line
13 self.someValueOne =
Constants.MY_CONSTANT_ONE + 1 copy
output Program exited with code #1
after 0.06 seconds.

Now we will see solution for issue: Importing a long list of constants to a Python file


Python isn’t preprocessed. You can just create a file


And importing them will just work:

import myconstants
print myconstants.MY_CONSTANT * 2

This question is answered By – Thomas K

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0