Python – Does it make sense to use string constants in Python instead of string literals as keys

programming practicespython

There is a dictionary in my class with informative, short string constants as keys that identify certain parts of the solution, like "velocity", "death_star_power_output". My colleague suggested that I use VELOCITY="velocity" and DEATH_STAR_POWER_OUTPUT="death_star_power_output" to index into this dictionary throughout the program, because it's the practice.

While I know such practices from other programming languages, where they serve a pragmatic purpose – that is to fail-fast in case of misspelling of the string – in Python it's the same one way or the other. Both:

value = dictionary["death_star_powder_output"]

and

DEATH_STAR_POWER_OUTPUT="death_star_power_output"
[...]
value = dictionary[DEATH_STAR_POWDER_OUTPUT]

will fail at the same time. Please notice the misspelling of POWER as POWDER. Is there some official guideline pertaining to this kind of practice in Python?

Best Answer

It's not as useful to eschew string literals in Python as it is in other languages, because Python enforces no strict predeclaration of identifiers, but it is still useful.

It's true that if you misspell a constant name in Python, you might not get a warning until run-time. But sufficiently clever analysers can still detect that you are using a variable that doesn't seem to have a declaration, or that you are declaring a constant that doesn't seem to be used. And since tooling support can only become smarter over time, and tool support changes much faster than language standard, it pays to obey conventions that enable better error checking whether it's already there or not.

Related Topic