Loading...
A name’s scope determines where it can be used. Its binding and the lifetime of the object it identifies are separate ideas, particularly when routines share mutable objects.
What you'll be able to do
A local variable belongs to a routine’s execution context and is not normally accessible by its local name from unrelated routines. Different calls can have separate local bindings even when the names are identical. This prevents temporary calculations in one task from accidentally replacing another task’s state.
A global name is available across a wider program scope. Globals can simplify access to genuine shared configuration, but widespread mutable global state creates hidden dependencies and makes isolated tests harder. Passing required values explicitly usually gives a clearer interface.
In Python, argument passing binds a parameter name to the supplied object. Assigning a new value to that parameter rebinds the local name; it does not automatically rebind the caller’s variable. Mutating a shared mutable object, such as appending to a list, can be visible through another reference.
Do not describe Python as simply copying every object or as providing a traditional reference parameter for every argument. Two names can refer to one list. An object may also survive a routine’s return when another reference still identifies it, even though the routine’s local execution context has ended.
An interface should distinguish routines that return a new value from routines that modify an existing object. A shallow copy creates a new outer collection but can still share nested objects. Avoid assuming that copying a list recursively duplicates everything it contains.
Trace names and objects separately when debugging aliasing: draw two arrows to a shared list, then follow which statement changes the list and which changes an arrow. Local scope limits name visibility; it does not guarantee that a routine has no externally visible effects.
def extend(values):
values.append(9)
values = [0]
items = [2, 4]
extend(items)
print(items)Scroll horizontally to see the full code or table.Attempt the task before opening its worked response. Record each change of state, explain the rule used, and check the result against the original requirements. Code examples labelled Python 3 use that language’s conventions; pseudocode states its own assumptions.
Common mistakes to avoid
Key takeaways
Test yourself
Answer a few questions, then review anything you missed.
Start with the quiz above to check the key ideas. You can also choose another topic from the practice library.