CHAPTER 19: Modules
In real life, we want all our files to be organized for easy storing and retrieval. Naturally, this instinct would extend to our programming needs. This is primarily why Python implemented modules.
A module allows the programmer to organize and logically arrange the code he has typed in. By grouping all related code into a module, one can better read, understand, debug, and use them. Modules in the Python language are objects that have arbitrarily named attributes, which can all be bound and referenced.
Put another way, modules are files that consist of Python code. They can define classes, functions, and variables. They can also include codes which can be executed. Below is an example of a module. The code for the module with the name “spam” would normally be in a file named “spam.py”. The example is that of a simple module:
Def print_func( par ):
Print “Hi:”, par
Any Python source file can be used as a module through the execution of an import statement in another source file. An import statement has the syntax:
When the Python interpreter encounters import statements, it will import the module in case the module is found in the search path. The search path is a directory list, searched by the interpreter before the module is imported. Let’s say, for example, that you would need to import the modulespam.py, the following command would have to be placed atop the script:
Once executed, the following result is shown:
Hi : Python
Modules have to be loaded only once, despite the number of times that it is imported. This will prevent the execution of the module from occurring repeatedly, in case multiple imports are called.
The Python language’s from statement allows a user to import certain attributes from modules and into the present namespace. The statement has the syntax:
From modname import name1[,name2[,...nameN]]
Let’s say that we need to import the eggs function from the bacon module, then the following statement should be written:
From bacon import eggs
This statement will not import the whole module bacon to your current namespace -- instead, it adds the item eggs to the importing module’s global symbol table.
Fromm...import * Statement
It will also be possible to import all of the names from the module to your current namespace through this import statement:
From modname import *
This will provide an easier way of importing all the items from the specified module into your current namespace. However, make sure not to overuse this statement.
In the process of importing modules, the interpreter searches for it in the following order:
Your current directory
When the module cannot be found, Python tries to look for it within a shell variable—PYTHONPATH
When this still fails, the language tries to check the default path. In UNIX systems, this is almost universally /usr/local/lib/python/.
The module’s search path is located in the sys system module as the variable sys.path. It contains the present directory, PYTHONPATH, as well as the default (which depends on the installation).
This is an environment variable, which consists of a list of directories. The PYTHONPATH’s syntax is similar to PATH, a shell variable. Here is an example of a Windows PYTHONPATH:
As well, here is an example of the usual PYTHONPATH from UNIX and UNIX-like systems:
Scoping and Namespaces
The variables are identifiers (names) that are mapped to objects. Namespaces are dictionaries of names that are variables (keys) as well as their values (corresponding variables).
Python statements are able to access variables in local namepsaces as well as in global namespaces. If local and global variables are equipped with the same name, the local one will shadow the global variable.
Every function is given its very own local namespace. The class methods also follow the same rule for scoping just as any ordinary function.
The Python language can make educated guesses depending on whether specific variables are global or local. This is done by assuming that variables assigned values in functions are local. Therefore, if you need to assign values to global variables within functions, the global statement will have to be used. Using the statement global VarName should tell Python that VarName is to be considered as a global variable. Then Python stops searching for the variable in local namespaces.
As an example, the variable spam is defined within the global namespace. Within the spam function, spam is assigned a value, therefore having Python assume that it is a local variable. However, the programmer accessed the local variable spam’s value before setting it, so a result will appear instead: UnboundLocalError. To fix this, the programmer will have to uncomment the global statement:
#To fix the code, uncomment the following line:
Spam = Spam+1
The dir() function is a built-in one that will return a list of sorted strings, which in turn contain the names defined by a specific module.
The list will contain the names of all the modules, functions, and variables that are defined therein. Here is a simple example we can follow:
#Use the built-in module math for import
When the code above is executed, it produces a long list as a result. The special string __name__ in the results is the name of the odule, while the __file__ on the result is the filename from which this module has been loaded.
Locals() and Globals() Functions
These functions can be used by the programmer to return names in local and global namespaces. This depends on the location from which they had been called.
If locals() has been called from within a function, it will then return all names that can be locally accessed from this function. On the other hand, if globals() is called from this same function, then it will return the names that can be globally accessed from that function.
When a module is imported in a script, the top-level portion code of the module will be executed just once. Therefore, if the programmer wishes to repeat the execution of the top-level code, the reload() function may be used. What the function does is to import again a module that has already been previously imported. The reload() function’s syntax is as follows:
In this syntax, the module_name part is the name of the one that you wish to reload—not the string which contains the module name. For example, in order to reload a module named spam, then simply type reload(spam).
A Python package is a file directory (hierarchial) which defines one Python application environment consisting of modules, their subpackages, sub-subpackages, and so forth.
For example, consider a file entitles Bacon.py found in the directory Eggs. This line of code appears in the file:
Print “Bacon and Eggs”
In a similar manner, there are two other files which have different functions but with the same name as that given:
● Eggs/Spam.py, which has the function Spam()
● Eggs/Juoce.py, which has the function Juice()
Then, let us put a new file named __init__.py inside the Eggs directory -- Eggs/__init__.py
In order to make all of the functions available once Eggs is imported, then one needs to put the explicit import statements within __init__.py as shown here:
From Bacon import Bacon
From Spam import Spam
From Juice import Juice
After these lines are added to __init__.py, the programmer will have all these classes available when the Eggs package is imported:
#Now, the Eggs package is imported
Once the code is executed, then the following is produced as a result:
Bacon and Eggs
Spam and Eggs
Juice and Eggs
In this example, we have taken just a single function in each of the files. However, you can always keep multiple functions in the files. Different Python classes can also be defines in these files, then packages can be created out of these classes.