Reading names from outside

Lesson 14 of 54 · Python Foundations

A name assigned at the top level of a Python file belongs to that module’s global scope. A function defined in the module can read such a name when it runs, provided no nearer binding takes precedence.

unit = "km"

def distance_label(distance):
    return f"{distance} {unit}"

print(distance_label(12))
12 km

distance is local to the call; unit is looked up in the function’s module globals. A global is not automatically shared across every file: each module has its own global namespace. If a name is not found in relevant scopes, Python raises NameError; built-in names such as print are also available.

A function reads the global value when it runs, not necessarily the value present at definition. An explicit parameter makes a dependency easier to see and change:

def distance_label(distance, unit):
    return f"{distance} {unit}"

print(distance_label(12, "mi"))
12 mi

This labels different units without changing a global name. It does not convert units.

Chapter index