JavaScript-like Object in Python standard library?
Posted
by David Wolever
on Stack Overflow
See other posts from Stack Overflow
or by David Wolever
Published on 2010-04-14T20:29:35Z
Indexed on
2010/04/14
20:53 UTC
Read the original article
Hit count: 401
python
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'
Thanks, David
© Stack Overflow or respective owner