[Python-Dev] other "magic strings" issues

Barry Warsaw barry at python.org
Fri Nov 7 12:17:05 EST 2003

On Fri, 2003-11-07 at 11:08, Alex Martelli wrote:
> From Barry's discussion of the problem of "magic strings" as arguments to 
> .encode / .decode , I was reminded of a blog entry,
> http://www.brunningonline.net/simon/blog/archives/000803.html
> which mentions another case of "magic strings" that might perhaps be
> (optionally but suggestedly) changed into more-readable attributes (in
> this case, clearly attributes of the 'file' type): mode arguments to 'file'
> calls.  Simon Brunning, the author of that blog entry, argues that
> myFile = file(filename, 'rb')
> (while of course we're going to keep accepting it forever) is not quite as 
> readable and maintainable as, e.g.:
> myFile = file(filename, file.READ + file.BINARY)
> Just curious -- what are everybody's feelings about that idea?  I'm
> about +0 on it, myself -- I doubt I'd remember to use it (too much C
> in my past...:-) but I see why others would prefer it.

I'm with you: too much muscle memory to probably use it.  But I still
think it's a good idea, with one caveat.  A problem with constants like
this, especially if they're mapped to integers, is that printing them is

>>> from socket import *
>>> print AF_UNIX
>>> from errno import *
>>> print EEXIST

If your memory is as bad as mine, how many times have /you/ typed
errno.errorcode[17]?  :)

I would love it if what happened really was something like:

>>> from socket import *
>>> print AF_UNIX
>>> from errno import *
>>> print EEXIST

Now, I have an enum metaclass, originally ripped from Jeremy, but with a
few nice additions and modifications of my own, which would get us
closer to this.  It allows you to define an enum like:

>>> class Family(enum.Enum):
...  AF_UNIX = 1
...  AF_INET = 2
...  # ...
>>> Family.AF_UNIX
EnumInstance(Family, AF_UNIX, 1)
>>> Family.AF_UNIX == 1
>>> Family.AF_UNIX == 3
>>> [x for x in Family]
[EnumInstance(Family, AF_UNIX, 1), EnumInstance(Family, AF_INET, 2)]
>>> Family[1]
EnumInstance(Family, AF_INET, 2)

The last might be a tad surprising, but makes sense if you think about
it. :)  Class Enum has a metaclass of EnumMetaclass, where all the fun
magic is <wink>.  EnumInstances are subclasses of int and it would be
easy to make their __str__() be the nicer output format.

Anyway, if these type attribute constants like file.READ were something
like EnumInstances, then I think it would make writing and debugging
stuff like this much nicer.

> Another separate "attributes of types" issue raised by that same blog
> entry -- and that one does find me +1 -- is: isn't it time to make available
> as attributes of the str type object those few things that we still need
> to 'import string' for?  E.g., the maketrans function (and maybe we could
> even give it a better name as long as we're making it a str.something?)...

+1-ly y'rs,

More information about the Python-Dev mailing list