liveBook · Manning

Function argument

As explained in Python Workout, Second Edition

A function argument is a value supplied to a function call for use by the corresponding parameter.

A function argument is a value supplied at a call site for a corresponding parameter. Python supports required arguments, optional arguments with defaults, positional expansion with *, and keyword expansion with **. section 2.7 section 7.3

Choose the argument form according to the function’s input contract:

  • Use named parameters for a known set of values; use a default when an argument is optional. section 7.3
  • Use *args when the number of positional values is unknown and the function will process the resulting tuple iteratively. section 2.7
  • Prefix an iterable with * at the call site to turn its elements into separate positional arguments. section 2.7
  • Use **kwargs to collect arbitrary name=value arguments in a dictionary for keyword-based processing. section 7.3

Unpacking a sequence

Calling mysum([1, 2, 3]) passes one argument—the list—whereas mysum(*[1, 2, 3]) passes three numeric arguments. The first form can therefore produce a TypeError when the function adds its arguments. section 2.7

def myxml(tagname, content='', **kwargs):
    attrs = ''.join([f' {key}="{value}"'
                     for key, value in kwargs.items()])
    return f'<{tagname}{attrs}>{content}</{tagname}>'

A function combines a required argument, an optional defaulted argument, and keyword arguments while converting the collected dictionary into XML attributes. section 7.3

How Python Workout, Second Edition covers it

How deep it goes
Explains defaults, tuple collection, iterable unpacking, and dictionary-based keyword processing, stopping short of deeper call mechanics.
Examples
Uses a variable-argument summation function and an XML-tag function with optional content and keyword-generated attributes.
What it assumes
Assumes function-call familiarity while reinforcing tuples, iteration, dictionaries, and list comprehensions through argument handling.
What you can do after
Apply it via Python function calls that pass optional values, unpack iterables, or supply arbitrary keyword pairs.
How it connects
Connects arguments with parameters, tuples, iterables, default values, keyword arguments, dictionaries, and list comprehensions.

Also explained in

Compare how 5 books explain function argument →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.