Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Scopes and Namespaces in python? [closed]

Tags:

python

I am new in python, please describe difference between Scopes and Namespaces with example.

thanks in advance

like image 970
python-lovers Avatar asked May 05 '15 05:05

python-lovers


1 Answers

Scopes

You can think of "scope" as being the set of names that you have access to from a particular point in the code.

x = 1
y = 2
def foo():
  z = 3 + y

# Here, I have access to `x, y, foo` -- They are in the current scope
# `z` is not in the current scope.  It is in the scope of `foo`.
a = x + y
b = x + z  # NameError because `z` is not in my scope.

Note that within the function foo, I have access to the "enclosing" scope. I can read from any name that is defined inside the function, but also any name that is defined in the environment where my function was created.

In the example, inside the function of foo, the scope contains x, y, foo, z, and a (it would contain b if b were to get defined and not throw the NameError).

 ______________________________
 |                            |
 |   Names in enclosing scope |
 |      {x, y, foo, ...}      |
 |                            |
 |   --------------------     |
 |   | function scope   |     |
 |   |       {z}        |     |
 |   | (Also has access |     |
 |   | enclosing scope) |     |
 |   --------------------     |
 |                            |
 ------------------------------

Namespaces

A namespace is a related concept. It is generally thought of as an object that holds a set of names. You can then access the names (and the data they reference) by looking at the members of the object.

foo.x = 1
foo.y = 2
foo.z = 3

Here, foo is a namespace. I suppose you can think of a namespace as a container of names. The most natural unit of namespace in python is a module though a class, instance of a class, function can be a namespace since you can attach arbitrary names/data to them under most circumstances.

Note that in python, these concepts become a little jumbled as you can import a module's scope as a namespace

# foo.py
x = 1
y = 1

# bar.py
import foo
print foo.x
print foo.y

Note that the "global" scope of foo gets imported into the global scope of bar as the namespace foo in this example.

We can also import the global scope of foo into the global scope of bar without a namespace if we want (though this practice is generally discouraged):

# bar.py
from foo import *
print x
print y
like image 121
mgilson Avatar answered Sep 27 '22 18:09

mgilson