Arguments & Parameters
Python’s argument system is one of the most flexible in any programming language. It allows you to build APIs that are both descriptive and easy to use. However, with this flexibility comes responsibility—understanding how Python maps arguments to parameters is critical for writing bug-free code.
1. Positional vs. Keyword Arguments
Section titled “1. Positional vs. Keyword Arguments”Positional
Section titled “Positional”By default, Python maps arguments to parameters based on their position.
def power(base, exponent): return base ** exponent
power(2, 3) # base=2, exponent=3Keyword
Section titled “Keyword”You can ignore the order by explicitly naming the parameters. This makes code significantly more readable.
power(exponent=3, base=2)2. Default Values & The Mutation Trap
Section titled “2. Default Values & The Mutation Trap”Parameters can have default values. If the caller omits the argument, the default is used.
3. Variadic Arguments: *args and **kwargs
Section titled “3. Variadic Arguments: *args and **kwargs”Sometimes a function needs to handle an unknown number of inputs.
*args(Positional): Collects extra positional arguments into a Tuple.**kwargs(Keyword): Collects extra keyword arguments into a Dictionary.
def setup_user(name, *roles, **metadata): print(f"User: {name}") print(f"Roles: {roles}") # Tuple print(f"Metadata: {metadata}") # Dictionary
setup_user("Alice", "Admin", "Editor", theme="dark", lang="en")4. Advanced Constraints: / and *
Section titled “4. Advanced Constraints: / and *”In modern Python (3.8+), you can force callers to use specific argument styles.
Positional-Only (/)
Section titled “Positional-Only (/)”Arguments before the / must be positional. This is common in low-level library functions.
def incr(x, /): return x + 1
# incr(x=5) # TypeError!Keyword-Only (*)
Section titled “Keyword-Only (*)”Arguments after the * must be passed as keywords. This is excellent for ensuring clarity in functions with many parameters.
def send_email(to, *, subject, body): pass
# send_email("a@b.com", "Hello", "Body") # TypeError!send_email("a@b.com", subject="Hello", body="Body") # Correct5. Under the Hood: Argument Unpacking
Section titled “5. Under the Hood: Argument Unpacking”You can “explode” a list or dictionary into individual function arguments using the same * and ** operators.
data = {"subject": "Alert", "body": "Disk full"}send_email("admin@server.com", **data) # Unpacks dict into keywordsSummary Table
Section titled “Summary Table”| Syntax | Name | Use Case |
|---|---|---|
name | Positional/Keyword | Standard parameter. |
name=val | Default | Optional parameter. |
*args | Variadic Positional | Handle any number of items. |
**kwargs | Variadic Keyword | Handle any number of settings/flags. |
/ | Positional-Only Marker | Force no keyword use. |
* | Keyword-Only Marker | Force explicit keywords for clarity. |