Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent of Ruby's 'method_missing'

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?

like image 266
missingfaktor Avatar asked Jul 15 '11 08:07

missingfaktor


2 Answers

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.

like image 129
Emil Ivanov Avatar answered Sep 23 '22 07:09

Emil Ivanov


Python doesn't distinguish between methods and attributes (a.k.a. "instance variables") the way Ruby does. Methods and other object attributes are looked up in exactly the same way in Python -- not even Python knows the difference at the look-up stage. Until the attribute is found, it's just a string.

So if you're asking for a way to ensure that __getattr__ is only called for methods, I'm afraid you probably won't find an elegant solution. But it's easy enough to simply return a function (or even a brand-new dynamically bound method) from __getattr__.

like image 45
senderle Avatar answered Sep 19 '22 07:09

senderle