Distinguishing between functions and methods in a decorator.

Berteun Damman berteun at NO_SPAMdds.nl
Fri Feb 8 08:11:07 EST 2008


On Thu, 07 Feb 2008 18:22:03 +0100, Diez B. Roggisch
<deets at nospam.web.de> wrote:
> Can you provide an example of what you are actually after? The 
> descriptor-protocol might come to use there.

Thanks for your responses. I have read the Descriptor protocol how-to,
which clarifies method access on objects, and indeed provides a
solution.

My idea was to have some @pre and @post decorators, which check some
pre-conditions. When applied to a method, the first parameter will be an
instance-object, and I wondered whether I could detect whether the
precondition cared about it or not.

So,
@pre(lambda x: x > 0)
def method(self, x):

Here the precondition function does not use 'self', yet it will of
course be provided in a call, so I need to strip it. In case of a @pre
applied to a function, this does not happen. I'm not sure whether this
magic is such a nice solution though.

However, the descriptor protocol indeed is what I need. If I provide the
__get__ method, this will be invoked instead of __call__, which will
happen on functions (or methods, if __get__ is not provided). This way
the two are clearly distinguishable, and I need not worry about
heuristics (such as, is the first parameter called 'self' or something).

Besides, it taught me a bit more about the inner design of Python. :)

Thanks,

Berteun



More information about the Python-list mailing list