Python equivalent of Ruby's 'method_missing'

Viewed 8528

What is Python's equivalent of Ruby's method_missing method? I tried using __getattr__ but this hook applies to fields too. I only want to intercept the method invocations. What is the Python way to do it?

4 Answers

This solution creates a Dummy object for which:

  • every non-existing method will work and return None (even if you pass parameters)
  • you can also provide a dictionary with methodname: defaultvalue for methods that should return a specific default value
class Dummy:
    def __init__(self, methods):
        self.methods = methods

    def __getattr__(self, attr):
        defaultvalue = self.methods[attr] if attr in self.methods else None
        return lambda *args, **kwargs: defaultvalue

    def baz(self):
        return 'custom'

d = Dummy({'foo': 1234})

print(d.foo())                        # 1234
print(d.bar(1, 2, x=123, y=456))      # None
print(d.kjfdhgjf())                   # None
print(d.baz())                        # 'custom'
Related