How to pass self and 2 arguments to thread

Viewed 2019

I'm simply trying to pass self and 2 other arguments to a thread, but I'm getting an error every time.

I tried following other samples, but nothing has worked so far.

class X:
    def start(self):
        newStartupThread = threading.Thread(target=self.launch, args=(t1_stop, 
            self.launchAdditionalParams))
        newStartupThread.name = "ClientLaunchThread%d" % 
            (self.launchAttemptCount+1)
        newStartupThread.daemon = True
        newStartupThread.start()


    def launch(self, test, additionalParams):
        pass

I'm getting this error:

TypeError: launch() takes at most 2 arguments (3 given)

**Edited the code to show that it is in a class

2 Answers

From the presence of self, I assume this is in a class.

import threading


class X:
    def start(self):
        t1_stop = 8
        self.launchAdditionalParams = {}

        newStartupThread = threading.Thread(
            target=self.launch,
            args=(t1_stop, self.launchAdditionalParams),
        )
        newStartupThread.name = "ClientLaunchThread"
        newStartupThread.daemon = True
        newStartupThread.start()

    def launch(self, test, additionalParams):
        print(locals())


x = X()
x.start()

works fine for me, outputting

{'additionalParams': {}, 'test': 8, 'self': <__main__.X object at 0x000001442938F438>}

launch is a function, not a method. Only methods need the self argument. Just remove the self argument and it should work:

def launch(test, additionalParams):

If it is within a class, you have to do one of two things:

  • Call it only on instances of the class (someClass.launch(arg1, arg2))
  • Make it a static method by not including the self argument
Related