Well, there is a difference in the generated code (at least when using CPython 2.7.12):
def runThread(a):
def threadFunc():
while True:
print a
time.sleep(1)
t = threading.Thread(target=threadFunc)
t.start()
Will issue a LOAD_GLOBAL
opcode for a
inside threadFunc()
(output is from inspect.dis.dis()
):
8 9 LOAD_GLOBAL 1 (a)
while
def runThread(a):
def threadFunc(a):
while True:
time.sleep(1)
t = threading.Thread(target=threadFunc, args=(a, ))
t.start()
will issue a LOAD_FAST
opcode:
8 9 LOAD_FAST 0 (a)
The LOAD_FAST
happens, because the compiler knows that a
is parameter and thus the lookup only needs to happen wrt. to the current namespace. LOAD_FAST
(hence the name) is potentially faster than LOAD_GLOBAL
, but if you need think about the differences in terms of performance, you probably shouldn't be using Python in the first place.
And yeah, everything screams "implementation detail" to me, too.
Scope-importing a
from an outer scope gives you added flexibility, since you can still modify a
even after the thread is already running. When passing a
as parameter to the thread function, that possibility is more or less gone. In any case, I would consider the former an antipattern unless its a
is the thread termination flag.