An idea for method_missing

mrstevegross mrstevegross at gmail.com
Wed Apr 29 20:27:48 CEST 2009


I was exploring techniques for implementing method_missing in Python.
I've seen a few posts out there on the subject... One tricky aspect is
if it's possible to not just intercept a method_missing call, but
actually dynamically add a new function to an existing class. I
realized you can modify the Class.__dict__ variable to actually add a
new function. Here's how to do it:

class Foo:
  def __init__(self):
    self.foo = 3

  def method_missing(self, attr, *args):
    print attr, "is called with %d args:" % len(args),
    print args

  def __getattr__(self, attr):
    print "Adding a new attribute called:", attr
    def callable(*args):
      self.method_missing(attr, *args[1:])
    Foo.__dict__[attr] = callable
    return lambda *args :callable(self, *args)

In the sample client code below, you'll see that the first time
go_home gets invoked, the __getattr__ call reports that it is adding a
new function. On subsequent calls, the actual method gets used:

f = Foo()
f.go_home(1,2,3)
f.go_home(1,2,3)
f.go_home(1,2,3)
f.go_away('boo')
f.go_home(1,2,3)

--Steve



More information about the Python-list mailing list