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

  • 1
    Your args are missing a comma. It should be `args=(callback,)` instead of `args=(callback)`. – MisterMiyagi Feb 18 '22 at 08:26
  • all this or a comma, thanks but this comma is strange no ? –  Feb 18 '22 at 08:30
  • The comma makes a tuple. Otherwise, ``2 + (3 * 4)`` would add ``2`` to a tuple. Only the *empty* tuple is defined by parentheses. – MisterMiyagi Feb 18 '22 at 08:32
  • The single-element tuple seems to confuse beginners. Keep it simple and just use a list i.e., *args=[callback]* – DarkKnight Feb 18 '22 at 08:35
  • 1
    Does this answer your question? [Python threading error - must be an iterable, not int](https://stackoverflow.com/questions/49947814/python-threading-error-must-be-an-iterable-not-int) – Tsyvarev Feb 18 '22 at 08:39
  • yes, thanks can i mark this topic solve whithot new reply post ? –  Feb 18 '22 at 09:02

1 Answers1

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)