On this page
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
- Parameters after
*in a function definition are keyword-only (def examp(*, x, y=None): ...). - Dictionaries can be unpacked into keyword arguments using
**:
>>> 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
- tuts/python3/tutorials/core_fundamentals/functions Linked here; links to this page; shared tags: #functions
- tuts/python3 Linked here; links to this page
- tuts/python3/python decorators Linked here; links to this page
- tuts/python3/python fundamentals Linked here; links to this page
- tuts/python3/stdlib_module/functools Linked here
- tuts/python3/tutorials links to this page
- tuts/python3/tutorials/core_fundamentals links to this page
- tuts/css/functions shared tags: #functions
- tuts/css/functions/color shared tags: #functions
- tuts/css/functions/color/color-mix shared tags: #functions