[Python-ideas] @run_as_thread decorator

Giampaolo Rodolà g.rodola at gmail.com
Sat Mar 5 19:00:52 CET 2011


I agree it should be possible to pass the same arguments of the
original constructor, in fact this is the code I use across the
various "private" projects I work on:

def run_as_thread(group=None, name=None, verbose=None, daemon=None):
    """Decorator to run a callable in a thread returning a
    thread instance.

    >>> @run_as_thread
    ... def foo():
    ...     time.sleep(100)
    ...     return "done"
    ...
    >>> t = foo()
    >>> t.is_alive()
    True
    >>> t.join()
    >>> t.is_alive()
    False
    """
    def outer(fun):
        def inner(*args, **kwargs):
            t = threading.Thread(target=fun, args=args, kwargs=kwargs,
                                 group=group, name=name, verbose=verbose)
            t.start()
            return t
        return inner

    if hasattr(group, '__call__'):
        # defined as @run_as_thread rather than @run_as_thread(arg=...)
        fun = group
        group = None
        outer = outer(fun)
    return outer



I don't know whether it is a good idea to provide such a thing
natively, but I can't even figure out what exactly is wrong/weird with
this exactly.
This is why I opened this discussion, basically. =)

--- Giampaolo
http://code.google.com/p/pyftpdlib/
http://code.google.com/p/psutil/


2011/3/5 Masklinn <masklinn at masklinn.net>:
> On 2011-03-05, at 14:21 , Giampaolo Rodolà 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?
> That looks good, though though I think run_as_thread needs to take arguments:
> * daemonifying needs to be performed *before* the thread is started, so it needs at least one argument `daemon=False` (which runs a daemonified thread if set to true)
> * maybe run_as_thread could take a second argument `start=True` to know whether the function should generate a started thread or a thread to start? Not sure about that one, are there situations where you'd *need* a yet-to-be-started thread apart from daemonification?
> * threads can take names, not sure if this is often used, should it be handled by run_as_thread? This is not as important as daemon because I think thread names can be set after start()
> * what are the semantics of the function's return value? None and it's basically ignored (as with regular target semantics)?
>
>



More information about the Python-ideas mailing list