Python equivalent of Ruby's 'method_missing'

missingfaktor picture missingfaktor · Jul 15, 2011 · Viewed 8k times · Source

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?

Answer

Emil Ivanov picture Emil Ivanov · Jul 15, 2011

There is no difference in Python between properties and methods. A method is just a property, whose type is just instancemethod, that happens to be callable (supports __call__).

If you want to implement this, your __getattr__ method should return a function (a lambda or a regular def, whatever suite your needs) and maybe check something after the call.