Monday, July 20, 2020

Python Modules and Packages Tutorial with examples



Hello guys! Welcome back to another section of my tutorial on Python. In this tutorial guide, we are going to be studying about Python Modules.

A module allows you to logically organize 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 arbitrarily named attributes that you can bind and reference.

Simply, a module is a file consisting 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 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

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 will prevent the module execution from happening over and over again if multiple import occur.

RECOMMENDED POST: Python Basic Syntax Tutorial 

The from....import Statement

Python's from statement allows you to import specific attributes from a module to the contemporary Python 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 also 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 provides an easy way to import all the items from the module into the contemporary 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, Python searches for each directory in the shell variable Pythonpath.
  • If all else fails, Python checks the default path. On UNIX, this default is /usr/local/lib/python/.

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

The PYTHONPATH Variable

The PYTHONPATH is an environment variable, which consists of a list of directories.

Syntax

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

Here is a typical PYTHONPATH from a Windows system -

set PYTHONPATH = c:\python20\lib;

And here 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 (keys) 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 same name, the local variable shadows the global variable.

Each of the 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 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 assign Money a value, so Python assumes Money as a local variable. However, we obtained the value of the local variable Money before we set 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

RECOMMENDED POST: Python String islower() Method 

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 the 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']

From the above example, the special string variable __name__ is the code 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 globals() and locals() functions is used for returning the names in the global and local namespaces based on the location from where they are called.

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

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

The return type of both functions is a dictionary. So, the names can be extracted 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 then excuted only once.

Therefore, if you want to re-execute the top-level code in a module, you can use of 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 module name.

Example
Below is an example to reload hello module -

reload(hello)



Python Packages
A Python package is a hierarchical file directory structure that defines a sole Python application environment that consists of modules and then subpackages and 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 having function Isdn().
  • Phone/G3.py having function G3().

Now, create one more file __init__.py 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

In above example, we took example of a single functions in each file, but you can keep multiple functions in your files. You can as well 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 my next tutorial, we are going to be studying about 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.
Share:

0 comments:

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.