Friday, June 27, 2014

Non-blocking thread lock decorator.

#!/usr/bin/env python

'''
http://codereview.stackexchange.com/questions/42802/a-non-blocking-lock-decorator-in-python
'''

from threading import Lock

def non_blocking_lock(fn):
    """Decorator. Prevents the function from being called multiple times simultaneously.

    If thread A is executing the function and thread B attempts to call the
    function, thread B will immediately receive a return value of None instead.

    """
    lock = Lock()

    @wraps(fn)
    def locker(*args, **kwargs):
        if lock.acquire(False):
            try:
                return fn(*args, **kwargs)
            finally:
                lock.release()

    return locker

Dynamically add Methods to Python Classes with Class Decorators

#!/usr/bin/env python
'''
Class decorators rebind class names to the result of a function at the end of a class statement.
https://www.inkling.com/read/learning-python-mark-lutz-4th/chapter-39/example-adding-methods-to
'''
def Extender(aClass, method):
    aClass[method] = method  # Manages class, not instance
    return aClass

@Extender
class Client1: # Client1 = Extender(Client1)
    def __init__(self, value): # Rebound at end of class stmt
        self.value = value
    def spam(self):
        return self.value * 2

A Python decorator for measuring the execution time of methods

import time                                                

def timeit(method):

    def timed(*args, **kw):
        ts = time.time()
        result = method(*args, **kw)
        te = time.time()

        print '%r (%r, %r) %2.2f sec' % \
              (method.__name__, args, kw, te-ts)
        return result

    return timed

class Foo(object):

    @timeit
    def foo(self, a=2, b=3):
        time.sleep(0.2)