2 ## a dynamic object for Python
3 ## by Sam Fredrickson <kinghajj@gmail.com>, 2007-02-22
5 ## inspired by Javascript. in JS, you can make objects like this:
11 ## with dynobject, you can do similar in python:
12 ## o = dynobject(a=2, b=3)
16 # ah, metaclasses. here's a use for them. without this metaclass, I couldn't
17 # use setattr() to define new properties on-the-fly
18 class __dynobject_meta__(type):
19 # when you are creating a dynobject, you can pass it keywords
20 def __call__(self
, **kwargs
):
21 obj
= type.__call
__(self
)
23 setattr(obj
, key
, kwargs
[key
])
26 class dynobject(object):
27 __metaclass__
= __dynobject_meta__
29 # when you iterate, you get pairs of attribute names and values
33 if attr
[0:2] != "__" and attr
[-3:-1] != "__":
34 yield (attr
, getattr(self
, attr
))
36 # if you request a nonexistant attribute, you get None rather than an
38 def __getattribute__(self
, attr
):
40 return object.__getattribute
__(self
, attr
)