how do I use the __metaclass__ variable to change the default base class?

Adam Feuer adamf at pobox.com
Sun Dec 1 23:52:28 EST 2002


Python folks, 

I have a piece of Python software made up of many classes that I would
like to collect information about at runtime- specifically, what
classes hold references to what other classes.

I thought it would be possible to define my own class that subclasses
object, and redefine the __setattr__ method on that class.  Then, when
I wanted to collect the information I would use the __metaclass__
global variable to tell Python at runtime that all my classes now
derive from my new base class (that is, the default base class for all
classes is now MyObject)...

I haven't been able to get this to work. What's wrong?

. . . .
class MyObject(object):
   def __setattr__(self, name, value):
      print "in __setattr__"
      self.__dict__[name] = value

__metaclass__ = MyObject

class TestClass1:
   def __init__(self):
      self.foo = "bar"

if __name__ == "__main__":
   t1 = TestClass1()
. . . .

When I execute this code, I get an exception:

$ python MetaclassTest2.py
Traceback (most recent call last):
  File "MetaclassTest2.py", line 13, in ?
    t1 = TestClass1()
TypeError: 'MyObject' object is not callable

However, this next bit of code works- it doesn't use the __metaclass__
variable but instead subclasses object directly:

. . . .
class MyObject(object):
   def __setattr__(self, name, value):
      print "in __setattr__"
      self.__dict__[name] = value

class TestClass1(MyObject):
   def __init__(self):
      self.foo = "bar"

if __name__ == "__main__":
   t1 = TestClass1()
. . . .

When I execute this, I get the expected result:

$ python MetaclassTest1.py
in __setattr__

Help!

By the way, I'm using Python 2.2.2 on Debian Linux 2.2.

cheers
adam
--
Adam Feuer <adamf at pobox dot com>




More information about the Python-list mailing list