Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript-like Object in Python standard library?

Tags:

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.

like image 415
David Wolever Avatar asked Apr 14 '10 20:04

David Wolever


People also ask

What is equivalent of JavaScript object in Python?

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).

What is Anobject Python?

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.

What is JavaScript's default object?

Every JavaScript function has a prototype object property by default(it is empty by default).

Which of the below are JavaScript standard built-in objects?

JavaScript also has four built-in objects: Array, Date, Math, and String.


2 Answers

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

like image 139
bscan Avatar answered Nov 09 '22 00:11

bscan


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'] 
like image 26
ars Avatar answered Nov 08 '22 22:11

ars