My Site
Categories
Blogs
Useful Links
Decorator fun in Python
Written by: Adam Olsen (synic)

I came across the following code a while ago. I can't take credit for it, and I can't remember where I got it. Oh well. It's pretty cool nonetheless.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
def threaded(f):
    """
        A decorator that will make any function run in a new thread
    """
    def wrapper(*args):
        t = threading.Thread(target=f, args=args)
        t.setDaemon(True)
        t.start()

    wrapper.name = func.name
    wrapper.dict = func.dict
    wrapper.doc = func.doc

    return wrapper

def synchronized(func):
    """
        A decorator to make a function synchronized – which means only one
        thread is allowed to access it at a time
    """
    def wrapper(self,__args,*__kw):
        try:
            rlock = self._sync_lock
        except AttributeError:
            from threading import RLock
            rlock = self.dict.setdefault(_sync_lock,RLock())
        rlock.acquire()
        try:
            return func(self,__args,*__kw)
        finally:
            rlock.release()
    wrapper.name = func.name
    wrapper.dict = func.dict
    wrapper.doc = func.doc
    return wrapper

# example:

@threaded
def this_is_a_long_running_function():
    connect_to_network_and_do_a_lot_of_stuff
# any time the above function is called, it will run in a new thread


vim tips: A, D, and C

A will take you to the end of the line and put you in insert mode. D will delete until the end of the line, and C will delete to the end of the line and put you in insert mode.

File under: Programming, Python
Comments:

No comments have been added yet


Add a comment:

Name:
Type Vim Here:   (It's a human test)
Email Address:   (optional for reply subscription)
Comment:   
 
Note: If you enter your email address, you will be subscribed to this article and will recieve comment updates via email. This is the only thing your address will be used for. A link will be provided at the end of each email that will allow you to unsubscribe should you need to, or you can go to http://www.vimtips.org/unsubscribe to unsubscribe from any/all updates.