[BangPypers] MetaClass in python

steve steve at lonetwin.net
Thu Jan 13 06:08:46 CET 2011

On 01/12/2011 09:13 PM, Nitin Kumar wrote:
> Hi Taj,
> On Wed, Jan 12, 2011 at 3:43 PM, Sirtaj Singh Kang<sirtaj at sirtaj.net>wrote:
>>  On 11-Jan-11, at 8:47 PM, Nitin Kumar wrote:
>>  [snip]
>>   So i do know who to create a class and its function dynamically at
>>>  runtime???
>>  You can dynamically create a class like this:
>>  NewClass = type('NewClass', (object,), {})
>>  where 'NewClass' is the name of your class, (object,) is any tuple of
>>  superclasses and *{} will be the __dict__ of the new class*. As steve
>>  mentioned earlier, you can
> So {} can contain function also for the new class, if then can you give
> example for the same. As i need function to class being generated.

Namespaces in python are basically dicts ...

[steve at laptop ~]$ python
Python 2.7 (r27:82500, Sep 16 2010, 18:02:00)
[GCC 4.5.1 20100907 (Red Hat 4.5.1-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
  >>> class A:
...     def m(self):
...             pass
  >>> A.__dict__
{'__module__': '__main__', 'm': <function m at 0x7f08629af398>, '__doc__': None}
  >>> a = A()
  >>> dir(a)   # the keys of __dict__ of the `object`
['__doc__', '__module__', 'm']
  >>> dir(A)   # the keys of __dict__ of the `class`
['__doc__', '__module__', 'm']

So, if you want to create a new function and replace it, use the method I showed 
earlier, or if you really need to create a new class you can use the approach 
that taj showed, basically something like this:

  >>> class foo(object):
...     pass
  >>> def method(obj, arg):
...     print "do something with %s passing arg %s" % (obj, arg)
  >>> NewClass = type('NewClass', (foo,), {'callme' : method})
  >>> a = NewClass()
  >>> a.callme("argument to a")
do something with <__main__.NewClass object at 0x7f08629aa610> passing arg 
argument to a

I haven't yet looked at the unittest example that you gave because to be honest, 
I'm sorry, I didn't quite understand what you said on first reading.

I'll take a closer look sometime today and reply if possible, however, basically 
all that your really need to understand is a `metaclass` is basically something 
that creates a new object (which is a class) with a nicely customized dict. That 
is to say ...

# if ...
A = MetaClass()

# you have the ability to say ...
a = A()

# and also say ...

# because MetaClass created A.__dict__ to contain ...
{'some_method':<function some_method>, ...}

- steve

random spiel: http://lonetwin.net/
what i'm stumbling into: http://lonetwin.stumbleupon.com/

More information about the BangPypers mailing list