[Python-ideas] Change magic strings to enums

Chris Angelico rosuav at gmail.com
Tue Apr 24 11:18:10 EDT 2018


On Wed, Apr 25, 2018 at 1:06 AM, Jacco van Dorp <j.van.dorp at deonet.nl> wrote:
> I
>
> 2018-04-24 15:58 GMT+02:00 Nick Coghlan <ncoghlan at gmail.com>:
>> On 24 April 2018 at 22:52, Jacco van Dorp <j.van.dorp at deonet.nl> wrote:
>>> 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.
>
>
> I guess we could add inconsistency as a con, then, since if the import
> system isn't working at places where you'd like to use the Enums (or
> even executing python code ?). This would mean that to the casual
> observer, it'd be arbitrary where they could be used instead.
>
> I wonder how many of these would be in places used by most people,
> though. I don't mind putting in some time to figure it out, but I have
> no idea where to start. Is there any easily searchable place where I
> could scan the standard library for occurences of magic strings ?

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.

ChrisA


More information about the Python-ideas mailing list