Sub topic 1
Python Default and Keyword Arguments
Prerequisites
This chapter assumes you can define and call Python functions, use basic numbers, strings, lists, dictionaries, and None, and read simple tracebacks.
Parameters and arguments: the vocabulary
A parameter is a name in a function definition. It describes a value the function can receive. An argument is the actual value supplied when the function is called.
def greet(name): # name is a parameter
return f"Hello, {name}"
greet("Ada") # "Ada" is an argumentPython binds each argument to a parameter. This binding determines which value each parameter receives.
Calling functions by position and by keyword
A positional argument is matched by its place in the call. A keyword argument names its parameter explicitly.
def connect(host, port):
return f"{host}:{port}"
print(connect("db.local", 5432))
print(connect(host="db.local", port=5432))
print(connect("db.local", port=5432))The last call mixes styles. Positional arguments must come before keyword arguments. A parameter cannot receive two values:
# connect("db.local", host="other.local")
# TypeError: got multiple values for argument 'host'Giving parameters default values
A default value is used when the caller omits that argument.
def greet(name, greeting="Hello", punctuation="!"):
return f"{greeting}, {name}{punctuation}"
print(greet("Ada"))
print(greet("Ada", "Hi"))
print(greet("Ada", punctuation="?"))A required parameter has no default. A parameter with a default is optional at the call site. In a definition, required parameters must come before parameters with defaults.
Where each kind of parameter may appear
Python supports several parameter categories. The / marker ends positional-only parameters. The * marker begins keyword-only parameters. Parameters between them normally accept either style.
def configure(path, /, mode="read", *, encoding="utf-8"):
return path, mode, encoding
print(configure("data.txt", encoding="ascii"))Here, path must be positional, mode can be positional or keyword, and encoding must be keyword-based.
Exercise
In def f(x, y=10, *, scale=1):, which call is valid: f(3, 2, 4) or f(3, scale=4)?
Show answer
f(3, scale=4) is valid. scale is keyword-only because it follows *.