-5

I'm new to python and I got a question in an assignment that reads:

"Name the four types of namespaces in Python"

I'm coming from a java/C background and as I understand it namespaces have to do with scope?

I think that two of the types of namespaces have are global and local?

Cristian Ciupitu
  • 20,270
  • 7
  • 50
  • 76

2 Answers2

1

From An Introduction to Python by Guido van Rossum and Fred L. Drake, Jr.:

A namespace is a mapping from names to objects. Examples of namespaces are: the set of built-in names (functions such as abs(), and built-in exception names); the global names in a module; and the local names in a function invocation. In a sense the set of attributes of an object also form a namespace. (my emphasis)

So there are four namespaces. In Python3 (but not Python2), list comprehensions also have their own namespaces. In both Python2 and Python3 generator expressions have their own namespace, as you can see from the NameError raised by the following code:

In [175]: (1 for i in range(1))
Out[175]: <generator object <genexpr> at 0x3a47d0f4>

In [176]: i
NameError: name 'i' is not defined

By the way, a scope related to, but not the same thing as a namespace. Whereas a namespace is a mapping between names and objects,

A scope is a textual region of a Python program where a namespace is directly accessible. "Directly accessible" here means that an unqualified reference to a name attempts to find the name in the namespace. (my emphasis)

Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
0

the innermost scope, which is searched first, contains the local names

the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contains non-local, but also non-global names

the next-to-last scope contains the current module’s global names

the outermost scope (searched last) is the namespace containing built-in names

Crypteya
  • 147
  • 11