13

The documentation for threading.Thread(target=...) states that

target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.

I usually use it like this:

import threading

def worker():
    a = 3
    print("bonjour {a}".format(a=a))

threading.Thread(target=worker).start()

Is there a way to chain the function elements in target so that a new one does not need to be defined? Something like (pseudocode obviously)

threading.Thread(target=(a=3;print("bonjour {a}".format(a=a))).start()

I have a bunch of very short calls to make in the Thread call and would like to avoid multiplication of function definitions.

WoJ
  • 27,165
  • 48
  • 180
  • 345
  • 2
    What do you have against defining a function? – martineau Feb 06 '16 at 18:31
  • 1
    Nothing, and this is how I do it today. In one case, though, I have 10 different two liners (so I cannot use a lambda, per @ForceBru answer) and the code would be more compact and organized without them floating around. – WoJ Feb 06 '16 at 18:34
  • 1
    Your code is more testable (you have tests, right?) if you define a function to use as the target of the thread. – chepner Feb 06 '16 at 18:43

2 Answers2

19

You can use a lambda function in Python 3.x

import threading

threading.Thread(target=lambda a: print("Hello, {}".format(a)), args=(["world"]))

You should probably take a look at this SO question to see why you can't use print in Python 2.x in lambda expressions.


Actually, you can fit many function calls into your lambda:

from __future__ import print_function # I'm on Python 2.7
from threading import Thread

Thread(target=(lambda: print('test') == print('hello'))).start()

That will print both test and hello.

Community
  • 1
  • 1
ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • Perfect, thanks. I am removing my previous comment about the problem with many functions within a `lambda` which your update addresses perfectly. – WoJ Feb 06 '16 at 19:27
  • Actually, `or` would not be a good idea, because if the first function returned something that has a boolean value of true, the second function will not be evaluated, and hence will not be called. – zondo Feb 06 '16 at 21:46
5

I don't really like using exec, but in Python3.x it is a function, so you could do

threading.Thread(target=exec, args=('a=3; print("bonjour {a}".format(a=a))',)
zondo
  • 19,901
  • 8
  • 44
  • 83