Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing a long list of constants to a Python file

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?

Edit.

The file Constants.py reads:

#!/usr/bin/env python # encoding: utf-8 """ Constants.py """  MY_CONSTANT_ONE = 50 MY_CONSTANT_TWO = 51 

And myExample.py reads:

#!/usr/bin/env python # encoding: utf-8 """ myExample.py """  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() 

Edit.

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.

like image 596
SK9 Avatar asked Jun 14 '11 12:06

SK9


People also ask

Where do you keep constants in Python?

Assigning value to constant in Python In Python, constants are usually declared and assigned in a module. Here, the module is a new file containing variables, functions, etc which is imported to the main file. Inside the module, constants are written in all capital letters and underscores separating the words.

Can you import all in Python?

You can import all the code from a module by specifying the import keyword followed by the module you want to import. import statements appear at the top of a Python file, beneath any comments that may exist. This is because importing modules or packages at the top of a file makes the structure of your code clearer.


1 Answers

Python isn't preprocessed. You can just create a file myconstants.py:

MY_CONSTANT = 50 

And importing them will just work:

import myconstants print myconstants.MY_CONSTANT * 2 
like image 196
Thomas K Avatar answered Sep 25 '22 15:09

Thomas K