On this page
  1. python functions
  2. *args (Variadic Positional Arguments)
  3. **kwargs & Keyword-Only Arguments
  4. Positional-Only, Positional-or-Keyword, and Keyword-Only (/, *)

python functions

Prev: python fundamentals | Up: python3 | Next: python decorators
Rel: python3, python decorators, python fundamentals, Functions Tutorial, functools
Ref: docs.python.org — Defining Functions
Tags: #public #python3 #functions


*args (Variadic Positional Arguments)

Use *args when accepting an arbitrary number of positional arguments, or * to unpack an iterable into a function call:

def add_exclaim(*args) -> list[str]:
    if len(args) == 1 and isinstance(args[0], list):
        args = args[0]
    return [f"{a}!" for a in args]

>>> my_strs = ['this', 'is', 'rocket', 'science', 2]
>>> add_exclaim(*my_strs)
['this!', 'is!', 'rocket!', 'science!', '2!']
>>> add_exclaim(my_strs)
['this!', 'is!', 'rocket!', 'science!', '2!']

**kwargs & Keyword-Only Arguments

>>> def examp(*, x, y=None):
...     return (x, y)
>>> my_dict = {'x': 'this', 'y': 'that'}
>>> examp(**my_dict)
('this', 'that')

Positional-Only, Positional-or-Keyword, and Keyword-Only (/, *)

def func(pos_only, /, pos_or_kw, *, kw_only):
    pass

Linked from

Related notes