Skip to main content

Modules in Python




What are Modules in Python? 

Modules are simply a ‘program logic’ or a ‘python script’ that can be used for variety of applications or functions. We can declare functions, classes etc in a module.

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.




How To Create Modules In Python?

Creating a module in python is similar to writing a simple python script using the .py extension. For the above example lets try to make a module for the various operations.

1
2
3
4
5
6
7
8
9
10
11
def add(x,y):
     return x + y
 
def sub(x, y):
     return x - y
 
def prod(x, y):
    return x * y
 
def div(x, y):
    return x / y

Save the above code in a file Calc.pyThis is how we create a module in python. We have created different functions in this module. We can use these modules in our main file, lets take a look at how we are going to use them in a program.

How To Use Python Modules?

We will use the import keyword to incorporate the module into our program, from keyword is used to get only a few or specific methods or functions from a module. Lets see what are different methods to use a module in your program.

Lets say we have our file with a name main.py.

1
2
3
4
5
6
import calc as a
a = 10
b = 20
 
addition = a.add(a,b)
print(addition)

In the above code, we have created an alias using the as keyword. The output of the above code will be the addition of the two numbers a and b using the logic specified in the add function in the calc.py module.

Lets take a look at another approach.

1
2
3
4
5
from calc import *
a = 20
b = 30
 
print(add(a,b))

In the above code, we have imported all the functions using the asterisk and we can simply mention the function name to get the results. 

Python Module Path

When we import a module, the interpreter looks for the module in the build-in modules directories in sys.path and if not found, it will look for the module in the following order:

  1. Current directory
  2. PYTHONPATH
  3. Default directory
1
2
3
import sys
 
print(sys.path)

To add Your file path to the system path.You can use


m_directory="home/python_files"
sys.path.append(m_directory)
#

When you run the above code, you will get the list of directories. You can make changes in the list to create your own path. 

Comments

Popular posts from this blog

Is-A and Has-A relationships in python

  In object-oriented programming, the concept of IS-A is a totally based on Inheritance, which can be of two types Class Inheritance or Interface Inheritance. It is just like saying "A is a B type of thing". For example, Apple is a Fruit, Car is a Vehicle etc. Inheritance is uni-directional. For example, House is a Building. But Building is not a House. #Is-A relationship --> By Inheritance class  A:    def   __init__ ( self ):      self .b= 10    def   mym1 ( self ):      print ( 'Parent method' ) class  B(A):    def   mym2 ( self ):      print ( 'Child method' ) d = B() d.mym1() #output: Parent method d.mym2() #output: Child method HAS-A Relationship:  Composition(HAS-A) simply mean the use of instance variables that are references to other objects. For example Maruti has Engine, or House has Bathroom. Let’s understand...

Inheritance and Types in Python

  Inheritance   Creating a new class from existing class is known as inheritance . The class from which features are inherited is known as base class and the class into which features are derived into is called derived class . Syntax: class  derived- class (base  class ):       < class -suite>      Inheritance promotes reusability of code by reusing already existing classes.  Inheritance is used to implement  is-a  relationship between classes.   Following hierarchy is an example representing inheritance between classes:   Single inheritance   When a derived class inherits only from syntax, the base class is called single inheritance. If it has one base class and one derived class it is called single inheritance.   Diagram     Syntax class  A:  #parent class         #some code       class  b(A):...

Exception Handling in Python

  Introduction   An error is an abnormal condition that results in unexpected behavior of a program. Common kinds of errors are syntax errors and logical errors. Syntax errors arise due to poor understanding of the language. Logical errors arise due to poor understanding of the problem and its solution.   Anomalies that occur at runtime are known as exceptions. Exceptions are of two types: synchronous exceptions and asynchronous exceptions. Synchronous exceptions are caused due to mistakes in the logic of the program and can be controlled. Asynchronous exceptions are caused due to hardware failure or operating system level failures and cannot be controlled.   Examples of synchronous exceptions are: divide by zero, array index out of bounds, etc.) . Examples of asynchronous exceptions are: out of memory error, memory overflow, memory underflow, disk failure, etc. Overview of errors and exceptions in Python is as follows:     Handling Exceptions   Flowch...