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, likeprint(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, likerange
andgetattr
), which is the end of the line.Imagine you have a function named
inner
, nested within a global function namedouter
, andinner
contains a reference to a name. Python first looks in theinner
namespace. If the name's not there, Python then looks in theouter
namespace. If that fails, Python tries the module'sglobal
namespace, then thebuiltin
namespace, eventually throwing aNameError
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 sayx
is in the function's scope, we meanx
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.