bhylu.com

Advertisements

Python Arguments

Arguments supply values to a function's parameters. Positional arguments follow order, while keyword arguments name the intended parameter explicitly.

Understand the idea

Default values are evaluated when the function is defined, not afresh for every call. This matters when the default is mutable. Use None and construct a new list inside when each call needs an independent container. A keyword-only parameter can make a safety-sensitive option explicit at the call site.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

def label(name, *, city="Nadiad"):
    return f"{name} / {city}"

print(label("Mira", city="Surat"))

Read the result

The output is Mira / Surat. city must be supplied by name if the caller overrides it.

Try one change

Write a function with an optional list input that never shares an accidental default list between calls.