Local imports
In Chapter 3, Using Modules and Packages, we introduced the concept of a
global namespace, and showed how the import
statement adds the name of the imported module or package into the global namespace. This description was actually a slight oversimplification. In fact, the import
statement adds the imported module or package to the current namespace, which may or may not be the global namespace.
In Python, there are two namespaces: the global namespace and the local namespace. The global namespace is where all the top-level definitions in your source file are stored. For example, consider the following Python module:
import random import string def set_length(length): global _length _length = length def make_name(): global _length letters = [] for i in range(length): letters.append(random.choice(string.letters)) return "".join(letters)
When you import this Python module, you will have added four entries to the global namespace: random
, string...