smartyfy.mrindigi.com

Python Master Course V2 — 056. Flexible Arguments: *args and **kwargs

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

Flexible Arguments: *args and **kwargs

Estimated study: 60–90 minutes. Prerequisite: Lesson 55, 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

Collect positional and named arguments safely. Explain the concepts in your own words, implement the pattern, predict output, test boundary conditions, and refactor for readability.

Concepts and professional approach

Collect positional and named arguments safely. 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: Flexible Arguments: *args and **kwargs

Collection in a definition, expansion in a call

A function sometimes accepts a varying number of values: a total can combine two measurements or twenty. In a definition, a parameter preceded by one star collects extra positional arguments into a tuple. A parameter preceded by two stars collects otherwise unmatched keyword arguments into a dictionary. The stars are syntax; the conventional names args and kwargs are not required. Prefer descriptive names such as values and metadata when they explain the collected data.

Python code

def inspect_inputs(*values, **metadata):
    print(values)
    print(metadata)

inspect_inputs(2, 5, unit="points", source="quiz")
inspect_inputs()

Expected output

(2, 5)
{'unit': 'points', 'source': 'quiz'}
()
{}

An empty call supplies an empty tuple and dictionary. Collection does not validate the contents, flatten nested lists, or convert strings into numbers. inspect_inputs([2, 5]) receives one positional argument, the list itself. At the call site, * has the opposite role: it expands an iterable into positional arguments. Similarly, ** expands a mapping into keyword arguments; the keys used for keyword names must be strings.

Python code

def inspect_inputs(*values, **metadata):
    print(values)
    print(metadata)

values = [2, 5]
labels = {"unit": "points"}
inspect_inputs(*values, **labels)

Expected output

(2, 5)
{'unit': 'points'}

Combine flexibility with an honest numeric contract

The following summary accepts any number of ordinary built-in integers, with booleans excluded, and one keyword-only label. Restricting this first version to integers makes its behavior clear without introducing mixed Decimal and float arithmetic or nonfinite values. An empty numeric input is allowed and has total zero. Validation identifies the offending argument position before performing arithmetic.

Python code

def summarize(*values, label="Total"):
    if not isinstance(label, str) or not label.strip():
        raise ValueError("label must be a nonempty string")
    for position, value in enumerate(values, start=1):
        if type(value) is not int:
            raise TypeError(f"value {position} must be an integer")
    return {"label": label.strip(), "count": len(values), "total": sum(values)}

print(summarize(2, 3, 5, label="Points"))
print(summarize())

Expected output

{'label': 'Points', 'count': 3, 'total': 10}
{'label': 'Total', 'count': 0, 'total': 0}

Because label follows the starred positional parameter, callers must name it. A final dictionary is not magically interpreted as settings: use **settings to expand it. If two expanded mappings, or an explicit keyword and a mapping, supply label twice, the call raises TypeError. Python does not use last-wins dictionary-update behavior when binding duplicate keyword arguments to a function call.

Use unrestricted keywords deliberately

The general signature order is ordinary parameters, a starred positional collector if needed, keyword-only parameters, then a double-star keyword collector. Do not add collectors to every function. An explicit signature makes misspelled options fail immediately. A function with unrestricted **metadata may quietly accept lable when the caller intended label. Either document that arbitrary metadata is allowed or validate a set of permitted keys and reject unknown ones.

For a labeled report, keep numerical inputs and descriptive settings separate. The summary returns data so another function can display it. Test a normal call, zero values, an expanded list, a boolean, and an unexpected keyword. If you later broaden the accepted number types, update the contract and tests together instead of assuming every object accepted by sum is appropriate for the application.

Progressive runnable Python example

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

def total(*values):
    return sum(values)
def profile(**fields):
    return fields
print(total(2, 3, 5))
print(profile(role='student'))

Expected output:

10
{'role': 'student'}

This warm-up demonstrates argument collection only. sum does not enforce an application-specific integer contract, and profile deliberately accepts arbitrary metadata keys. Use the validated summary above when those stricter rules are required.

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 flexible numeric summary and labeled metadata builder. 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

Distinguish the star syntax in the definition from star syntax in a call.

1. What types do *values and **metadata receive inside inspect_inputs?

Answer and reasoning: Values is a tuple and metadata is a dictionary. An omitted group becomes an empty collection. Their names are arbitrary; the stars determine the collection behavior.

2. How do summarize([2, 3]) and summarize(*[2, 3]) differ?

Answer and reasoning: The first passes one list, which the strict integer check rejects with TypeError. The second expands the list into two integer arguments and returns a count of 2 and total of 5.

3. Why does summarize(2, label="A", **{"label": "B"}) fail?

Answer and reasoning: It supplies the label keyword twice. Function-call argument binding rejects the conflict with TypeError rather than selecting either value. Remove the duplicate before calling.

4. Can summarize(2, 3, "Points") set the label?

Answer and reasoning: No. All three arguments enter values, so the string fails integer validation. Label is keyword-only; use summarize(2, 3, label="Points").

5. Why does summarize reject True even though sum([True, 2]) works?

Answer and reasoning: Bool is a subclass of int and arithmetic treats True like 1, but this summary contract accepts ordinary integers only. type(value) is int deliberately excludes booleans and integer subclasses; this is a design choice, not a universal rule for all numerical functions.

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.