40

My code:

    import threading

def hello(arg, kargs):
    print arg

t = threading.Timer(2, hello, "bb")
t.start()

while 1:
    pass

The print out put is just:

b

How can I pass a argument to the callback? What does the kargs mean?

Bin Chen
  • 58,165
  • 53
  • 139
  • 181

2 Answers2

76

Timer takes an array of arguments and a dict of keyword arguments, so you need to pass an array:

import threading

def hello(arg):
    print arg

t = threading.Timer(2, hello, ["bb"])
t.start()

while 1:
    pass

You're seeing "b" because you're not giving it an array, so it treats "bb" an an iterable; it's essentially as if you gave it ["b", "b"].

kwargs is for keyword arguments, eg:

t = threading.Timer(2, hello, ["bb"], {arg: 1})

See http://docs.python.org/release/1.5.1p1/tut/keywordArgs.html for information about keyword arguments.

Glenn Maynard
  • 53,510
  • 10
  • 114
  • 128
  • 1
    Here's a link to the [section on keyword arguments](http://docs.python.org/tutorial/controlflow.html#keyword-arguments) in a more up-to-date version of tutorial (although the information looks about the same). – martineau Dec 11 '10 at 09:26
  • 1
    Google kept dropping me in that version. Ironically, the older version is easier to read; they've gone so far overboard with the styling in the newer ones that it's distracting, with the background color spastically jumping back and forth. – Glenn Maynard Dec 11 '10 at 19:19
4

The third argument to Timer is a sequence. Since you pass "bb" as that sequence, hello gets the elements of that sequence ("b" and "b") as separate arguments (arg and kargs). Put "bb" in a list and hello will get the string as the first argument.

t = threading.Timer(2, hello, ["bb"])

As for hello's parameters, you probably mean:

def hello(*args, **kwargs):

The meaning of **kwargs is covered in the queston "What does *args and **kwargs mean?"

Community
  • 1
  • 1
outis
  • 72,188
  • 19
  • 145
  • 210