Packages and Modules in Python

A Module in Python is a file with the .py extension. This file can be added to another Python file with a simple import statement. The important statement would use the filename without the .py extension.
Here is a simple example.
We create a file called Functions.py

def add(x=0,y=0):
    return x+y


It is being accessed from another file UseFunctions.py

import Functions
print(Functions.add(2,3))

Next we develop a module with a class.
classfunctions.py

 

def add(x=0,y=0):
    return x+y
class Complex:
    def __init__(self, rp=0, ip=0):
        self.rp=rp
        self.ip=ip
    def __str__(self):
        if(self.ip<0):
            return str(self.rp) + " - i * " + str(-self.ip)
        else:
            return str(self.rp) + " + i * " + str(self.ip)

UseClasses.py

import classfunctions as cy
print(add(2,3))
c1=Complex(2,3)
c2=Complex(3)
c3=Complex(3,-9)
print(c1)
print(c2)
print(c3)

5
2 + i * 3
3 + i * 0
3 – i * 9

 

Modules defined in other directories become packages are imported through packagename.module syntax.
For example

import champak.champ as cp
print(cp.sub(3,4))


will import module champ in package champak

def sub(x=0,y=0):
    return x-y

If we don’t want all modules in a package to be available for import, then we we create a file called.
__init__.py

 

__init__.py:
__all__ = [“champ”]

This works for an import * statement.

Leave a Reply