1

Let's suppose I at first have a function with a variable number of positional and keyword arguments, like this:

def print_stuff(*args, **kwargs):
    print("Args: {args}".format(args=args))
    print("Kwargs: {kwargs}".format(kwargs=kwargs))

I would like to add a keyword argument maybe, which I tried like this:

def print_stuff(*args, **kwargs, maybe=False):
    print("Args: {args}".format(args=args))
    print("Kwargs: {kwargs}".format(kwargs=kwargs))
    if maybe:
        print("Maybe!")

However, I get a SyntaxError: invalid syntax. I have considered rewriting it as

def print_stuff(*args, **kwargs):
    print("Args: {args}".format(args=args))
    print("Kwargs: {kwargs}".format(kwargs=kwargs))
    maybe = kwargs.pop('maybe', False)
    if maybe:
        print("Maybe!")

but I find this not so aesthetically pleasing because the argument maybe is no longer in the def line, so to see all the possible arguments you have to read the entire function body.

Is there any more elegant way to do this? (I had a look at https://docs.python.org/3/reference/expressions.html#calls but none was immediately clear to me).

Kurt Peek
  • 52,165
  • 91
  • 301
  • 526

0 Answers0