{"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":"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","position":23,"of":89,"minutes":8,"answer":"A name assigned anywhere in a function is local for the whole function, which is why reading a global before assigning it raises UnboundLocalError, while mutating a global object needs no declaration at all.","keyIdea":"A name assigned anywhere in a function is local for the whole function, which is why reading a global before assigning it raises UnboundLocalError, while mutating a global object needs no declaration at all."},"body":{"format":"markdown","text":"## Four places Python looks for a name\n\nWhen you use a name, Python searches in this order and stops at the first hit:\n\n1. **Local**: names assigned inside the current function.\n2. **Enclosing**: names in a function that contains this one.\n3. **Global**: names at the top level of the module.\n4. **Built-in**: `print`, `len`, `sum` and the rest.\n\nThat is the LEGB rule, and it explains both directions of confusion.\n\nReading a global from inside a function works without ceremony:\n\n```python\nTAX_RATE = 0.18\n\ndef with_tax(amount):\n    return amount * (1 + TAX_RATE)     # fine, found at step 3\n```\n\n> Figure: How Python decides that a name is local. Steps: 1. def is compiled (The whole body is scanned before any of it runs); 2. Assigned anywhere in the body? (One assignment counts, even on the last line); 3. Yes: local for all of it (Unless global or nonlocal says otherwise); 4. Read before that line (UnboundLocalError, not NameError); 5. No assignment at all (Looked up outward as it runs: local, enclosing, global, built-in). This is a compile-time decision made from the text of the function, which is why the assignment can be on the last line and still make the name local on the first. UnboundLocalError therefore means the opposite of what it sounds like: not that the name is missing, but that Python knows it is local and knows it has no value yet.\n\n## Assigning changes everything\n\n```python\ncount = 0\n\ndef bump():\n    count = count + 1     # UnboundLocalError\n\nbump()\n```\n\n```\nUnboundLocalError: cannot access local variable 'count' where it is not associated with a value\n```\n\nThe reason is precise and worth knowing. When Python compiles the function, it scans the whole body. Because `count` is assigned *somewhere* in it, `count` is marked local for the **entire** function, including the line that tries to read it before the assignment. The global `count` becomes invisible inside `bump`, so the read on the right-hand side has nothing to fetch.\n\nThe surprising part is that this happens even when the assignment comes later:\n\n```python\ndef report():\n    print(TAX_RATE)     # UnboundLocalError\n    TAX_RATE = 0.05\n\nreport()   # The error occurs when the function runs.\n```\n\nA single assignment anywhere in the body makes this name local throughout the function. Python decides that scope while compiling the function. The `UnboundLocalError` is raised later, when the function runs and tries to read the local name before it has a value.\n\n## `global`, and why to avoid needing it\n\n```python\ncount = 0\n\ndef bump():\n    global count\n    count += 1\n```\n\nThat works. It also means any function anywhere can now change `count`, and when the value is wrong you have to read the whole program to find out who changed it. Every additional `global` roughly doubles the search space when debugging.\n\nBetter shapes, in order of preference:\n\n```python\ndef bump(count):\n    return count + 1        # take it in, hand it back\n\ncount = bump(count)\n```\n\nor keep the state in an object, or in a dictionary passed explicitly. Module-level **constants** in capitals, read but never assigned, are fine and normal; `global` for mutable state is the thing to avoid.\n\n## Mutation slips through without `global`\n\n```python\ntotals = []\n\ndef record(x):\n    totals.append(x)      # works — no `global` needed\n```\n\nNo error, and the list does change. The rule from the previous lesson applies: `totals.append(x)` does not assign to the name `totals`, it calls a method on the object the name already refers to. Only **assignment** triggers the local-name rule.\n\nSo `totals = []` inside the function would need `global`, and `totals.append(x)` does not. That asymmetry catches people who learned the `global` rule as \"you cannot change globals from a function\".\n\n## `nonlocal`, for nested functions\n\n```python\ndef counter():\n    n = 0\n    def increment():\n        nonlocal n\n        n += 1\n        return n\n    return increment\n```\n\n`nonlocal` says \"the name in the enclosing function, not a new local and not a module global\". Without it, `n += 1` would be an `UnboundLocalError` inside `increment`. You meet this in closures and decorators, both of which appear later in the course.\n\n## Loops and `if` do not create a scope\n\nUnlike most languages with braces, Python only creates a new scope for a **function**, a class, or a module. A variable first assigned inside a `for` or an `if` is visible after it:\n\n```python\nrows = [\"a\", \"b\", \"c\"]  # also try an empty list\nfor row in rows:\n    last = row\nprint(last)  # An empty list skips the assignment to last.\n```\n\nIf the loop runs zero times, it never assigns to `last`. Reading `last` afterwards raises `NameError` if the name has no earlier binding. If `last` already has a value, the old value remains. Initialise it before the loop when later code depends on it.\n\n## Shadowing a built-in\n\n```python\nlist = [1, 2, 3]\nlist(\"abc\")        # TypeError: 'list' object is not callable\n```\n\nAssigning to `list`, `dict`, `sum`, `id`, `type` or `input` hides the built-in for the rest of the module. Nothing warns you at the moment you do it; the failure comes later, somewhere else, in code that had every right to expect `list` to be a type. Add a trailing underscore (`list_`) or pick a better name.\n\nFree linters catch this in one command: `ruff check` flags shadowed built-ins, unused names and the loop-variable problems above, and it runs in under a second on a whole project."},"check":{"question":"A function reads `config` on its first line and, twenty lines later, does `config = {}` in an error branch that has never yet run. Every call now fails on line 1 with UnboundLocalError. Why does an unreached line break the first line?","options":[{"text":"Python executes the function body once at import to check it, so the assignment already ran and left the name empty.","correct":false,"tempting":"Invents a pre-execution pass; the body of a function runs only when it is called."},{"text":"The error branch is unreachable, so Python treats the whole function as invalid and raises on entry.","correct":false,"tempting":"Treats a scoping error as a validity check on dead code, which Python does not perform."},{"text":"Scope is decided when the function is compiled: an assignment anywhere in the body makes the name local throughout, so the read at line 1 finds an unset local rather than the global.","correct":true},{"text":"`config` is a mutable object, and mutable globals must be declared with `global` before any use inside a function.","correct":false,"tempting":"Half-remembers the `global` rule, which concerns assignment rather than mutability and would not explain a failure on a read."}]},"prev":{"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"},"next":{"slug":"returning-values","title":"Returning: one value, several values, or nothing at all","url":"https://addaly.com/learn/python-for-ai/returning-values"},"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) 'Where a name lives, and why the function cannot see it', in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/scope-and-globals (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":"Where a name lives, and why the function cannot see it","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":"A name assigned anywhere in a function is local for the whole function, which is why reading a global before assigning it raises UnboundLocalError, while mutating a global object needs no declaration at all.","hero":{"kind":"figure","figure":{"t":"figure","label":"Figure","figure":{"caption":"This is a compile-time decision made from the text of the function, which is why the assignment can be on the last line and still make the name local on the first. UnboundLocalError therefore means the opposite of what it sounds like: not that the name is missing, but that Python knows it is local and knows it has no value yet.","steps":[{"label":"def is compiled","detail":"The whole body is scanned before any of it runs"},{"label":"Assigned anywhere in the body?","detail":"One assignment counts, even on the last line"},{"label":"Yes: local for all of it","detail":"Unless global or nonlocal says otherwise"},{"label":"Read before that line","detail":"UnboundLocalError, not NameError"},{"label":"No assignment at all","detail":"Looked up outward as it runs: local, enclosing, global, built-in"}],"title":"How Python decides that a name is local","type":"flow"},"alt":"Figure: How Python decides that a name is local. Steps: 1. def is compiled (The whole body is scanned before any of it runs); 2. Assigned anywhere in the body? (One assignment counts, even on the last line); 3. Yes: local for all of it (Unless global or nonlocal says otherwise); 4. Read before that line (UnboundLocalError, not NameError); 5. No assignment at all (Looked up outward as it runs: local, enclosing, global, built-in). This is a compile-time decision made from the text of the function, which is why the assignment can be on the last line and still make the name local on the first. UnboundLocalError therefore means the opposite of what it sounds like: not that the name is missing, but that Python knows it is local and knows it has no value yet."}},"blocks":[{"t":"h2","id":"four-places-python-looks-for-a-name","runs":[{"text":"Four places Python looks for a name"}]},{"t":"p","runs":[{"text":"When you use a name, Python searches in this order and stops at the first hit:"}]},{"t":"ol","start":1,"items":[[{"text":"Local","b":true},{"text":": names assigned inside the current function."}],[{"text":"Enclosing","b":true},{"text":": names in a function that contains this one."}],[{"text":"Global","b":true},{"text":": names at the top level of the module."}],[{"text":"Built-in","b":true},{"text":": "},{"text":"print","code":true},{"text":", "},{"text":"len","code":true},{"text":", "},{"text":"sum","code":true},{"text":" and the rest."}]]},{"t":"p","runs":[{"text":"That is the LEGB rule, and it explains both directions of confusion."}]},{"t":"p","runs":[{"text":"Reading a global from inside a function works without ceremony:"}]},{"t":"code","lang":"python","label":"Python","text":"TAX_RATE = 0.18\n\ndef with_tax(amount):\n    return amount * (1 + TAX_RATE)     # fine, found at step 3"},{"t":"h2","id":"assigning-changes-everything","runs":[{"text":"Assigning changes everything"}]},{"t":"code","lang":"python","label":"Python","text":"count = 0\n\ndef bump():\n    count = count + 1     # UnboundLocalError\n\nbump()"},{"t":"code","lang":"","label":"Text","text":"UnboundLocalError: cannot access local variable 'count' where it is not associated with a value"},{"t":"p","runs":[{"text":"The reason is precise and worth knowing. When Python compiles the function, it scans the whole body. Because "},{"text":"count","code":true},{"text":" is assigned "},{"text":"somewhere","i":true},{"text":" in it, "},{"text":"count","code":true},{"text":" is marked local for the "},{"text":"entire","b":true},{"text":" function, including the line that tries to read it before the assignment. The global "},{"text":"count","code":true},{"text":" becomes invisible inside "},{"text":"bump","code":true},{"text":", so the read on the right-hand side has nothing to fetch."}]},{"t":"p","runs":[{"text":"The surprising part is that this happens even when the assignment comes later:"}]},{"t":"code","lang":"python","label":"Python","text":"def report():\n    print(TAX_RATE)     # UnboundLocalError\n    TAX_RATE = 0.05\n\nreport()   # The error occurs when the function runs."},{"t":"p","runs":[{"text":"A single assignment anywhere in the body makes this name local throughout the function. Python decides that scope while compiling the function. The "},{"text":"UnboundLocalError","code":true},{"text":" is raised later, when the function runs and tries to read the local name before it has a value."}]},{"t":"h2","id":"global-and-why-to-avoid-needing-it","runs":[{"text":"global","code":true},{"text":", and why to avoid needing it"}]},{"t":"code","lang":"python","label":"Python","text":"count = 0\n\ndef bump():\n    global count\n    count += 1"},{"t":"p","runs":[{"text":"That works. It also means any function anywhere can now change "},{"text":"count","code":true},{"text":", and when the value is wrong you have to read the whole program to find out who changed it. Every additional "},{"text":"global","code":true},{"text":" roughly doubles the search space when debugging."}]},{"t":"p","runs":[{"text":"Better shapes, in order of preference:"}]},{"t":"code","lang":"python","label":"Python","text":"def bump(count):\n    return count + 1        # take it in, hand it back\n\ncount = bump(count)"},{"t":"p","runs":[{"text":"or keep the state in an object, or in a dictionary passed explicitly. Module-level "},{"text":"constants","b":true},{"text":" in capitals, read but never assigned, are fine and normal; "},{"text":"global","code":true},{"text":" for mutable state is the thing to avoid."}]},{"t":"h2","id":"mutation-slips-through-without-global","runs":[{"text":"Mutation slips through without "},{"text":"global","code":true}]},{"t":"code","lang":"python","label":"Python","text":"totals = []\n\ndef record(x):\n    totals.append(x)      # works — no `global` needed"},{"t":"p","runs":[{"text":"No error, and the list does change. The rule from the previous lesson applies: "},{"text":"totals.append(x)","code":true},{"text":" does not assign to the name "},{"text":"totals","code":true},{"text":", it calls a method on the object the name already refers to. Only "},{"text":"assignment","b":true},{"text":" triggers the local-name rule."}]},{"t":"p","runs":[{"text":"So "},{"text":"totals = []","code":true},{"text":" inside the function would need "},{"text":"global","code":true},{"text":", and "},{"text":"totals.append(x)","code":true},{"text":" does not. That asymmetry catches people who learned the "},{"text":"global","code":true},{"text":" rule as “you cannot change globals from a function”."}]},{"t":"h2","id":"nonlocal-for-nested-functions","runs":[{"text":"nonlocal","code":true},{"text":", for nested functions"}]},{"t":"code","lang":"python","label":"Python","text":"def counter():\n    n = 0\n    def increment():\n        nonlocal n\n        n += 1\n        return n\n    return increment"},{"t":"p","runs":[{"text":"nonlocal","code":true},{"text":" says “the name in the enclosing function, not a new local and not a module global”. Without it, "},{"text":"n += 1","code":true},{"text":" would be an "},{"text":"UnboundLocalError","code":true},{"text":" inside "},{"text":"increment","code":true},{"text":". You meet this in closures and decorators, both of which appear later in the course."}]},{"t":"h2","id":"loops-and-if-do-not-create-a-scope","runs":[{"text":"Loops and "},{"text":"if","code":true},{"text":" do not create a scope"}]},{"t":"p","runs":[{"text":"Unlike most languages with braces, Python only creates a new scope for a "},{"text":"function","b":true},{"text":", a class, or a module. A variable first assigned inside a "},{"text":"for","code":true},{"text":" or an "},{"text":"if","code":true},{"text":" is visible after it:"}]},{"t":"code","lang":"python","label":"Python","text":"rows = [\"a\", \"b\", \"c\"]  # also try an empty list\nfor row in rows:\n    last = row\nprint(last)  # An empty list skips the assignment to last."},{"t":"p","runs":[{"text":"If the loop runs zero times, it never assigns to "},{"text":"last","code":true},{"text":". Reading "},{"text":"last","code":true},{"text":" afterwards raises "},{"text":"NameError","code":true},{"text":" if the name has no earlier binding. If "},{"text":"last","code":true},{"text":" already has a value, the old value remains. Initialise it before the loop when later code depends on it."}]},{"t":"h2","id":"shadowing-a-built-in","runs":[{"text":"Shadowing a built-in"}]},{"t":"code","lang":"python","label":"Python","text":"list = [1, 2, 3]\nlist(\"abc\")        # TypeError: 'list' object is not callable"},{"t":"p","runs":[{"text":"Assigning to "},{"text":"list","code":true},{"text":", "},{"text":"dict","code":true},{"text":", "},{"text":"sum","code":true},{"text":", "},{"text":"id","code":true},{"text":", "},{"text":"type","code":true},{"text":" or "},{"text":"input","code":true},{"text":" hides the built-in for the rest of the module. Nothing warns you at the moment you do it; the failure comes later, somewhere else, in code that had every right to expect "},{"text":"list","code":true},{"text":" to be a type. Add a trailing underscore ("},{"text":"list_","code":true},{"text":") or pick a better name."}]},{"t":"p","runs":[{"text":"Free linters catch this in one command: "},{"text":"ruff check","code":true},{"text":" flags shadowed built-ins, unused names and the loop-variable problems above, and it runs in under a second on a whole project."}]}],"check":{"question":[{"text":"A function reads "},{"text":"config","code":true},{"text":" on its first line and, twenty lines later, does "},{"text":"config = {}","code":true},{"text":" in an error branch that has never yet run. Every call now fails on line 1 with UnboundLocalError. Why does an unreached line break the first line?"}],"options":[{"text":[{"text":"Python executes the function body once at import to check it, so the assignment already ran and left the name empty."}],"correct":false,"tempting":[{"text":"Invents a pre-execution pass; the body of a function runs only when it is called."}]},{"text":[{"text":"The error branch is unreachable, so Python treats the whole function as invalid and raises on entry."}],"correct":false,"tempting":[{"text":"Treats a scoping error as a validity check on dead code, which Python does not perform."}]},{"text":[{"text":"Scope is decided when the function is compiled: an assignment anywhere in the body makes the name local throughout, so the read at line 1 finds an unset local rather than the global."}],"correct":true,"tempting":null},{"text":[{"text":"config","code":true},{"text":" is a mutable object, and mutable globals must be declared with "},{"text":"global","code":true},{"text":" before any use inside a function."}],"correct":false,"tempting":[{"text":"Half-remembers the "},{"text":"global","code":true},{"text":" rule, which concerns assignment rather than mutability and would not explain a failure on a read."}]}],"order":[3,0,2,1],"why":null},"prev":{"slug":"arguments-in-depth","title":"Arguments: positional, named, default, and the trap in the default","minutes":9},"next":{"slug":"returning-values","title":"Returning: one value, several values, or nothing at all","minutes":7}}}