Glossary

Namespace

A namespace is a mapping from names (identifiers) to objects. Different namespaces allow the same name to exist in different contexts without conflict. Python implements namespaces using dictionaries: global variables live in a module's __dict__, instance attributes live in an object's __dict__, and local variables live in a frame's locals (optimised in CPython to an array, but conceptually a dictionary).

Python creates multiple namespaces during program execution: the built-in namespace (containing print, len, True, etc.), a global namespace for each module, and a local namespace for each function call. The LEGB rule determines the order in which these are searched. The dir() function lists names in the current scope, and vars(obj) returns an object's __dict__.

The Zen of Python states: "Namespaces are one honking great idea — let's do more of those!" This reflects Python's commitment to using namespaces to keep code organised and names unambiguous. Modules, classes, and functions all create namespaces. The import statement is fundamentally about connecting namespaces: it makes another module's namespace accessible from the current one.

Related terms: Module, Scope, LEGB Rule, Import

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.