Saturday 11 November 2017

Python:Module & Package

Modules and Packages in Python:
=========================
Introduction:
Python modules are .py files that consist of Python code. Any Python file can be referenced as a module.

Some modules are available through the Python Standard Library and are therefore installed with your Python installation. Others can be installed with Python’s package manager pip. Additionally, you can create your own Python modules since modules are comprised of Python .py files.

Module: A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.

·      A module allows you to logically organize your Python code.
·      Grouping related code into a module makes the code easier to understand and use.
·      A module is a Python object with arbitrarily named attributes that you can bind and reference.
·      Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code.

Example:
The Python code for a module named aname normally resides in a file namedaname.py. Here is an example of a simple module, support.py

#Filename is support.py
def print_func( par ):
   print "Hello : ", par
   return


The import Statement:
You can use any Python source file as a module by executing an import statement in some other Python source file. The import has the following syntax :

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

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.
For example, to import the module hello.py, you need to put the following command at the top of the script:

#!/usr/bin/python3
# Import module support
import support

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

Output:
Hello : Zara

Note: 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.

The from...import Statement
Python's from statement lets you import specific attributes from a module into the current namespace. The from...import has the following syntax:

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

For example, to import the function fibonacci from the module fib, use the following statement :
#!/usr/bin/python3

# Fibonacci numbers 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
>>> from fib import fib
>>> fib(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

This statement does not import the entire module fib into the current namespace; it just introduces the item fibonacci from the module fib into the global symbol table of the importing module.

The from...import * Statement
It is also possible to import all the names from a module into the current namespace by using the following import statement:

from modname import *

This provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly.


'import module' Vs 'from module import'
===============================
The difference between import module and from module import foo is mainly subjective.

Pick the one you like best and be consistent in your use of it. Here are some points to help you decide.

import module
  • Pros:
    • Less maintenance of your import statements. Don't need to add any additional imports to start using another item from the module
  • Cons:
    • Typing module.foo in your code can be tedious and redundant (tedium can be minimized by using import module as mo then typing mo.foo)

from module import foo
  • Pros:
    • Less typing to use foo
    • More control over which items of a module can be accessed
  • Cons:
    • To use a new item from the module you have to update your import statement
    • You lose context about foo. For example, it's less clear what ceil() does compared to math.ceil()

Either method is acceptable, but don't use from module import *.
For any reasonable large set of code, if you import * you will likely be cementing it into the module, unable to be removed. This is because it is difficult to determine what items used in the code are coming from 'module', making it easy to get to the point where you think you don't use the import any more but it's extremely difficult to be sure.

Packages in Python:

A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages, and so on.
Consider a file Pots.py available in Phone directory. This file has the following line of source code:

#!/usr/bin/python3

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

Similar, we have other two files having different functions with the same name as above. They are −
  • Phone/Isdn.py file having function Isdn()
  • Phone/G3.py file having function G3()
Now, create one more file __init__.py in the Phone directory −
  • Phone/__init__.py
To make all of your functions available when you have imported Phone, you need to put explicit import statements in __init__.py as follows :

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

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

#!/usr/bin/python3

# Now import your Phone Package.
import Phone

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

When the above code is executed, it produces the following result:

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


In the above example, we have taken example of a single function in each file, but you can keep multiple functions in your files. You can also define different Python classes in those files and then you can create your packages out of those classes.


For Detailed Explanation on Modules refer to Python3 Documentation:
Python3:Modules



Good Videos for a Quick Understanding of Concepts:

Import Modules and Exploring The Standard Library:




Packages:


Modules & Packages.







1 comment:

  1. Nice article I was impressed by seeing this blog, it was very interesting and it is s for sharing all the information with us all.very useful for me. This is good information and really helpful for the people who need information about this.

    oracle training in chennai

    oracle training institute in chennai

    oracle training in bangalore

    oracle training in hyderabad

    oracle training

    oracle online training

    hadoop training in chennai

    hadoop training in bangalore


    ReplyDelete

Note: only a member of this blog may post a comment.