Defining Functions in Python

1. Default Value Parameters

Specifying default values for parameters is a very useful approach. When calling a function, you can use fewer parameters than defined.

# Default values: retries, reminder
def ask_ok(prompt, retries=4, reminder='Please try again!'):    while True:        reply = input(prompt)        if reply in ('y', 'ye', 'yes'):   # The keyword 'in' is used to confirm if a value is in the sequence            return True        if reply in ('n', 'no', 'nop', 'nope'):            return False        retries = retries - 1        if retries < 0:            raise ValueError('invalid user response')        print(reminder)# Only provide required positional argumentask_ok('Do you really want to quit?')# Do you really want to quit?# Please try again!# Provide an optional argumentask_ok('OK to overwrite the file?', 2)# OK to overwrite the file?# Please try again!# Provide all argumentsask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')# OK to overwrite the file?# Come on, only yes or no!

2. Keyword Arguments

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):    print("-- This parrot wouldn't", action, end='')    print("if you put", voltage, "volts through it.")    print("-- Lovely plumage, the", type)    print("-- It's", state, "!")# One positional argumentparrot(1000)# One keyword argumentparrot(voltage=1000)# Two keyword argumentsparrot(voltage=100000, action="VOOOOM")# Two keyword argumentsparrot(action="VOOOOM", voltage=100000)# Three positional argumentsparrot('a million', 'bereft of life', 'jump')# One positional argument, one keyword argumentparrot('a thousand', state='pushing up the daisies')## Error casesparrot() # Missing required argumentparrot(voltage=5.0, 'dead') # Non-keyword argument after keyword argumentparrot(110, voltage=220) # Duplicate value for the same parameterparrot(actor="John Cleese") # Unknown keyword argument

When calling a function, keyword arguments must follow positional arguments.

All passed keyword arguments must match a parameter accepted by the function, and the order of keyword arguments does not matter.

You cannot assign a value to the same parameter multiple times.

3. Special Parameters

By default, parameters can be passed to Python functions either by position or explicitly as keywords.

def f(pos1, pos2, /, pos_or_kwd, * , kwd1, kwd2):    print(pos1, pos2, pos_or_kwd, kwd1, kwd2)# / and * are optional. These symbols indicate how parameter values are passed to the function# positional, positional, positional or keyword, keyword, keyword
  • Positional-only parameters should be placed before the / (forward slash).

  • / is used to logically separate positional-only parameters from other parameters. If there is no / in the function definition, it indicates that there are no positional-only parameters.

  • After / can be either positional or keyword parameters or keyword-only parameters.

  • Using positional-only parameters can prevent users from using parameter names. This is useful when parameter names have no real significance, when enforcing the order of positional arguments, or when receiving both positional and keyword arguments.
  • When parameter names have real significance, and explicit names can make the function definition easier to understand, use keywords to prevent users from relying on the order of positional arguments.
  • For APIs, using positional-only parameters can prevent destructive API changes when modifying parameter names in the future.

4. Arbitrary Argument Lists

Using an arbitrary number of arguments when calling a function is the least common option. These arguments are contained in a tuple. There may be several regular parameters before the variable number of arguments.

# *args can only be used as keyword arguments, not as positional arguments
def write_multiple_items(file, separator, *args):    file.write(separator.join(args))

5. Unpacking Argument Lists

Function calls require independent positional arguments, but when arguments are in a list or tuple, the opposite operation must be performed.

>>> list(range(3,6)) # Normal call with two parameters[3, 4, 5]
>>> args = [3,6]
>>> list(range(*args)) # Call with parameters unpacked from a list[3, 4, 5]

Similarly, dictionaries can be passed as keyword arguments using the ** operator.

def parrot(voltage, state='a stiff', action='voom'):    print("-- This parrot wouldn't", action, end=' ')    print("if you put", voltage, "volts through it.", end=' ')    print("E's", state, "!")
d = {"voltage": "four million", "state": "bleedin demised", "action": "VOOM"}parrot(**d)# -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin demised !

6. Lambda Expressions

The lambda keyword is used to create small anonymous functions.

def make_incrementor(n):    return lambda x: x + n
f = make_incrementor(42)
print(f(0)) # 42
print(f(1)) # 43

Leave a Comment