Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Best/Cleanest way to define constant lists or dictionarys

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!

like image 360
TSmith Avatar asked Jun 20 '12 01:06

TSmith


People also ask

How do you define a constant 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.

Is there constant in Python?

Python doesn't have constants.

Why does Python not 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".


2 Answers

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.

like image 187
Ned Batchelder Avatar answered Oct 26 '22 19:10

Ned Batchelder


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.

like image 29
Blender Avatar answered Oct 26 '22 20:10

Blender