smartyfy.mrindigi.com

Python Master Course V2 — 054. Default and Keyword Arguments

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 06 · LESSON 054 / 200

Default and Keyword Arguments

Estimated study: 60–90 minutes. Prerequisite: Lesson 53, plus Python variables, collections, conditions and loops.

Course hub

Video lesson

Video not yet available. This is a reserved video link/player location.

Learning objectives

Design readable interfaces with safe defaults. Explain the concepts in your own words, implement the pattern, predict output, test boundary conditions, and refactor for readability.

Concepts and professional approach

Design readable interfaces with safe defaults. A function creates a reusable abstraction: it accepts inputs, performs a focused responsibility, and may return an output. Prefer small named functions with clear contracts. Validate external inputs at system boundaries, choose meaningful names, and separate calculation from printing so functions can be tested. Avoid hidden state where possible. Study the example, then change the inputs and explain the result.

Professional design checklist: define the purpose; choose inputs and outputs; consider invalid and edge-case values; write a minimal implementation; test normal, boundary and failure paths; then document the contract.

Understand and apply: Default and Keyword Arguments

Defaults are part of an interface

The worked function below is a deliberate keyword-only variant. The introductory label function retained later in this lesson allows prefix either positionally or by keyword; its signature has no standalone star.

A default supplies a parameter value when a caller leaves that argument out. Choose defaults for genuinely common, safe behavior, rather than to hide a missing required input. In a reporting helper, a standard label can make calls concise while a keyword override makes unusual behavior explicit. An empty string and None are still explicit arguments; Python does not replace them with the default merely because they look empty.

Python code

def label(text, *, prefix="Item"):
    return f"{prefix}: {text}"

print(label("Notebook"))
print(label("Notebook", prefix="Stock"))
print(label("Notebook", prefix=""))

Expected output

Item: Notebook
Stock: Notebook
: Notebook

Here text is required, prefix is optional, and the star requires callers to name prefix if they override it. A call such as label("Notebook", "Stock") raises TypeError. Keyword-only configuration is useful when several settings have the same type and could otherwise be swapped. Adding this restriction to an existing public function can break callers, so introduce it deliberately rather than silently changing an established interface.

A default is created when the definition executes

Default expressions are evaluated once for each execution of the function definition, not anew on every call. This is harmless for an immutable string that is never changed. It matters for a list, because several calls can receive the same list object. Appending changes that object, so the next omitted-argument call observes earlier work. The following bug demonstration should be run as one fresh block; repeating calls without redefining the function accumulates more items.

Python code

def remember_bad(item, history=[]):
    history.append(item)
    return history

first = remember_bad("alpha")
second = remember_bad("beta")
print(first)
print(second)
print(first is second)

Expected output

['alpha', 'beta']
['alpha', 'beta']
True

The first variable does not hold a frozen snapshot. It refers to the same list as second, so the later append is visible through both names. This is not caused by a global declaration or by Python copying arguments incorrectly. The shared object came from the definition-time default. Replacing append with a new-list construction could change the behavior, but a clear no-shared-default design is easier for beginners to maintain.

Use None to request a fresh collection

Python code

def remember(item, history=None):
    if history is None:
        history = []
    history.append(item)
    return history

print(remember("alpha"))
print(remember("beta"))
existing = ["start"]
print(remember("next", existing))
print(existing)

Expected output

['alpha']
['beta']
['start', 'next']
['start', 'next']

None is a sentinel meaning no collection was supplied. The function creates a fresh list only in that case. An explicitly supplied list is intentionally modified, as the last two lines show. State this mutation in the contract. If callers should retain their original list unchanged, copy it with list(history) before appending. A safe default does not by itself promise that supplied objects will never be modified.

Use is None, not if not history, because an empty caller-owned list is a valid supplied object. Also remember that changing an outer variable later does not update an already evaluated default. When a value must be calculated at call time, use a sentinel and calculate it inside the body. Test two independent omitted-argument calls, an explicit empty list, and a nonempty supplied list; a single call cannot expose a shared-default defect.

Progressive runnable Python example

Requires Python 3.10+. Save as lesson54.py, run with python lesson54.py or python3 lesson54.py.

def label(text, prefix='Item'):
    return f'{prefix}: {text}'
print(label('Notebook'))
print(label('Notebook', prefix='Stock'))

Expected output:

Item: Notebook
Stock: Notebook

Additional exploration

Run the example with different valid inputs. Predict the result before executing. Extract repeated operations into a named function and write at least one assertion for the expected output. For invalid inputs, decide whether to return a documented result or raise an informative exception.

Guided practical project

Create a reporting function with configurable labels. Start with a short requirements table identifying inputs, outputs and validation rules. Implement the smallest working function first, add a separate caller, and test at least three scenarios: typical input, boundary input and invalid input. Print a labeled report only at the program’s outermost layer.

Acceptance criteria: results are deterministic for the same inputs; no unexpected shared mutable state; invalid input is handled deliberately; output is documented; at least three assertions are included in your local project.

Common mistakes and debugging

  • Confusing print with return; printing does not pass a value back to the caller.
  • Using ambiguous names or overly long functions; divide responsibilities clearly.
  • Assuming all inputs are valid; validate values at appropriate boundaries.
  • Relying on global mutable variables; pass dependencies explicitly.
  • Skipping edge-case tests; test zero, empty, negative or missing values as applicable.

Practice and explained answers

Try each question before opening its answer. These self-checks do not record course completion.

Optional hint for question 1

Ask whether each variable stores a snapshot or refers to the same mutable object.

1. Why do first and second both show two items in remember_bad?

Answer and reasoning: Both variables refer to the same default list. The second call mutates that list, and reading first afterward reveals the mutation. The returned references are aliases, not independent snapshots.

2. Repair a list default when each omitted-argument call needs fresh state.

Answer and reasoning: Use history=None, then if history is None: history = [] inside the function. A new list is constructed during each such call. Do not leave the empty list in the signature.

3. Why is if not history an imperfect replacement for if history is None?

Answer and reasoning: It also matches a caller-supplied empty list. Replacing that list would change which object receives the append. The identity check distinguishes absence from an intentionally supplied, currently empty collection.

4. What happens if prefix is an empty string in label?

Answer and reasoning: The explicit empty string is used, yielding : Notebook. Defaults apply to omitted arguments. Rejecting an empty prefix would require an additional documented validation rule.

5. If rate = 2 precedes def scale(x, factor=rate), then rate becomes 5, what is scale(3)?

Answer and reasoning: It returns 6 if the body is return x * factor. The default captured the value 2 when the definition executed. A later reassignment of rate does not re-evaluate that default expression.

Mastery checkpoint

Before moving on, explain the lesson concept, run the example, complete the project, write three tests, and explain why your function design is maintainable. The five-question self-check above provides answer explanations; it does not store account-level completion.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.