HomePython Page 6 - Python 101 (part 7): Dinner With A Hungry Giant
From Python, With Love - Python
Python allows developers to logically group functions togetherinto modules, which can be imported and used by any Python program. In thisarticle, find out what a module is, learn how modules and module namespaceswork, and check out the default modules that ship with Python
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.
>>> from menu import lunch
This module is owned by The Hungry Giant. Cook smart. Eat healthy. Die
anyway.
>>> lunch["Tue"]
'Fish and Chips'
>>>
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:
#!/usr/bin/python
def getDinnerItem(day):
print "Sorry, diner closed on " + day
getDinnerItem("Mon")
When you run this, the output reads
Sorry, diner closed on Mon
Now, look what happens when you import some names from the "menu.py" module into this program:
#!/usr/bin/python
def getDinnerItem(day):
print "Sorry, diner closed on " + day
# imports
from menu import dinner
from menu import getDinnerItem
getDinnerItem("Mon")
When you run this program. the imported names will overwrite the names already existing in the namespace, resulting in the following output:
This module is owned by The Hungry Giant. Cook smart. Eat healthy. Die
anyway.
Dinner on Mon is: Pasta
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:
# numbers.py
x = 1
y = 2
z = x + y
Look what happens when I import these values into a script:
#!/usr/bin/python
# import
from numbers import x,y,z
# at this stage, z = x + y => z = 3
print z
# alter the value of imported x
x = 10
# z is still referring to the value of x in the module, so z still = 3
print z
# the only way to get z to recognize the new value of x is to redefine z in
context
z = x + y