What are some common uses for Python decorators? [closed] What are some common uses for Python decorators? [closed] python python

What are some common uses for Python decorators? [closed]


I use decorators mainly for timing purposes

def time_dec(func):  def wrapper(*arg):      t = time.clock()      res = func(*arg)      print func.func_name, time.clock()-t      return res  return wrapper@time_decdef myFunction(n):    ...


I've used them for synchronization.

import functoolsdef synchronized(lock):    """ Synchronization decorator """    def wrap(f):        @functools.wraps(f)        def newFunction(*args, **kw):            lock.acquire()            try:                return f(*args, **kw)            finally:                lock.release()        return newFunction    return wrap

As pointed out in the comments, since Python 2.5 you can use a with statement in conjunction with a threading.Lock (or multiprocessing.Lock since version 2.6) object to simplify the decorator's implementation to just:

import functoolsdef synchronized(lock):    """ Synchronization decorator """    def wrap(f):        @functools.wraps(f)        def newFunction(*args, **kw):            with lock:                return f(*args, **kw)        return newFunction    return wrap

Regardless, you then use it like this:

import threadinglock = threading.Lock()@synchronized(lock)def do_something():  # etc@synchronzied(lock)def do_something_else():  # etc

Basically it just puts lock.acquire() / lock.release() on either side of the function call.


I use decorators for type checking parameters which are passed to my Python methods via some RMI. So instead of repeating the same parameter counting, exception-raising mumbo-jumbo again and again.

For example, instead of:

def myMethod(ID, name):    if not (myIsType(ID, 'uint') and myIsType(name, 'utf8string')):        raise BlaBlaException() ...

I just declare:

@accepts(uint, utf8string)def myMethod(ID, name):    ...

and accepts() does all the work for me.


matomo