11

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?

14

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 nested inside.

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.

  • 3
    "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." – Nikos Feb 20 '15 at 14:01
  • 2
    This answer is right in spirit, but wrong in detail. Classes in Python do not introduce a new namespace, which is why class attributes must be qualified with the class name and why instance attributes must be qualified with the instance name. The levels of namespace in Python from inner to outer are Local, Enclosing, Global and Built-in. A class may be defined at any of these levels, but the members of a class must always be qualified. – Rob Smallshire Oct 5 '17 at 13:14
  • You're right. Classes don't work the way I said they do. I was thinking they create a lexical scope like a function, but they don't. Please update the answer if you have time, else I'll do it at some point. Thanks. – Carl Smith Oct 5 '17 at 19:48
  • 1
    +1 Brilliant answer, encapsulating such subtlety so economically. I found this very helpful, thank you! – seeker Dec 24 '17 at 3:05
  • 1
    "A namespace is a hash of name, value pairs, a lot like a Python dictionary" - I'm pretty sure namespaces are stored as python dictionaries. For instance, you can edit the global namespace by calling globals(), which lets you modify the dictionary directly to bind objects and names: for instance globals()[name]="object". Great answer otherwise. – Evan Rosica May 19 '18 at 6:13
3

There is an excellent article on Python namespaces here. To quote the relevant part to answer your question about the reference between scopes and namespaces:

A scope refers to a region of a program from where a namespace can be accessed without a prefix.

For example, imagine a simple die-rolling program:

import random  # 'random' is in module namespace

def roll(sides=6):  # 'roll' is in module namespace, 'sides' is in roll's
    return random.randint(1, sides)  # both 'random' and 'sides' are in scope here

# but sides can't be accessed out here 

roll has its own namespace, but the names in the module's namespace are also in scope.

  • @CarlSmith note that early Python documentation says the same thing: "A scope is a textual region of a Python program where a name space is directly accessible. "Directly accessible'' here means that an unqualified reference to a name attempts to find the name in the name space." – jonrsharpe Feb 17 '15 at 17:01
  • @CarlSmith aside from the additional of non-local/enclosing scope, has that much changed? I think we are saying the same thing - a namespace contains the names and values, and the scope tells you which namespaces are accessible. – jonrsharpe Feb 17 '15 at 17:22
  • I deleted my old comments. – Carl Smith Oct 18 '18 at 2:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.