Search code examples
pythonfunctionarguments

How do I implement **kwargs to omit arguments in a function?


I'm looking for someone who can explain a solution as simply as possible

When making a function, I was wondering if it was possible to optionalize certain arguments in a function. Usually I would get an error saying missing 1 required positional argument: 'arg1'. using **kwargs may work, any way someone can explain this to me?

This is what I'm trying to accomplish.

def myFunc(arg1, arg2, arg3):
    print(arg1)
    print(arg2)
    print(arg3)

myFunc(arg3)

Solution

  • Make all of the args keyword args:

    def myFunc(arg1=None, arg2=None, arg3=None):
        ...
    

    Then call the function with as many or as few of the args as you like:

    myFunc(arg1="hello", arg2="apple")
    myFunc(arg2="goodbye")
    myFunc(arg3="abc")