First time user on stack overflow and I'm excited to be here.
INTRO: I recently began the magical adventure into the world of Python programming - I love it. Now everything has gone smoothly in my awkward transition from C, but I'm having trouble creating something which would be synonymous to a HEADER file (.h).
PROBLEM: I have medium sized dictionaries and lists (about 1,000 elements), lengthy enums, and '#defines' (well not really), but I can't find a CLEAN way to organize them all. In C, I would throw them all in a header file and never think again about it, however, in Python that's not possible or so I think.
CURRENT DIRTY SOLUTION: I'm initializing all CONSTANT variables at the top of either the MODULE or FUNCTION (module if multiple functions need it).
CONCLUSION: I would be forever grateful if someone had come up with a way to CLEANLY organize constant variable's.
THANK YOU SO MUCH!
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.
Python doesn't have constants.
Why are class-level constants discouraged? "There's no equivalent for constants in Python, as the programmer is generally considered intelligent enough to leave a value he wants to stay constant alone".
Put your constants into their own module:
# constants.py RED = 1 BLUE = 2 GREEN = 3
Then import that module and use the constants:
import constants print "RED is", constants.RED
The constants can be any value you like, I've shown integers here, but lists and dicts would work just the same.
Usually I do this:
File: constants.py
CONSTANT1 = 'asd' CONSTANT_FOO = 123 CONSTANT_BAR = [1, 2, 5]
File: your_script.py
from constants import CONSTANT1, CONSTANT_FOO # or if you want *all* of them # from constants import * ...
Now your constants are in one file and you can nicely import and use them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With