[Python-Dev] Non-string keys in type dict

PJ Eby pje at telecommunity.com
Thu Mar 8 06:35:46 CET 2012


On Wed, Mar 7, 2012 at 8:39 PM, Victor Stinner <victor.stinner at gmail.com>wrote:

> So my question is: what is the use case of such dict?


Well, I use them for this:

http://pypi.python.org/pypi/AddOns

(And I have various other libraries that depend on that library.)

Short version: AddOns are things you can use to dynamically extend
instances -- a bit like the "decorator" in "decorator pattern" (not to be
confused with Python decorators).  Rather than synthesize a unique string
as a dictionary key, I just used the AddOn classes themselves as keys.
 This works fine for object instances, but gets hairy once classes come
into play.  ( http://pypi.python.org/pypi/AddOns#class-add-ons - an
orthogonal alternative to writing hairy metaclasses with  registries for
special methods, persisted attributes, and all other sorts of things one
would ordinarily use metaclasses for.)

In principle, I could refactor AddOns to use synthetic (i.e. made-up)
strings as keys, but it honestly seemed unpythonic to me to make up a key
when the One Obvious key to use is the AddOn type itself.  (Or in some
cases, a tuple comprised of an AddOn type plus additional values - which
would mean string manipulation for every access.)

Another possible solution would be to not store addons directly in a class'
dictionary, but instead throw in an __addons__ key with a subdictionary;
again this seemed like pointless indirection, wasted memory and access time
when there's already a perfectly good dictionary lying about.

IOW, it's one of those places where Python's simple orthogonality seems
like a feature rather than a bug that needs fixing.  I mean, next thing you
know, people will be saying that *instance* dictionaries need to have only
string keys or something.  ;-)

Of course, if my library has to change to be able to work on 3.3, then I
guess it'll have to change.  IIRC, this is *probably* the only place I'm
using non-string keys in type or instance dictionaries, so in the big
scheme of porting costs, it's not that much.

But, since you asked, that's the main use case I know of for non-string
keys in type dictionaries, and I wouldn't be terribly surprised if I'm the
only person with public code that does this.  ;-)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20120308/0cb7c331/attachment.html>


More information about the Python-Dev mailing list