0

for some reason I am having trouble passing *args and **kwargs to both a threading.Timer() and a function...here is the code I am having trouble with;

from threading import Timer

def print_me(text='foo'):
    print(text)

def repeat_task(delay, action, *args, **kwargs):
    Timer(delay, repeat_task, (delay, action, [*args], {**kwargs}).start()
    action(*args, **kwargs)

repeat_task( 5, print_me, text='bar' )

if anyone could point me in the right direction I would be very appreciative. :)

1 Answer 1

1

[*args] and {**kwargs} are both invalid syntax. kwargs is already a dict, so if you want it as a dict, just use it directly. args is a tuple, so if you want its value as a tuple, just use it directly, and if you want to turn it into a list for some reason, you can use list(args).

You're passing these arguments to Timer(), whose parameters are defined as:

Timer(interval, function, args=None, kwargs=None)

Notice that there are no *s there: the args and kwargs parameters for this constructor are normal parameters.

So your third argument needs to be all your positional arguments: delay and action, then all the contents of args. One way to do this is to add lists together with +:

[delay, action] + list(args)

And your fourth argument needs to be the keyword arguments, which is just kwargs.

So this should work:

Timer(delay, repeat_task, [delay, action] + list(args), kwargs).start()
2
  • aaah you are right, however it isn't that line spitting out the error...it is this one "action(args, kwargs)" (I probably should have clarified that in my question) the error says "TypeError: unorderable types: dict() >= int()" Apr 12, 2016 at 23:47
  • eer acutally that is a new error...your comment actually fixed it. :) now I need to figure out this new error...lol Apr 12, 2016 at 23:58

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.