user3019917 user3019917 -3 years ago 49
Python Question

Python thread scope

Both codes seem to have similar performance. How does the scope work in this case? Is any of them better than the other? Is there a better way to achieve the same behavior?

code 1:

class ex:
b = 6
def foo(self, a):
def fooHandler(a):
while True:
print a
time.sleep(1)
threading.Thread(target=fooHandler, args=(a,)).start()
x = ex()
x.foo(10)
x.foo(100)
x.foo(1000)


code 2:

class ex:
b = 6
def foo(self, a):
def fooHandler():
while True:
print a
time.sleep(1)
threading.Thread(target=fooHandler).start()
x = ex()
x.foo(10)
x.foo(100)
x.foo(1000)

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download