[Python-ideas] Change magic strings to enums

Nick Coghlan ncoghlan at gmail.com
Tue Apr 24 09:58:19 EDT 2018


On 24 April 2018 at 22:52, Jacco van Dorp <j.van.dorp at deonet.nl> wrote:
> 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.

"It's cleaner" isn't a user problem though. The main justification for
using enums is that they're easier to interpret in log messages and
expection tracebacks than opaque constants, and that argument is much
weaker for well-chosen string constants than it is for other constants
(like the numeric constants in the socket and errno modules).

For backwards compatibility reasons, we'd want to keep accepting the
plain string versions anyway (implicitly converting them to their enum
counterparts).

At a less philosophical level, many of the cases where we use magic
strings are in code that has to work even when the import system isn't
working yet - that's relatively straightforward to achieve when the
code is only relying on strings with particular contents, but *much*
harder if they're relying on a higher level type like enum objects.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list