Threading Decorator [Python]

Oct 27 2020

Sto cercando di creare un semplice programma usando il socket Python e la libreria di threading. Vorrei automatizzare la seguente procedura utilizzando un decoratore:

t = threading.Thread(target=function, args=(arg1, arg2))
t.start()

il programma è strutturato utilizzando OOP quindi ho definito una sottoclasse all'interno di quella principale per contenere tutti i decoratori (ho letto di questo metodo in questo articolo: https://medium.com/@vadimpushtaev/decorator-inside-python-class-1e74d23107f6). Quindi ho una situazione come questa:

class Server(object):

    class Decorators(object):

        @classmethod
        def threaded_decorator(cls, function):
            def inner_function():
                function_thread = threading.Thread(target=function)
                function_thread.start()
            return inner_function

    def __init__(self, other_arguments):
        # other code
        pass

    @Decorators.threaded_decorator
    def function_to_be_threaded(self):
        # other code
        pass

Ma quando provo a correre, ottengo il seguente errore: TypeError: function_to_be_threaded() missing one required argument: 'self'. Sospetto che il problema si trovi nella parte in cui chiamo threading.Thread (target = function) che in qualche modo non passa l'intera funzione self.function_to_be_threaded. Quindi, se sai come risolvere questo problema, puoi dirmelo? Inoltre, puoi dirmi se c'è un modo per implementare un decoratore che accetta argomenti che passeranno alla classe Thread come args=(arguments_of_the_decorator)?

Grazie mille per il tuo tempo e scusa il mio inglese, lo sto ancora esercitando

Risposte

1 napuzba Oct 27 2020 at 15:15

Usa la *argssintassi per spostare gli argomenti. In altre parole, usa *argsper raccogliere tutti gli argomenti posizionali come una tupla e spostarla threading.Threadcome args.

import threading
import time
class Server(object):

    class Decorators(object):

        @classmethod
        def threaded_decorator(cls, function):
            def inner_function(*args):
                function_thread = threading.Thread(target=function,args=args)
                function_thread.start()
            return inner_function

    def __init__(self, count,sleep):
        self.count = count
        self.sleep = sleep

    @Decorators.threaded_decorator
    def function_to_be_threaded(self,id):
        for xx in range(self.count):
            time.sleep(self.sleep)
            print("{} ==> {}".format(id,xx))
           

>>> Server(6,1).function_to_be_threaded('a')
>>> Server(2,3).function_to_be_threaded('b')

a ==> 0
a ==> 1
a ==> 2
b ==> 0
a ==> 3
a ==> 4
a ==> 5
b ==> 1

vedi anche Come posso passare argomenti da una funzione all'altra?