Python – Relationship Between Scope and Namespaces

python

In many resources I found "scope" and "namespaces" are used interchangeably, which seems a bit confusing since they mean different things.

  • Scope defines the region of the code where a name is available.
  • The LEGB rule defines the way names are looked up.
  • Namespace is a place where you look up names.

Then I read:

  • "names are bind to a namespace according to where they are assigned…" (which I believe is the deal with scopes in lexical scoping).
  • "functions add an extra namespace layer to your programs" [ref.] (don't they add a extra local scope?)
  • "all the names assigned inside a function definition are put in the local scope (the
    namespace associated with the function call)."
  • "global scope—that is, a namespace in which variables created (assigned) at the top level of the module file live."

*all of the quotes are from learning python 5th edition ch17

Are namespaces in Python the way scopes are implemented? Are they the same thing? Can anyone enlighten me?

Best Answer

A namespace is a dictionary, mapping names (as strings) to values. When you do an assignment, like a = 1, you're mutating a namespace. When you make a reference, like print(a), Python looks through a list of namespaces to try and find one with the name as a key.

A scope defines which namespaces will be looked in and in what order. The scope of any reference always starts in the local namespace, and moves outwards until it reaches the module's global namespace, before moving on to the builtins (the namespace that references Python's predefined functions and constants, like range and getattr), which is the end of the line.

Imagine you have a function named inner, nested within a global function named outer, and inner contains a reference to a name. Python first looks in the inner namespace. If the name's not there, Python then looks in the outer namespace. If that fails, Python tries the module's global namespace, then the builtin namespace, eventually throwing a NameError if the name isn't found.

When we say x is in a function's namespace, we mean it is defined there, locally within the function. When we say x is in the function's scope, we mean x is either in the function's namespace or in any of the outer namespaces that the function's namespace is currently nested within.

Whenever you define a function, you create a new namespace and a new scope. The namespace is the new, local hash of names. The scope is the implied chain of namespaces that starts at the new namespace, then works its way through any outer namespaces (outer scopes), up to the global namespace (the global scope), and on to the builtins.

The terms can be used almost interchangeably, but that's not because they mean the same thing; it's because they overlap a lot in what they imply.

Related Topic