Sorting out module namespaces

Each module (a file with Python code, ending in .py) has its own namespace. All the functions defined in the module use the module's namespace as their global namespace. The functions won't look elsewhere (except for the built-in namespace) for names that are referenced within them. This means that the author of a module can use global names in a module without worrying about their conflicting with global names used elsewhere. In other words, whenever you see "global" used in Python, think "module global."

Tip For more about modules, see Chapter 12.

When a module imports another module, the imported module's name becomes part of the importing module's namespace. You can then access its functions and other information by using the module name, a dot, and the function name, the same way you can when you import a module into interactive mode.

Imagine you have a module called that does nothing but import another module:

# module 'mymod' import math

If you import this module into interactive mode, you can print the math.pi constant by typing this code:

>>> import mymod >>> mymod.math.pi 3.14159265359

But the name math and its constant pi are known only inside the module. The surrounding namespace of interactive mode still doesn't know about the math module:

Traceback (most recent call last):

File "<stdin>", line 1, in <module> NameError: name 'math' is not defined

TECHNICAL It's possible to manipulate a module's global names by using the STUFF same notation used to refer to its functions, modulename.itemname.

You should do this only if you know what you're doing. (It's an advanced feature we don't cover in this book.)

Was this article helpful?

0 0

Post a comment