{"course":{"slug":"python-for-ai","title":"Python, from Zero, for AI","url":"https://addaly.com/learn/python-for-ai","level":"beginner","track":"build"},"lesson":{"slug":"arguments-in-depth","title":"Arguments: positional, named, default, and the trap in the default","url":"https://addaly.com/learn/python-for-ai/arguments-in-depth","position":22,"of":89,"minutes":9,"answer":"Default values are created once when the def line runs, so a mutable default is shared by every call, and a function can mutate the object you passed but cannot rebind your name.","keyIdea":"Default values are created once when the `def` line runs, so a mutable default is shared by every call, and a function can mutate the object you passed but cannot rebind your name."},"body":{"format":"markdown","text":"## Four ways to hand a value to a function\n\n```python\ndef send(message, to, retries=3, urgent=False):\n    ...\n\nsend(\"hello\", \"asha@example.com\")                    # positional\nsend(\"hello\", to=\"asha@example.com\")                 # mixed\nsend(to=\"asha@example.com\", message=\"hello\")         # all named, any order\nsend(\"hello\", \"asha@example.com\", 5, True)           # all positional\n```\n\nPositional arguments are matched by order. Named ones are matched by name and can appear in any order, but every positional argument must come before every named one, or you get `SyntaxError: positional argument follows keyword argument`.\n\nThat last call, `send(\"hello\", \"asha@example.com\", 5, True)`, is legal and bad. Six months later nobody knows what `5` and `True` mean. Passing booleans and bare numbers by name (`retries=5, urgent=True`) costs eight characters and removes a whole category of misreading.\n\n## Defaults are evaluated once, when the function is defined\n\nThis is the most famous trap in Python, and it is worth meeting deliberately:\n\n> Figure: One list in a def line, four calls. Timeline: Import, def add(item, basket=[]) runs. One empty list is created, now and never again.; Call 1, add(\"milk\") uses the default. Returns ['milk'].; Call 2, add(\"rice\") uses the same list. Returns ['milk', 'rice']: the surprise.; Call 3, add(\"dal\", []) passes a fresh list, so the default is untouched. Returns ['dal'].; Call 4, add(\"atta\") is back on the default, which still holds two items. Returns three.. The list was created once, when the def statement ran, and it belongs to the function rather than to any call. The fix is always the same: default to None, and make the real list inside the body.\n\n```python\ndef add_item(item, basket=[]):\n    basket.append(item)\n    return basket\n\nprint(add_item(\"rice\"))     # ['rice']\nprint(add_item(\"dal\"))      # ['rice', 'dal']\n```\n\nThe empty list in the `def` line was created **once**, when Python executed the `def` statement, and the same list is reused on every call that does not supply one. Items accumulate across calls forever.\n\nThe mechanism is worth holding on to, because it explains the whole rule: a `def` line is executed like any other statement, and the default expressions in it are evaluated at that moment, not at call time.\n\nThe fix is always the same:\n\n```python\ndef add_item(item, basket=None):\n    if basket is None:\n        basket = []\n    basket.append(item)\n    return basket\n```\n\nImmutable defaults (numbers, strings, `True`, `None`, tuples) cannot be modified, so they are safe. **Never use a list, dict or set as a default value.**\n\nThe same trap has a subtler form: `def log(msg, when=datetime.now())` stamps every message with the time the module was imported.\n\n## `*args` and `**kwargs`\n\nTo accept any number of positional arguments, put a star in front of a name:\n\n```python\ndef total(*amounts):\n    return sum(amounts)\n\ntotal(10, 20, 30)      # amounts is the tuple (10, 20, 30)\n```\n\nTwo stars collects any named arguments into a dictionary:\n\n```python\ndef make_request(url, **options):\n    print(url, options)\n\nmake_request(\"/chat\", timeout=30, stream=True)\n# /chat {'timeout': 30, 'stream': True}\n```\n\nThe names `args` and `kwargs` are convention only; the stars do the work. You will meet them constantly in library code and in wrappers that pass arguments through to something else:\n\n```python\ndef logged_call(func, *args, **kwargs):\n    print(f\"calling {func.__name__}\")\n    return func(*args, **kwargs)\n```\n\nA star in a **call** does the reverse: it unpacks. `func(*[1, 2])` calls `func(1, 2)`, and `func(**{\"a\": 1})` calls `func(a=1)`. Same symbol, opposite direction, decided by whether you are defining or calling.\n\n## Forcing arguments to be named\n\nAnything after a bare `*` in the parameter list can only be passed by name:\n\n```python\ndef resize(image, *, width, height):\n    ...\n\nimg = \"photo.jpg\"                    # sample image value\nresize(img, width=800, height=600)    # fine\nresize(img, 800, 600)                # TypeError\n```\n\nThis is how a library stops you from silently swapping two same-typed arguments, and it is worth doing in your own code for any function with more than about three parameters. It also lets you reorder or add parameters later without breaking callers.\n\nThe mirror image is `/`, which forces the parameters before it to be positional. You mostly meet it in the standard library's documentation rather than writing it yourself.\n\n## Arguments are passed by object reference\n\nPython does not copy what you pass in and does not hand over a pointer to your variable. The function receives the *same object* the caller had:\n\n```python\ndef spoil(items):\n    items.append(\"surprise\")\n\nbasket = [\"rice\"]\nspoil(basket)\nprint(basket)        # ['rice', 'surprise']\n```\n\nThe function mutated the caller's list. But rebinding does not escape:\n\n```python\ndef replace(items):\n    items = [\"new\"]      # rebinds the local name only\n\nbasket = [\"rice\"]\nreplace(basket)\nprint(basket)        # ['rice']\n```\n\nThe one rule that covers both: **mutating the object is visible to the caller; assigning a new object to the parameter name is not.** Half of all confusion about Python's argument passing dissolves once that sentence is in place.\n\nIf a function must not modify what it is given, copy at the top of it, and say so in the docstring. If it is meant to modify in place, return `None`, following the convention that mutating operations do not hand back a value."},"check":{"question":"A caching helper is written as `def remember(key, store={}): store[key] = time.time(); return store`. It is called from two unrelated modules and each reports seeing the other's keys. What is the mechanism?","options":[{"text":"Dictionaries are global in Python unless declared inside a function body with the `local` keyword.","correct":false,"tempting":"Invents a keyword and a scoping rule; ordinary assignment inside a function is already local."},{"text":"The default dictionary was created once when the `def` statement executed, so every call without an explicit `store` shares that one object.","correct":true},{"text":"Both modules imported the same module, and Python re-runs a module's `def` statements on each import, merging the dictionaries.","correct":false,"tempting":"Gets the import caching backwards (a module's body runs once) while the shared state actually comes from the single default object."},{"text":"`store[key] = ...` mutates the caller's dictionary, so the fix is for each caller to pass a copy.","correct":false,"tempting":"Describes real mutation semantics, but here no caller passed anything, so copying at the call site cannot be the fix."}]},"prev":{"slug":"functions","title":"Functions, and the difference between printing and returning","url":"https://addaly.com/learn/python-for-ai/functions"},"next":{"slug":"scope-and-globals","title":"Where a name lives, and why the function cannot see it","url":"https://addaly.com/learn/python-for-ai/scope-and-globals"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Arguments: positional, named, default, and the trap in the default', in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/arguments-in-depth (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Arguments: positional, named, default, and the trap in the default","courseTitle":"Python, from Zero, for AI","module":{"index":3,"slug":"functions-and-structure","title":"Functions, modules, and code you can read again in March"},"answer":null,"keyIdea":"Default values are created once when the `def` line runs, so a mutable default is shared by every call, and a function can mutate the object you passed but cannot rebind your name.","hero":{"kind":"figure","figure":{"t":"figure","label":"Figure","figure":{"caption":"The list was created once, when the def statement ran, and it belongs to the function rather than to any call. The fix is always the same: default to None, and make the real list inside the body.","events":[{"when":"Import","what":"def add(item, basket=[]) runs. One empty list is created, now and never again."},{"when":"Call 1","what":"add(\"milk\") uses the default. Returns ['milk']."},{"when":"Call 2","what":"add(\"rice\") uses the same list. Returns ['milk', 'rice']: the surprise."},{"when":"Call 3","what":"add(\"dal\", []) passes a fresh list, so the default is untouched. Returns ['dal']."},{"when":"Call 4","what":"add(\"atta\") is back on the default, which still holds two items. Returns three."}],"title":"One list in a def line, four calls","type":"timeline"},"alt":"Figure: One list in a def line, four calls. Timeline: Import, def add(item, basket=[]) runs. One empty list is created, now and never again.; Call 1, add(\"milk\") uses the default. Returns ['milk'].; Call 2, add(\"rice\") uses the same list. Returns ['milk', 'rice']: the surprise.; Call 3, add(\"dal\", []) passes a fresh list, so the default is untouched. Returns ['dal'].; Call 4, add(\"atta\") is back on the default, which still holds two items. Returns three.. The list was created once, when the def statement ran, and it belongs to the function rather than to any call. The fix is always the same: default to None, and make the real list inside the body."}},"blocks":[{"t":"h2","id":"four-ways-to-hand-a-value-to-a-function","runs":[{"text":"Four ways to hand a value to a function"}]},{"t":"code","lang":"python","label":"Python","text":"def send(message, to, retries=3, urgent=False):\n    ...\n\nsend(\"hello\", \"asha@example.com\")                    # positional\nsend(\"hello\", to=\"asha@example.com\")                 # mixed\nsend(to=\"asha@example.com\", message=\"hello\")         # all named, any order\nsend(\"hello\", \"asha@example.com\", 5, True)           # all positional"},{"t":"p","runs":[{"text":"Positional arguments are matched by order. Named ones are matched by name and can appear in any order, but every positional argument must come before every named one, or you get "},{"text":"SyntaxError: positional argument follows keyword argument","code":true},{"text":"."}]},{"t":"p","runs":[{"text":"That last call, "},{"text":"send(\"hello\", \"asha@example.com\", 5, True)","code":true},{"text":", is legal and bad. Six months later nobody knows what "},{"text":"5","code":true},{"text":" and "},{"text":"True","code":true},{"text":" mean. Passing booleans and bare numbers by name ("},{"text":"retries=5, urgent=True","code":true},{"text":") costs eight characters and removes a whole category of misreading."}]},{"t":"h2","id":"defaults-are-evaluated-once-when-the-function-is-defined","runs":[{"text":"Defaults are evaluated once, when the function is defined"}]},{"t":"p","runs":[{"text":"This is the most famous trap in Python, and it is worth meeting deliberately:"}]},{"t":"code","lang":"python","label":"Python","text":"def add_item(item, basket=[]):\n    basket.append(item)\n    return basket\n\nprint(add_item(\"rice\"))     # ['rice']\nprint(add_item(\"dal\"))      # ['rice', 'dal']"},{"t":"p","runs":[{"text":"The empty list in the "},{"text":"def","code":true},{"text":" line was created "},{"text":"once","b":true},{"text":", when Python executed the "},{"text":"def","code":true},{"text":" statement, and the same list is reused on every call that does not supply one. Items accumulate across calls forever."}]},{"t":"p","runs":[{"text":"The mechanism is worth holding on to, because it explains the whole rule: a "},{"text":"def","code":true},{"text":" line is executed like any other statement, and the default expressions in it are evaluated at that moment, not at call time."}]},{"t":"p","runs":[{"text":"The fix is always the same:"}]},{"t":"code","lang":"python","label":"Python","text":"def add_item(item, basket=None):\n    if basket is None:\n        basket = []\n    basket.append(item)\n    return basket"},{"t":"p","runs":[{"text":"Immutable defaults (numbers, strings, "},{"text":"True","code":true},{"text":", "},{"text":"None","code":true},{"text":", tuples) cannot be modified, so they are safe. "},{"text":"Never use a list, dict or set as a default value.","b":true}]},{"t":"p","runs":[{"text":"The same trap has a subtler form: "},{"text":"def log(msg, when=datetime.now())","code":true},{"text":" stamps every message with the time the module was imported."}]},{"t":"h2","id":"args-and-kwargs","runs":[{"text":"*args","code":true},{"text":" and "},{"text":"**kwargs","code":true}]},{"t":"p","runs":[{"text":"To accept any number of positional arguments, put a star in front of a name:"}]},{"t":"code","lang":"python","label":"Python","text":"def total(*amounts):\n    return sum(amounts)\n\ntotal(10, 20, 30)      # amounts is the tuple (10, 20, 30)"},{"t":"p","runs":[{"text":"Two stars collects any named arguments into a dictionary:"}]},{"t":"code","lang":"python","label":"Python","text":"def make_request(url, **options):\n    print(url, options)\n\nmake_request(\"/chat\", timeout=30, stream=True)\n# /chat {'timeout': 30, 'stream': True}"},{"t":"p","runs":[{"text":"The names "},{"text":"args","code":true},{"text":" and "},{"text":"kwargs","code":true},{"text":" are convention only; the stars do the work. You will meet them constantly in library code and in wrappers that pass arguments through to something else:"}]},{"t":"code","lang":"python","label":"Python","text":"def logged_call(func, *args, **kwargs):\n    print(f\"calling {func.__name__}\")\n    return func(*args, **kwargs)"},{"t":"p","runs":[{"text":"A star in a "},{"text":"call","b":true},{"text":" does the reverse: it unpacks. "},{"text":"func(*[1, 2])","code":true},{"text":" calls "},{"text":"func(1, 2)","code":true},{"text":", and "},{"text":"func(**{\"a\": 1})","code":true},{"text":" calls "},{"text":"func(a=1)","code":true},{"text":". Same symbol, opposite direction, decided by whether you are defining or calling."}]},{"t":"h2","id":"forcing-arguments-to-be-named","runs":[{"text":"Forcing arguments to be named"}]},{"t":"p","runs":[{"text":"Anything after a bare "},{"text":"*","code":true},{"text":" in the parameter list can only be passed by name:"}]},{"t":"code","lang":"python","label":"Python","text":"def resize(image, *, width, height):\n    ...\n\nimg = \"photo.jpg\"                    # sample image value\nresize(img, width=800, height=600)    # fine\nresize(img, 800, 600)                # TypeError"},{"t":"p","runs":[{"text":"This is how a library stops you from silently swapping two same-typed arguments, and it is worth doing in your own code for any function with more than about three parameters. It also lets you reorder or add parameters later without breaking callers."}]},{"t":"p","runs":[{"text":"The mirror image is "},{"text":"/","code":true},{"text":", which forces the parameters before it to be positional. You mostly meet it in the standard library’s documentation rather than writing it yourself."}]},{"t":"h2","id":"arguments-are-passed-by-object-reference","runs":[{"text":"Arguments are passed by object reference"}]},{"t":"p","runs":[{"text":"Python does not copy what you pass in and does not hand over a pointer to your variable. The function receives the "},{"text":"same object","i":true},{"text":" the caller had:"}]},{"t":"code","lang":"python","label":"Python","text":"def spoil(items):\n    items.append(\"surprise\")\n\nbasket = [\"rice\"]\nspoil(basket)\nprint(basket)        # ['rice', 'surprise']"},{"t":"p","runs":[{"text":"The function mutated the caller’s list. But rebinding does not escape:"}]},{"t":"code","lang":"python","label":"Python","text":"def replace(items):\n    items = [\"new\"]      # rebinds the local name only\n\nbasket = [\"rice\"]\nreplace(basket)\nprint(basket)        # ['rice']"},{"t":"p","runs":[{"text":"The one rule that covers both: "},{"text":"mutating the object is visible to the caller; assigning a new object to the parameter name is not.","b":true},{"text":" Half of all confusion about Python’s argument passing dissolves once that sentence is in place."}]},{"t":"p","runs":[{"text":"If a function must not modify what it is given, copy at the top of it, and say so in the docstring. If it is meant to modify in place, return "},{"text":"None","code":true},{"text":", following the convention that mutating operations do not hand back a value."}]}],"check":{"question":[{"text":"A caching helper is written as "},{"text":"def remember(key, store={}): store[key] = time.time(); return store","code":true},{"text":". It is called from two unrelated modules and each reports seeing the other’s keys. What is the mechanism?"}],"options":[{"text":[{"text":"Dictionaries are global in Python unless declared inside a function body with the "},{"text":"local","code":true},{"text":" keyword."}],"correct":false,"tempting":[{"text":"Invents a keyword and a scoping rule; ordinary assignment inside a function is already local."}]},{"text":[{"text":"The default dictionary was created once when the "},{"text":"def","code":true},{"text":" statement executed, so every call without an explicit "},{"text":"store","code":true},{"text":" shares that one object."}],"correct":true,"tempting":null},{"text":[{"text":"Both modules imported the same module, and Python re-runs a module’s "},{"text":"def","code":true},{"text":" statements on each import, merging the dictionaries."}],"correct":false,"tempting":[{"text":"Gets the import caching backwards (a module’s body runs once) while the shared state actually comes from the single default object."}]},{"text":[{"text":"store[key] = ...","code":true},{"text":" mutates the caller’s dictionary, so the fix is for each caller to pass a copy."}],"correct":false,"tempting":[{"text":"Describes real mutation semantics, but here no caller passed anything, so copying at the call site cannot be the fix."}]}],"order":[3,1,2,0],"why":null},"prev":{"slug":"functions","title":"Functions, and the difference between printing and returning","minutes":7},"next":{"slug":"scope-and-globals","title":"Where a name lives, and why the function cannot see it","minutes":8}}}