pythondefault-arguments

Python: explicitly use a function's default arguments


Under normal circumstances one calls a function with its default arguments by omitting those arguments. However if I'm generating arguments on the fly, omitting one isn't always easy or elegant. Is there a way to use a function's default argument explicitly? That is, to pass an argument which points back to the default argument.

So something like this except with ~use default~ replaced with something intelligent.

def function(arg='default'):
  print(arg)

arg_list= ['not_default', ~use default~ ]

for arg in arg_list:
  function(arg=arg)

# output:
# not_default
# default

I don't know if it's even possible and given the term "default argument" all my searches come up with is coders first tutorial. If this functionality is not supported that's ok too, I'd just like to know.


Solution

  • Unfortunately there is no such feature in Python. There are hackarounds, but they're not very likable.

    The simple and popular pattern is to move the default into the function body:

    def function(arg=None):
        if arg is None:
            arg = 'default'
        ...
    

    Now you can either omit the argument or pass arg=None explicitly to take on the default value.