Added a basic implementation of wc.
[4chanprog.git] / dynobject.py
blob832c30f41a278dd76d94d106bc6ae4a63a659d82
1 ## dynobject.py
2 ## a dynamic object for Python
3 ## by Sam Fredrickson <kinghajj@gmail.com>, 2007-02-22
4 ##
5 ## inspired by Javascript. in JS, you can make objects like this:
6 ## o = {a: 2, b: 3}
7 ## o.c = 4
8 ## o.d = 5
9 ## ...
11 ## with dynobject, you can do similar in python:
12 ## o = dynobject(a=2, b=3)
13 ## o.c = 4
14 ## o.d = 5
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)
22 for key in kwargs:
23 setattr(obj, key, kwargs[key])
24 return obj
26 class dynobject(object):
27 __metaclass__ = __dynobject_meta__
29 # when you iterate, you get pairs of attribute names and values
30 def __iter__(self):
31 attrs = dir(self)
32 for attr in attrs:
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
37 # error
38 def __getattribute__(self, attr):
39 try:
40 return object.__getattribute__(self, attr)
41 except:
42 return None