Determining if a function is a method of a class within a decorator
tjreedy at udel.edu
Tue Jun 30 15:32:57 EDT 2009
I do not like top posting.
Some thoughts in randon order:
Introspection is version-specific.
Call-time introspection is different from definition-time introspection.
Do what is easy and works.
Do not use recipes that depend on version-specific stuff you do not
Code objects, I believe, know the names of parameters.
That question and responses were only about methods, not non-class
You get to match these responses to your post ;-).
David Hirschfield wrote:
> Yeah, it definitely seems like having two separate decorators is the
> solution. But the strange thing is that I found this snippet after some
> deep googling, that seems to do something *like* what I want, though I
> don't understand the descriptor stuff nearly well enough to get what's
> answer number 3, by ianb. It seems to indicate there's a way to
> introspect and determine the class that the function is going to be
> bound to...but I don't get it, and I'm not sure it's applicable to my case.
> I'd love an explanation of what is going on in that setup, and if it
> isn't usable for my situation, why not?
> Thanks again,
> Terry Reedy wrote:
>> David Hirschfield wrote:
>>> I'm having a little problem with some python metaprogramming. I want
>>> to have a decorator which I can use either with functions or methods
>>> of classes, which will allow me to swap one function or method for
>>> another. It works as I want it to, except that I want to be able to
>>> do some things a little differently depending on whether I'm swapping
>>> two functions, or two methods of a class.
>> Unbounds methods are simply functions which have become attributes of
>> a class. Especially in Py3, there is *no* difference.
>> Bound methods are a special type of partial function. In Python, both
>> are something else, though still callables. Conceptually, a partial
>> function *is* a function, just with fewer parameters.
>>> Trouble is, it appears that when the decorator is called the function
>>> is not yet bound to an instance, so no matter whether it's a method
>>> or function, it looks the same to the decorator.
>> Right. Whether it is an A or an A, it looks like an A.
>> Worse: when the decorator is called, there is no class for there to be
>> instances of.
>>> This simple example illustrates the problem:
>> Add a second parameter to tell the decorator which variant of behavior
>> you want. Or write two variations of the decorator and use the one you
More information about the Python-list