Lesson 7: Modules
A module is a Python object with arbitrarily named attributes that you can bind
and reference. It allows for logical organization of Python code which makes
the code easier to use and understand. In a nutshell, a module is a Python file
with definitions of functions, classes and variables. A module can also include
runnable code.
import Statement
A Python source file can be used (imported) as a module by executing an
import statement in some other Python source file. The import has the
following syntax-
import module1[, module2[,... moduleN]
Example
import calendar
print (calendar.calendar(2022))
When the interpreter encounters an import statement, it imports the module if
the module is present in the search path. A search path is a list of directories
that the interpreter searches before importing a module.
Example:
Consider a python source file named hello.py containing the following code;
def sayhi(arg ):
print ('Hello ', arg)
return
The file can be imported into another source file as follows;
import hello
# A call to defined function as follows
hello.sayhi("Peter")
A module is loaded only once, regardless of the number of times it is imported.
This prevents the module execution from happening repeatedly, if multiple
imports occur.
from...import Statement
The from statement is used to import specific attributes from a module into the
current namespace.
Example:
A. Irungu
Consider our hello.py source file with the following code:
def sayhi( arg ):
print ('Hello ',arg)
return
def loop(num):
while num>0:
print (num)
num-=1
A specific module in hello.py can be imported into another source file as
follows;
from hello import loop
# A call to defined function as follows
loop (10)
This statement does not import the entire hello module into the current
namespace; it just introduces the function loop from the module hello into the
global symbol table of the importing module.
The statement from hello import * is used to import all the names from the
hello module into the current namespace. This statement should be used
sparingly.
Executing Modules as Scripts
Within a module, the module’s name (as a string) is available as the value of
the global variable __name__. The code in the module will be executed, just as
if you imported it, but with the __name__. set to "__main__. ".
Add this code at the end of your module-
def fib(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
if __name__== "__main__":
f=fib(100)
print(f)
A. Irungu
When you run the above code, the following output will be displayed.
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Locating Modules
When you import a module, the Python interpreter searches for the module in
the following sequences-
The current directory.
If the module is not found, Python then searches each directory in the
shell variable PYTHONPATH.
If all else fails, Python checks the default path. On UNIX, this default
path is normally /usr/local/lib/python3/.
The module search path is stored in the system module sys as the sys.path
variable. This variable contains the current directory, PYTHONPATH, and the
installation-dependent /default path.
Example:
What is the current search path?
import sys
for p in sys.path: print(p)
How to add a directory to the current search path
sys.path.append('X:/path/') # where X is a drive letter
The dir( ) Function
The built-in function dir() returns a sorted list of strings containing the names
defined by a module. The list contains the names of all the modules, variables
and functions that are defined in a module.
Example
import hello
dir(hello)
Here, the special string variable __name__ is the module's name, and __file__
is the filename from which the module was loaded.
The globals() and locals() Functions
A. Irungu
The globals() and locals() functions can be used to return the names in the
global and local namespaces depending on the location from where they are
called.
If locals() is called from within a function, it will return all the names
that can be accessed locally from that function.
If globals() is called from within a function, it will return all the names
that can be accessed globally from that function.
The return type of both these functions is dictionary. Therefore, names can be
extracted using the keys() function.
The reload() Function
When a module is imported into a script, the code in the top-level portion of a
module is executed only once.
Therefore, if you want to re-execute the top-level code in a module, you can
use the reload() function. The reload() function imports a previously imported
module again. The syntax of the reload() function is this-
reload(module_name)
The module_name is the name of the module you want to reload and not the
string containing the module name. For example, to reload hello module, do
the following-
reload(hello)
Packages in Python
A package is a hierarchical file directory structure that defines a single Python
application environment that consists of modules and sub-packages and sub-
sub-packages, etc.
Example: How to create a Package
Consider a file factorial.py available in mypack directory, in which a function
called factorial() is defined. A file hello.py file in which a function hello()
defined. And a file loop.py file in which a function loop() defined
Then add one more file __init .py in to the mypack directory.
To make all the functions available when mypack is imported, add explicit
import statements in init .py as follows-
from factorial import factorial
from hello import hello
A. Irungu
from loop import loop
When mypack package is imported to a program.
import mypack as m
m.factorial(6);
m.hello()
m.loop()
In the above example, a single function in defined in each file. However,
multiple functions (or even python classes) can be defined in each file.
Assignment:
Read about the following Modules, packages, and Libraries
matplotlib
seaborn
pandas
scipy
statistics
Read about Python Development Frameworks.
And then finally, Discuss the following ecosystem among your study groups;
Modules
Packages
Libraries
Frameworks
A. Irungu