Search code examples
pythonfunctionwinapiargs

How do I call a function with an optional and an *args arguments?


How do I call my function

def press(clickLeft=False, *args):
    buttons = {'Enter': 0x0D, 'Ctrl': 0x11, 'a': 0x41,'c': 0x43, 'v': 0x56}
    codes = [buttons[b] for b in args]
    for b in codes:
        win32api.keybd_event(b, 0,0,0)
    if clickLeft:
        click()

If I call it like this

press('Ctrl', clickLeft=True)

It gives an error

TypeError: press() got multiple values for argument 'clickLeft'

Solution

  • The pythononic convention is for arguments to go before keyword arguments (kwargs). So if you move your args to go before your optional/keyword arguments that should solve the problem:

    def press(*args, clickLeft=False):
       pass
    

    Then you call it as you suggested:

    press('Ctrl', clickLeft=True)