VMware ESXi and vSphere Cluster Management

Default Values for Function Parameters in Python

Learn how Python function defaults work, how to override them, and when to use positional, keyword, and safe None-based arguments.

A function parameter is a named input declared in a function definition. An argument is the value supplied when the function is called. Python lets you assign a value to a parameter in the function definition. That value is the parameter's default parameter value: Python uses it when the caller omits that argument.

Defaults make optional inputs possible while keeping common function calls short. A caller can accept the usual behavior or provide a different value when needed.

See also: Default values for parameters.

Defining a Function with Default Values

Write a default using parameter_name=default_value inside the parameter list:

def greet(name="friend"):
    print(f"Hello, {name}!")

greet()
greet("Mina")

The first call omits name, so Python uses "friend". The second call supplies "Mina", so that value replaces the default.

Defaults can be strings, numbers, booleans, None, and other Python values:

def configure(retries=3, verbose=False, label="standard", timeout=None):
    print(retries, verbose, label, timeout)

configure()
# 3 False standard None

When every parameter has a default, the function can be called with no arguments. This is useful when the defaults describe the most common case.

Example: A Profile Function

This function gives all three parameters defaults, so an empty call is valid:

def describe_profile(name="Alex", gender="unspecified", website="not provided"):
    return f"Name: {name}; Gender: {gender}; Website: {website}"

print(describe_profile())
# Name: Alex; Gender: unspecified; Website: not provided

The no-argument call uses every default. Explicit arguments override the corresponding defaults:

print(describe_profile("Jordan", "nonbinary", "example.com"))
# Name: Jordan; Gender: nonbinary; Website: example.com

A default is only a fallback. If the caller supplies a value, Python uses the supplied value for that call.

Required and Optional Parameters Together

A required parameter has no default and must receive an argument. An optional parameter has a default and may be omitted.

def describe_profile(name, gender, website="not provided"):
    return f"Name: {name}; Gender: {gender}; Website: {website}"

print(describe_profile("Jordan", "nonbinary"))
# Name: Jordan; Gender: nonbinary; Website: not provided

name and gender are required. The call supplies both and omits website, so Python assigns the default string to website.

Call styleArgument supplied?How the parameter is matchedValue used
No argument for a defaulted parameterNoPython uses the parameter's declared defaultThe default value
Positional argument suppliedYesMatched by its position in the callThe supplied value
Keyword argument suppliedYesMatched by the parameter nameThe supplied value
Required parameter omittedNoNo value can be obtainedPython raises a missing-argument error

Parameter Ordering Rules

In a normal function signature, parameters without defaults must come before parameters with defaults. The valid pattern is:

def function(required_parameter, optional_parameter="default"):
    pass

This definition is invalid because a required parameter follows a defaulted parameter:

def function(optional_parameter="default", required_parameter):
    pass

Python reports a syntax error before the function can be used. Move all required parameters earlier, or give the later parameter a default if it should really be optional.

Positional Arguments with Defaults

A positional argument is matched to a parameter according to its order in the call. Positional arguments can omit trailing optional parameters:

def connect(host, port=443, secure=True):
    print(host, port, secure)

connect("example.org")
# example.org 443 True

connect("example.org", 8080)
# example.org 8080 True

connect("example.org", 8080, False)
# example.org 8080 False

When using positional arguments, the values must be in the declared order. Python does not infer what a value was intended to mean:

def describe_profile(name, gender, website="not provided"):
    print(f"Name: {name}; Gender: {gender}; Website: {website}")

describe_profile("Jordan", "nonbinary")
# Name: Jordan; Gender: nonbinary; Website: not provided

describe_profile("nonbinary", "Jordan")
# Name: nonbinary; Gender: Jordan; Website: not provided

The second call is syntactically valid, but its values are assigned to the wrong parameters because their positions were reversed.

Keyword Arguments with Defaults

A keyword argument names the parameter explicitly, such as name="Jordan". Keyword arguments are matched by parameter name rather than by position.

def describe_profile(name, gender, website="not provided"):
    return f"Name: {name}; Gender: {gender}; Website: {website}"

print(describe_profile(gender="nonbinary", name="Jordan"))
# Name: Jordan; Gender: nonbinary; Website: not provided

This call supplies the two required values in a different order and omits website. The names ensure that each value reaches the intended parameter.

In a call, positional arguments must come before keyword arguments. For example:

describe_profile("Jordan", gender="nonbinary")

# Equivalent to:
describe_profile(name="Jordan", gender="nonbinary")

Do not provide the same parameter twice:

describe_profile("Jordan", name="Taylor")  # TypeError
FeaturePositional argumentsKeyword arguments
Matching methodBy argument orderBy parameter name
Order sensitivityHigh; values must be in the declared orderLower; named arguments can be reordered
ReadabilityConcise for short, obvious callsClearer because each value is labeled
Risk of swapping similarly shaped valuesHigherLower
Use with omitted defaulted parametersOmit trailing optional argumentsName the needed parameters and omit any defaulted one

Choosing Positional or Keyword Calls

  • Use positional arguments when the function has a few parameters and their order is obvious.
  • Use keyword arguments when several parameters have similar types, when the call has many options, or when readability matters.
  • Use keywords to prevent accidental swapping, especially for fields such as name and gender, which may both contain strings.
# Concise, but the meaning depends on position
save_profile("Jordan", "nonbinary")

# More explicit and safer to read
save_profile(name="Jordan", gender="nonbinary")

Safe Defaults for Lists and Dictionaries

Default expressions are evaluated once, when Python creates the function, not afresh on every call. This is safe for immutable values such as strings and numbers, but it can cause problems with mutable objects.

A list or dictionary is mutable: a function can change it. If a mutable object is used directly as a default, the same object may be reused across calls.

def add_tag(tag, tags=[]):
    tags.append(tag)
    return tags

print(add_tag("python"))  # ['python']
print(add_tag("functions"))  # ['python', 'functions']

The second call sees the list changed by the first call. This shared-state behavior is usually unintended.

Use None as a None sentinel: it represents an omitted value, and the function creates a fresh list or dictionary inside its body.

def add_tag(tag, tags=None):
    if tags is None:
        tags = []
    tags.append(tag)
    return tags

print(add_tag("python"))  # ['python']
print(add_tag("functions"))  # ['functions']

The two calls now receive separate lists. The same pattern works for dictionaries:

def add_setting(key, value, settings=None):
    if settings is None:
        settings = {}
    settings[key] = value
    return settings
Default typeTypical useSafe to use directly?Recommended approach
Immutable stringDefault label or nameYesUse the string directly
NumberCount, limit, or timeoutYesUse the number directly
BooleanFeature switchYesUse True or False directly
NoneMissing or not-yet-created valueYesUse it as a sentinel and initialize inside the function
ListCollection that may be changedNo, if mutatedUse None, then create [] inside
DictionarySettings or lookup data that may be changedNo, if mutatedUse None, then create {} inside

Troubleshooting Common Problems

A required parameter follows a defaulted parameter

Cause: The function signature violates Python's ordering rule.

def report(format="text", title):  # SyntaxError

Fix: Put required parameters first:

def report(title, format="text"):
    pass

Values appear under the wrong labels

Cause: Positional arguments were passed in the wrong order.

Fix: Follow the declared order or use keywords such as name=... and gender=....

An optional value was not replaced by its default

Cause: The caller explicitly supplied a value. Supplied arguments always override defaults.

Fix: Omit the argument to use the default, or deliberately pass the replacement value you want.

Values from an earlier call appear in a later call

Cause: A list or dictionary default was mutated and shared between calls.

Fix: Use None as the default and create a new collection inside the function.

A call reports a missing required argument

Cause: A parameter without a default was omitted.

Fix: Provide the value positionally or by keyword, or redesign the parameter with an appropriate default if the input should be optional.

Key Points

  • A default parameter value is assigned in the function signature and is used when the caller omits that argument.
  • Arguments supplied by the caller override defaults for that call.
  • Required parameters must come before defaulted parameters in a normal signature.
  • Positional arguments depend on order; keyword arguments depend on parameter names.
  • Keyword calls are often safer when values have similar types or when clarity is important.
  • Never use a mutable list or dictionary directly as a default when the function mutates it; use the None sentinel pattern instead.