Rant: Dicts that are not dicts
Sunday, August 3rd, 2008
There’s something I have to get off my chest. I HATE it when things in Python pretend to be something they are not. I often use IPython to introspect things so I know how to use them. Lately, I’ve been running into more and more libraries which return things that pretend to be one thing, but which really are something else. Observe:
import optparse
parser = optparse.OptionParser()
parser.add_option("-p", dest="path", action="store", type="string")
(options, args) = parser.parse_args()
print options
Output:
{'path': None}
“Ah”, I think, “a dictionary. Swell!”, and go ahead and do:
print options.get('path', 'default')
And then it responds:
Traceback (most recent call last): File "/home/todsah/foo.py", line 7, in <module> print options.get('path', 'default') AttributeError: Values instance has no attribute 'get'
What the hell? A dictionary with no get attribute? Then, when you print the type, it turns out it’s not a dictionary at all: “<type 'instance'>“. It’s a plain old object instance, and you have to use getattr(), etc instead of foo[key] and foo.get(). Fortunately, I’ve seen this trap now for so many times, the first thing I do is check the type of the thing I’m having problems with, but occasionally it still bites me in the ass.
I am seeing this more and more often, and it annoys me to no end. Python is supposed to be a rapid application development language, and things like this are extremely annoying. Don’t pretend to be something you’re not. If an object is going to behave dictionary-like, why not just extend the real dict object? Wouldn’t that be so much easier?
So, developers: Please don’t make things appear like things they’re not. It causes confusion, and possibly even bugs.