pythonpython-3.xpython-multithreadingargswindow-decoration

Can't get the parameters of a func using threading lib in a python decoration?


Below is the python codes,The decoration is ok without thread created through a class inherit from threading.thread. for example create a thread by giving the target func as a paremeter to threading.thread()

import threading ,time
from time import sleep, ctime
import functools

def find(func):
    @functools.wraps(func)
    def wrapper(*args,**kwargs):
        print("ags:%s,%s\n" % (args,kwargs))
        return func(*args, **kwargs)
    return wrapper

@find
def now() :
    return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )

class myThread (threading.Thread) :
    """docstring for myThread"""
    @find
    def __init__(self, nloop, nsec) :
        super(myThread, self).__init__()
        self.nloop = nloop
        self.nsec = nsec

    @find
    def run(self):
        print('start loop', self.nloop, 'at:', ctime())
        sleep(self.nsec)
        print('loop', self.nloop, 'done at:', ctime())
@find
def main():
    thpool=[]
    print('starting at:', now())

    for i in range(10):
        thpool.append(myThread(i,2))

    for th in thpool:
        th.start()

    for th in thpool:
        th.join()

    print('all Done at:', now())

if __name__ == '__main__':
    main()

I got a error info as below:

File "F:\question\multithreadfmclass.py", line 15, in wrapper
    print("ags:%s,%s\n" % (args,kwargs))
  File "D:\ProgramFiles\Python352\lib\threading.py", line 813, in __repr__
    assert self._initialized, "Thread.__init__() was not called"
AssertionError: Thread.__init__() was not called

How to remove the bugs? tks in advance.


Solution

  • You are printing the Thread object before it is initialized which is impossible. It is not easy to find this mistake because of your decorator but if you call func first, then it works:

    def find(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            result = func(*args, **kwargs)
            print("ags:%s,%s\n" % (args, kwargs))
            return result
    
    return wrapper