0

how is possible to pass a function to a thread like a standard variable,

when i pass function on args , i have a non iterable error

there is a summary of my code

from CallbackThread import CallbackThread
import time
import threading

class foo:
    def runSomthing(self,callback):
        #do things
        callthread = threading.Thread(target=self.newthread, args=(callback))
        callthread.start()

    def newthread(self,calback):
       print("runiing")
       while True:
           #if receve data (udp)
            data = 0
          #run mycallbacktest
          calback(data)


def mycallbacktest(i):
    print("hello world", i)

myobj = foo()
myobj.runSomthing(mycallbacktest)

i have see on similar topics things like that https://gist.github.com/amirasaran/e91c7253c03518b8f7b7955df0e954bb

and i have try this based on this bu i not sure what this is doing, for me is just call a callback when thread if finished

class BaseThread(threading.Thread):
    def __init__(self, callback=None, callback_args=None, *args, **kwargs):
        target = kwargs.pop('target')
        super(BaseThread, self).__init__(target=self.target_with_callback, *args, **kwargs)
        self.callback = callback
        self.method = target
        self.callback_args = callback_args

    def target_with_callback(self):
        self.method()
        if self.callback is not None:
            self.callback(*self.callback_args)

but this d'ont solve what i tring to do

6
  • 1
    Your args are missing a comma. It should be args=(callback,) instead of args=(callback). Commented Feb 18, 2022 at 8:26
  • all this or a comma, thanks but this comma is strange no ? Commented Feb 18, 2022 at 8:30
  • The comma makes a tuple. Otherwise, 2 + (3 * 4) would add 2 to a tuple. Only the empty tuple is defined by parentheses. Commented Feb 18, 2022 at 8:32
  • The single-element tuple seems to confuse beginners. Keep it simple and just use a list i.e., args=[callback] Commented Feb 18, 2022 at 8:35
  • 1
    Does this answer your question? Python threading error - must be an iterable, not int Commented Feb 18, 2022 at 8:39

1 Answer 1

0

as suggested MisterMiyagi, the awnser a missig comma,

It should be args=(callback,) instead of args=(callback)

(this post is to mark this post close)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.