Descobri mais uma utilidade para os decorators em python:

import threading

class Thread(threading.Thread):
    def __init__(self, f):
        threading.Thread.__init__(self)
        self.run = f

@Thread
def func():
    print "Hello world!"

func.start()

Jeito simples e eficientes para criar funções threadizadas.

Update: É possível otimizar esse código para não precisar escrever .start() na mão, e deixar as funções compatíveis com a sua versão não-threadizada:

class Thread(threading.Thread):
    def __init__(self, f):
        threading.Thread.__init__(self)
        self.run = f

    def __call__(self):
        return self.start()

@Thread
def func():
    print "Hello world!"

func()

Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© 2012 Eugeni's blog Suffusion theme by Sayontan Sinha