__getattr__ and functions that don't exist

Nick Smallbone nick.smallbone at gmail.com
Thu May 25 18:31:43 EDT 2006


Erik Johnson wrote:
> Maybe I just don't know the right special function, but what I am wanting to
> do is write something akin to a __getattr__ function so that when you try to
> call an object method that doesn't exist, it get's intercepted *along with
> it's argument*, in the same manner as __getattr__ intercepts attributes
> references for attributes that don't exist.
>
>
> This doesn't quite work:
>
> >>> class Foo:
> ...   def __getattr__(self, att_name, *args):
> ...     print "%s%s" % (att_name, str(tuple(*args)))
> ...
> >>> f = Foo()

The problem is that the call to f.bar happens in two stages: the
interpreter calls getattr(f, "foo") to get a function, and then it
calls that function. When __getattr__ is called, you can't tell what
the parameters of the function call will be, or even if it'll be called
at all - someone could have run "print f.bar".

Instead, you can make __getattr__ return a function. Then *that*
function will be called as f.bar, and you can print out its arguments
there:

class Foo:
    def __getattr__(self, attr):
        def intercepted(*args):
            print "%s%s" % (attr, args)
        return intercepted




More information about the Python-list mailing list