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.
JavaScript objects are like Python classes (because they inherit like Python classes). For JavaScript attribute and item access are the same. This is achieved in Python by providing custom item methods. In Python the custom item methods must be placed on the type of the object (or a superclass of its type).
An object is simply a collection of data (variables) and methods (functions) that act on those data. Similarly, a class is a blueprint for that object.
Every JavaScript function has a prototype object property by default(it is empty by default).
JavaScript also has four built-in objects: Array, Date, Math, and String.
In Python 3.3+ you can use SimpleNamespace, which does exactly what you're looking for:
from types import SimpleNamespace obj = SimpleNamespace() obj.airspeed = 42
https://docs.python.org/3.4/library/types.html#types.SimpleNamespace
You can try with attrdict:
class attrdict(dict): def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) self.__dict__ = self a = attrdict(x=1, y=2) print a.x, a.y print a['x'], a['y'] b = attrdict() b.x, b.y = 1, 2 print b.x, b.y print b['x'], b['y']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With