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!
Usually I do this:
File: constants.py
File: your_script.py
Now your constants are in one file and you can nicely import and use them.
Make a separate file
constants.py
, and put all globally-relevant constants in there. Then you canimport constants
to refer to them asconstants.SPAM
or do the (questionable)from constants import *
to refer to them simply asSPAM
orEGGS
.While we're here, note that Python doesn't support constant constants. The convention is just to name them in
ALL_CAPS
and promise not to mutate them.If you want to mess with nested constants and don't like dicts, I came up with this fun solution:
Ex:
Pros:
Cons:
Thoughts?
h/t to @hlzr and you guys for the original class idea
Put your constants into their own module:
Then import that module and use the constants:
The constants can be any value you like, I've shown integers here, but lists and dicts would work just the same.