Source

pythonwise / trylock.py

from functools import wraps
from threading import RLock
from collections import defaultdict

class AlreadyRunningError(Exception):
    pass


def try_lock(keyfn=None):
    '''Allow function to run only once. `keyfn` can be used to select a subset
    of the function arguments/kwargs to lock on.

    Will raise `AlreadyRunningError` if runtion already running.

    Example::
        def push(day, records):
            ...

    And we care only about the day argument, when we'll do::

        @try_lock(lambda args, kw: args[0])
        def push(day, records):
            ...
    '''
    keyfn = keyfn or (lambda args, kw: 7)  # Return the same key
    by_key_locks = defaultdict(RLock)
    master_lock = RLock()

    def wrapper(func):
        @wraps(func)
        def wrapped(*args, **kw):
            key = keyfn(args, kw)

            # Get lock for key
            with master_lock:
                lock = by_key_locks[key]

            if not lock.acquire(blocking=False):
                raise AlreadyRunningError(
                    "{} already running for {}".format(func.__name__, key))

            try:
                return func(*args, **kw)
            finally:
                lock.release()
        return wrapped
    return wrapper
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.