Python Programming – Modules and Packages

In this Page, We are Providing Python Programming – Modules and Packages. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Modules and Packages

As the program gets longer, it is a good option to split it into several files for easier maintenance. There might also be a situation when the programmer wants to use a handy function that is used in several programs without copying its definition into each program. To support such scenarios, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter.

Module

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Definitions from a module can be imported into other modules. For instance, consider a script file called “fibo.py” in the current directory with the following code.

# Fibonacci numbers module

def fib ( n ) :                                        # write Fibonacci series up to n
         a , b=0 , 1 
         while b<n :
            print b , 
            a, b=b , a+b

def fib2 ( 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

Now on the Python interpreter, import this module with the following command:

>>> import fibo

Within a module, the module’s name (as a string) is available as the value of the global variable
___name___:

>>> fibo.___name___ 
' fibo '

Use the module’s name to access its functions:

>>> fibo . fib ( 1000 )
1 1 2 3 5 8  13  21  34  55  89  144  233  377  610  987 
>>> fibo . fib2 ( 1000 )
[ 1 ,  1 ,  2 ,  3 ,  5 ,  8 ,  13 ,  21 ,  34 ,  55 ,  89 ,  144 ,  233 ,  377 ,  610 ,  987 ]

If it is intended to use a function often, assign it to a local name:

>>> Fibonacci=fibo . fib 
>>> Fibonacci ( 500 )
1  1  2  3  5  8  13  21  34  55  89  144  233  377