Decorator question (how to test if decorated function is in a class)
bruno.42.desthuilliers at websiteburo.invalid
Fri Jun 19 11:38:46 EDT 2009
Martin P. Hellwig a écrit :
> Hi all,
> I have been trying out to wrap my mind around the advantages of
> decorators and thought I found a use in one of my experiments. (see code
> after my sig).
> Although it works, I think it should be able to do it better.
> My particular problem is that I want to remove an argument (say always
> the first one) when the decorated function is called.
> However if the function is defined in a class the first argument is self
> and thus the second argument should be removed.
You'll have the same problem with a function defined outside a class
then "attached" to the class, ie:
Foo.meth = func
> Since I like to have a more general DRY approach I want to test if the
> decorated function is defined in a class or not thus knowing that the
> first argument is self and must be preserved.
Short answer: this makes no sense.
> I tried different approaches but all didn't work and looked very
> unpythonic (looking at the attributes, descriptors namespaces, id() of
> the function, the first argument and the decorator itself).
> So is there a way to find out if the first argument is 'self' without
> making a false positive if the first argument is a class instance passed
> to a function?
The solution to your problem is elsewhere... Read the doc about the
descriptor protocol, and how it's implemented by the function type to
"turn" functions into methods when they are looked up as attribute of a
More information about the Python-list