metaclass

Mark McEahern mark at mceahern.com
Fri Apr 12 13:45:21 EDT 2002


I'm trying to translate the tracing metaclass provided here:

  http://www.python.org/doc/essays/metaclasses/Trace.py

to use the new __metaclass__ construct in Python 2.2, but I can't seem to
get off the ground.

For starters, suppose I simply want the metaclass to switch out one class
with another.

  # This should return an instance of Proxy instead of Switched.
  # Eventually, Proxy will be able to trace calls to Switched
  # before passing them on to Switched.
  s = Switched()

I try this:

#! /usr/bin/env python
# junk.py

class Proxy(object):

  pass

class SwitcherooMeta(type):

  def __new__(cls, name, bases, dict):
    # Normally, this should just do this:
    # return type.__new__(cls, name, bases, dict)
    # Instead, try to return the proxy type.
    # This results in 'Proxy' object is not callable:
    return Proxy()
    # This doesn't work either:
    object.__new__(Proxy, name, bases, dict)

class Switched(object):

  __metaclass__ = SwitcherooMeta

s = Switched()

When I run that, I get:

$ junk.py
Traceback (most recent call last):
  File "./junk.py", line 19, in ?
    s = Switched()
TypeError: 'Proxy' object is not callable

I've tried to follow the documentation provided here:

  http://www.python.org/2.2/descrintro.html#metaclasses

Any pointers on meta classes?

Thanks,

// mark






More information about the Python-list mailing list