[Python-ideas] Change magic strings to enums

Jacco van Dorp j.van.dorp at deonet.nl
Tue Apr 24 08:52:23 EDT 2018


A bit ago I was reading some of the python docs (
https://docs.python.org/3.6/library/warnings.html ), the warning
module, and I noticed a table of magic strings.

I can think of a few other places where magic strings are used - for
example, string encoding/decoding locales and strictness, and probably
a number of other places.

Since Python 3.4, We've been having Enums.

Wouldn't it be cleaner to use enums by default instead of those magic
strings ? for example, for warnings filter actions, (section 29.5.2),
quite near the top of the page.

You could declare in the warnings module:

class FilterAction(Enum):
    Error = 'error'
    Ignore = 'ignore'
    Always = 'always'
    Default = 'default'
    Module = 'module'
    Once = 'once'

And put in the docs that people should use enums. For as long as a
transition period would last, any entrypoint into the module where
currently the magic string is used, you could transform it with the
single line:
 action = FilterAction(action)  # transforms from old magic string to
shiny new enum member
Then whenever enough people have shifted/4.0 comes around, the string
argument version can be deprecated.

Pro's
 - no magic strings
 - more clarity
 - easier to get all possible values with for example type checking
editors (because of the type annotation)

Con's :
 - implementation effort (as long as the modules are in pure Python, I
could perhaps help. Im not to confident about my C skills tho)

Backwards compatibility wouldn't be an issue because of the easy
transformation from the old string as long as we use those string as
the enum values.

ofc, precise names of enums/members is up for debate. I personally
prefer the above version to ALLCAPS, but that might be my comparitive
lack of C experience. These named constants are generally done in all
caps, but they're also often because of lack of a simple enum class.

I tried to search for this, but couldn't find any discussion about it.
Apologies if this has been rejected before.

Jacco


More information about the Python-ideas mailing list