Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to differentiate between method and function in a decorator?

I want to write a decorator that acts differently depending on whether it is applied to a function or to a method.

def some_decorator(func):
    if the_magic_happens_here(func): # <---- Point of interest
        print 'Yay, found a method ^_^ (unbound jet)'
    else:
        print 'Meh, just an ordinary function :/'
    return func

class MyClass(object):
    @some_decorator
    def method(self):
        pass

@some_decorator
def function():
    pass

I tried inspect.ismethod(), inspect.ismethoddescriptor() and inspect.isfunction() but no luck. The problem is that a method actually is neither a bound nor an unbound method but an ordinary function as long as it is accessed from within the class body.

What I really want to do is to delay the actions of the decorator to the point the class is actually instantiated because I need the methods to be callable in their instance scope. For this, I want to mark methods with an attribute and later search for these attributes when the .__new__() method of MyClass is called. The classes for which this decorator should work are required to inherit from a class that is under my control. You can use that fact for your solution.

In the case of a normal function the delay is not necessary and the decorator should take action immediately. That is why I wand to differentiate these two cases.

like image 480
user242486 Avatar asked Mar 12 '10 20:03

user242486


People also ask

What is the difference between decorator and function?

Functions and methods are called callable as they can be called. In fact, any object which implements the special __call__() method is termed callable. So, in the most basic sense, a decorator is a callable that returns a callable. Basically, a decorator takes in a function, adds some functionality and returns it.

Can a decorator be a method?

To provide data input integrity, a decorator can be used to decorate a method defined in the class. Currently, in the example, the decorator, @integer_check is commented out.

When would you use a function decorator?

You'll use a decorator when you need to change the behavior of a function without modifying the function itself. A few good examples are when you want to add logging, test performance, perform caching, verify permissions, and so on. You can also use one when you need to run the same code on multiple functions.

Which function or symbol is used to indicate a decorator?

You can decorate a function or decorate a class while defining that function or class by using an @ symbol. The decorator syntax uses an @ symbol, the name of the decorator, and then the body of your function or class starting on the next line.


3 Answers

I would rely on the convention that functions that will become methods have a first argument named self, and other functions don't. Fragile, but then, there's no really solid way.

So (pseudocode as I have comments in lieu of what you want to do in either case...):

import inspect
import functools

def decorator(f):
  args = inspect.getargspec(f)
  if args and args[0] == 'self':
     # looks like a (future) method...
  else:
     # looks like a "real" function
     @functools.wraps(f)
     def wrapper  # etc etc

One way to make it a bit more solid, as you say all classes involved inherit from a class under your control, is to have that class provide a metaclass (which will also of course be inherited by said classes) which checks things at the end of the class body. Make the wrapped function accessible e.g. by wrapper._f = f and the metaclass's __init__ can check that all wrapped methods did indeed have self as the first argument.

Unfortunately there's no easy way to check that other functions (non-future-methods) being wrapped didn't have such a first argument, since you're not in control of the environment in that case. The decorator might check for "top-level" functions (ones whose def is a top-level statement in their module), via the f_globals (globals dict, i.e., module's dict) and f_name attributes of the function -- if the function's such a global presumably it won't later be assigned as an attribute of the class (thereby becoming a future-method anyway;-) so the self named first arg, if there, can be diagnosed as wrong and warned about (while still treating the function as a real function;-).

One alternative would be to do the decoration in the decorator itself under the hypothesis of a real function, but also make available the original function object as wrapper._f. Then, the metaclass's __init__ can re-do the decoration for all functions in the class body that it sees have been marked this way. This approach is much more solid than the convention-relying one I just sketched, even with the extra checks. Still, something like

class Foo(Bar): ... # no decorations

@decorator
def f(*a, **k): ...

Foo.f = f   # "a killer"... function becomes method!

would still be problematic -- you could try intercepting this with a __setattr__ in your metaclass (but then other assignments to class attributes after the class statement can become problematic).

The more the user's code has freedom to do funky things (and Python generally leaves the programmer a lot of such freedom), the harder time your "framework-y" code has keeping things under tight control instead, of course;-).

like image 98
Alex Martelli Avatar answered Oct 12 '22 22:10

Alex Martelli


From Python 3.3 onwards by using PEP 3155:

def some_decorator(func):
    if func.__name__ != func.__qualname__:
        print('Yay, found a method ^_^ (unbound jet)')
    else:
        print('Meh, just an ordinary function :/')
    return func

A method x of class A will have a __qualname__ that is A.x while a function x will have a __qualname__ of x.

like image 41
kentwait Avatar answered Oct 13 '22 00:10

kentwait


Do you need to have the magic happen where you choose which wrapper to return, or can you defer the magic until the function is actually called? You could always try a parameter to your decorator to indicate which of the two wrappers it should use, like

def some_decorator( clams ):
   def _mydecor(func ):
       @wraps(func)
       def wrapping(*args....)
          ...
       return wrapping
   def _myclassdecor(func):
       @wraps(func)
       .....

   return _mydecor if clams else _myclassdecor

The other thing that I might suggest is to create a metaclass and define the init method in the metaclass to look for methods decorated with your decorator and revise them accordingly, like Alex hinted at. Use this metaclass with your base class, and since all the classes that will use the decorator will inherit from the base class, they'll also get the metaclass type and use its init as well.

like image 21
rldrenth Avatar answered Oct 12 '22 23:10

rldrenth