[Python-ideas] @run_as_thread decorator

Nick Coghlan ncoghlan at gmail.com
Sat Mar 5 15:10:56 CET 2011


On Sat, Mar 5, 2011 at 11:21 PM, Giampaolo Rodolà <g.rodola at gmail.com> wrote:
>  >>> import time, threading
>  >>>
>  >>> @threading.run_as_thread
>  ... def foo():
>  ...     time.sleep(100)
>  ...     return 1
>  ...
>  >>> t = foo()
>  >>> t.isAlive()
>  True
>  >>> t.join()
>  >>> t.isAlive()
>  False
>  >>>
>
> The same thing could be done for multiprocessing module.
> Would this be acceptable for inclusion?

So basically:

def run_as_thread(f):
    @functools.wraps(f):
    def wrapped(*args, **kwds):
        t = threading.Thread(target=f, args=args, kwds=kwds)
        t.start()
        return t
    return wrapped

Something like that would make defining worker threads *really* easy.

A similar idea may make sense as an addition to the
concurrent.futures.Executor ABC. For example:

def autosubmit(self):
    def decorator(f):
        @functools.wraps(f):
        def wrapped(*args, **kwds):
            return self.submit(f, *args, **kwds)
        return wrapped
    return decorator

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list