Quite often, I find myself wanting a simple, “dump” object in Python which behaves like a JavaScript object (ie, its members can be accessed either with .member or with ['member']).
Usually I’ll just stick this at the top of the .py:
class DumbObject(dict):
def __getattr__(self, attr):
return self[attr]
def __stattr__(self, attr, value):
self[attr] = value
But that’s kind of lame, and there is at least one bug with that implementation (although I can’t remember what it is).
So, is there something similar in the standard library?
And, for the record, simply instanciating object doesn’t work:
>>> obj = object() >>> obj.airspeed = 42 Traceback (most recent call last): File "", line 1, in AttributeError: 'object' object has no attribute 'airspeed'
Edit: (dang, should have seen this one coming)… Don’t worry! I’m not trying to write JavaScript in Python. The place I most often find I want this is while I’m still experimenting: I have a collection of “stuff” that doesn’t quite feel right to put in a dictionary, but also doesn’t feel right to have its own class.
There is no “standard library” with that kind of object, but on ActiveState there is a quite well-known recipe from Alex Martelli, called “bunch”.
Note: there’s also a package available on pypi called bunch and that should do about the same thing, but I do not know anything about its implementation and quality.