Why does this function receive 2 positional variables when it is only given one?

1 day ago 3
ARTICLE AD BOX

It appears that when you code the following:

keyboard.add_hotkey('left', move, [0, -1])

It is interpreting the third argument as an iterable that specifies the arguments to be passed. In this case the iterable is a list of two elements, 0 and -1, and so move will be called like move(0, 1). If you want move to be called with a single argument that is an iterable of two integers, then:

keyboard.add_hotkey('left', move, [[0, -1]]) # or keyboard.add_hotkey('left', move, [(0, -1)]) # or keyboard.add_hotkey('left', move, ((0, -1),)) # or etc.

So your code can be greatly simplified with:

import keyboard actions = [ ('left', move, [(0, -1)]), ('right', move, [(0, 1)]), ('up', rotate, ['left']), ('down', rotate, ['right']) ] for action in actions: # action takes on each element of actions keyboard.add_hotkey(*action) # unpacks action as individual arguments

Note that I have used tuples in place of some of the lists hoping that it makes the code easier to read.

Read Entire Article