Threading and Class Functions - Python

#1

It appears that you can’t start a thread with a class instance method. Is that correct?

class ObjClass:
    __init__(self):
        pass
   
    def some_method(self):
        pass

obj_instance = ObjClass()

#this gets a runtime exception
sys.run_in_thread(obj_instance.some_method)

#this works fine
sys.run_in_thead(ObjClass.some_method)
0 Likes

#2

Yes. This can be circumvented using a lambda:

class Foo:
    def __init__(self):
        self.bar = 1
    def printbar(self):
        print self.bar

a = Foo()

sys.run_in_thread(lambda: a.printbar())

>>> 1

Perhaps more usefully, anonymous functions also let you pass arguments into a thread invocation, which you can’t normally do, since, as you’ve seen, run_in_thread only takes a function name.

class Foo:
    def __init__(self):
        self.bar = 1
    def printbaz(self, num):
        print self.bar + num

a = Foo()

sys.run_in_thread(lambda: a.printbaz(20))

>>> 21

Here’s a V5 mimic project which shows this code in action, executing it in your browser using Javascript. Simply click “play” to run the code.

2 Likes

#3

That’s great. Actually, better than great.

Thanks.

0 Likes