Python Modules and Packages Tutorial with examples



Hello dear readers! Welcome back to another edition of our tutorial on Python. In this tutorial guide, we are going to be studying about the Python Modules.

A module allows you to logically organize all of your Python code. Grouping related Python code into a module makes the code easier to understand and use. A module is a Python object that has an arbitrarily named attributes that you can bind and reference.

A module is a file that consists of Python code. A module can define functions, variables and classes. A Python module can as well include a usable code.

Example

The Python code for a module that is named aname normally resides in a file named aname.py. Below is a very simple example of a simple module, program.py.

def print_func( par ):
   print "Hello : ", par
   return


The import Statement

You can use a Python source file as a module by the process of executing an import statement in some other Python source file.

Syntax

The Python import statement has the following syntax -

import module1[, module2[,... moduleN]

Whenever the interpreter run into 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 Python interpreter searches for before it imports a module.

Example

For example, to import the module program.py, you will need to put the following commands at the top of the script -

#!/usr/bin/python

# Import module support
import support

# Now you can call defined function that module as follows
support.print_func("Paul")

Output

When the above code is executed, it will produce the following result -

Hello : Paul

A Python module is loaded only once, irrespective of the number of times it is imported. This prevents the module execution from taking place repeatedly if multiple import occur.

RECOMMENDED POST: Python Basic Syntax Tutorial

The from....import Statement

Python from statement lets you to import specific attributes from a module to the current namespace.

Syntax

The from...import has the following syntax -

from modname import name1[, name2[, ... nameN]]

Example

To import the function fibonaci from the module fib, then use the following statement -

from fib import fibonaci

The above Python statement does not import the entire module fib into the current namespace. What it does is to introduce the item fibonaci from the module fib into the global symbol table of code importing module.

The from...import * Statement

It is possible to import all names from the Python module into the current namespace by making use of the following import statement -

from modname import *

This gives an easy way to import all the items from the module into the current namespace. However, this statement should be sparingly used.


Locating Modules

Whenever you import a module, the interpreter searches for the module in the following order -

  • The current directory.
  • If the module is not found then Python looks for each directory in the shell variable Pythonpath.
  • If all fails, Python checks the default path. On UNIX, path is /usr/local/lib/python/.

The module's search path is stored in the system module sys as a sys.path variable. This variable contains the current directory, and installation-dependent default.

The PYTHONPATH Variable

The PYTHONPATH variable is an environment variable, that is made up of a list of directories.

Syntax

The syntax of PYTHONPATH is the same as that of the shell variable PATH.

Below is a typical PYTHONPATH from a Windows system -

set PYTHONPATH = c:\python20\lib;

Below is a typical PYTHONPATH from a UNIX system -

set PYTHONPATH = /usr/local/lib/python

RECOMMENDED POST: Python String Find() Method

Namespaces and Scoping

Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names and their corresponding objects.

A Python statement can access any variable in a local namespace and in the global namespace. If a local and a global variable have the same name, the local variable shadows the global variable.

Each functions has its own local namespace. The class methods follow the same scoping rule as the ordinary functions.

Python makes educated guesses on whether variables are local or global. It simply assumes that any variable that is assigned a value in a function is local.

Therefore, in order to assign a value to a global variable within a function, you must first make use of the global statement.

The statement global VarName tells Python that VarName is a global variable. Python then stops searching the local namespace for the variable.

Example

For example, we defined a variable Money in the global namespace. Within the function Money, we then assign Money a value, so Python assumes that Money is a local variable. However, we obtained the value of the local variable Money before then setting it, so an UnboundLocalError is the result. In order to fix this problem, you will uncomment the global statement.

#!/usr/bin/python

Money = 2000
def AddMoney():
   # Uncomment the following line to fix the code:
   # global Money
   Money = Money + 1

print Money
AddMoney()
print Money


The dir() Function

The dir() function returns a sorted list of strings which contains the names defined by a module.

The list contains the names of all modules, variables and functions that are defined in a module.

Example

Following is a simple example -

#!/usr/bin/python

# Import built-in module math
import math

content = dir(math)
print content

Output

When the above code is executed, it will produce the following result -

['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 
'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 
'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 
'sqrt', 'tan', 'tanh']

Here, the special string variable __name__ is the module's name and __file__ is the filename from which the module was loaded.

RECOMMENDED POST: Python String Index() Method

The globals() and locals() Functions
The Python globals() and locals() functions returns the names in the global and the local namespaces based on the location from where they are called.

If locals() is called from within a function, it returns all the names which can be accessed locally from that function.

If globals() is called from within a function, it returns all the names which can be accessed globally from that function.

The return type of both functions is a dictionary. So, the names can be extracted by using the keys() function.

The reload() Function
When the module is imported into the script, the code that is in the top-level portion of a module is excuted only once.

So, if you intend re-executing the top-level code in a Python module, you can use the reload() function. The reload() function imports a previously imported module again.

Syntax
Below is the syntax for the reload() function -

reload(module_name)

Here, module_name is the name of the module you want to reload and not the string containing the name of the module.

Example
Following below is an example to reload hello module -

reload(hello)



Python Packages
A Python package is a hierarchical file directory structure that defines a Python application environment that consists of modules and then subpackages & sub-subpackages, and so on.

Let us now consider a file Pots.py available in Phone directory. This file has following line of source code -

#!/usr/bin/python

def Pots():
   print "I'm Pots Phone"

In similar way, we have another two files having different functions with the same name as above -

  • Phone/Isdn.py that is having function Isdn().
  • Phone/G3.py having function G3().

Create one more file __init__.py in your Phone directory -

  • Phone/__init__.py

In order to make all your functions to be available when you have imported Phone, you will need to put explicit import statements in __init__.py.

from Pots import Pots
from Isdn import Isdn
from G3 import G3

After you have added these lines to __init__.py, you have all these classes available when you import the Phone package.

#!/usr/bin/python

# Now import your Phone Package.
import Phone

Phone.Pots()
Phone.Isdn()
Phone.G3()

Output
When the above code is executed, it will produce the following result -

I'm Pots Phone
I'm 3G Phone
I'm ISDN Phone

Here, we took example of a single functions in each file, but you can keep multiple functions in your files. You can also decide to define various classes in those files and then create your packages out of those classes.


Alright guys! This is where we are rounding up for this tutorial guide. In our next tutorial, we are going to be studying about the Python Files I/O.

Feel free to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.