Python 101 (part 7): Dinner With A Hungry Giant - Between A Rock And...Another Rock
(Page 3 of 9 )
The elements within a module - variables, functions, other imports - are referred to as "module attributes".
The "import" keyword is used to search for the named module and load it if found. Once the module has been successfully imported, functions and variables contained within it can be accessed by prefixing their names with the module name. Since each module sets up an independent namespace, this is a handy way to avoid name clashes.
To see how this works, consider the following example, which uses two modules, each containing a function named rock():
def rock(): # module huey.py
print "Between a rock and a hard place"
def rock(): # module dewey.py
print "Rock on!"
Let's see what happens when I try to use these in a program:
>>> import huey
>>> import dewey
>>> huey.rock()
Between a rock and a hard place
>>> dewey.rock()
Rock on!
>>>
Since each module attribute has a unique prefix, it's possible to distinguish between attributes with the same name in different modules, and thereby avoid name conflicts.
You'll be interested to know that everything you do in Python takes place within the context of a module. Even commands typed into the interactive command-line interpreter take place within the bubble of Python's top-level module, named "__main__".
Next: Love Bytes >>
More Python Articles
More By Vikram Vaswani, (c) Melonfire