Thus far, you've been importing modules as is, and using module attributes by referencing them with the module name as prefix. Python also offers an alternative method to selectively access and use module attributes - the "from" statement. The "from" statement allows you to import specific attributes from a module into the current namespace. Since these attributes become part of the current namespace, it no longer becomes necessary to prefix them with the module name in order to use them. Consider the following example, which demonstrates how this works.
In this case, the module variable "menu.lunch" is imported into the current namespace as the variable "lunch". It's important to exercise caution when using the "from" statement - since "from" imports module attributes directly into the current namespace, you run the risk of overwriting current names when you use it. To illustrate this, consider the following simple Python program:
When you run this, the output reads
Now, look what happens when you import some names from the "menu.py" module into this program:
When you run this program. the imported names will overwrite the names already existing in the namespace, resulting in the following output:
Another important gotcha with "from": importing names using "from" implies that changes to those names (after they have been imported) are not reflected in the parent module. Consider the following module:
Look what happens when I import these values into a script:
blog comments powered by Disqus |