[Python-ideas] Change magic strings to enums

Steven D'Aprano steve at pearwood.info
Tue Apr 24 13:19:02 EDT 2018


On Wed, Apr 25, 2018 at 01:18:10AM +1000, Chris Angelico wrote:

> First, though, can you enumerate (pun intended) the problems with
> magic strings? You list "no magic strings" as a benefit, as if it's
> self-evident; I'm not sure that it is.

It shouldn't be self-evident, because the use of strings in the warnings 
module doesn't match the most common accepted meaning of magic strings.

https://en.wikipedia.org/wiki/Magic_string

Possibly Jacco was thinking of "magic constants":

https://en.wikipedia.org/wiki/Magic_number_%28programming%29#Unnamed_numerical_constants

(although in this case, they're text constants, not numerical). But this 
seems like a fairly benign example to my eyes: the strings aren't likely 
to change their values. As discussed here:

https://softwareengineering.stackexchange.com/questions/221034/usage-of-magic-strings-numbers

not all uses of literals are harmful.

A fairly lightweight change would be to add named constants to the 
warning module:

ERROR = 'error'

etc, and refactor the module to use the named constants instead of 
hard-coded strings. I'm surprised that it doesn't already do that.

That would be 100% backwards compatible, without the cost of importing 
and creating enums, but allow consumers of the warnings module to 
inspect it and import symbolic names if they so choose:

from warnings import ERROR


By the way, I notice that the warnings module makes heavy use of assert 
to check user-supplied input. That's dangerous since asserts can be 
disabled, and also poor API design: it means that even if the asserts 
trigger on error (which isn't guaranteed), they raise the wrong kind of 
exception: AssertionError instead of TypeError for bad types or 
ValueError for bad values.


-- 
Steve


More information about the Python-ideas mailing list