Python Modules

In Python, a module is a file with Python code. This Python file may contain function definitions, variables, classes, and executable statements that can be included in the application.

Create a Module

A module is usually created to split a longer program into several files for easier maintenance.

To create a module, simply create and save a Python file with .py file extension.

Example
my_module.py

def add(a, b):
    result = a + b
    return result

def substract(a, b):
    result = a - b
    return result

Use the Module

To use any function from a module, you simply need to import the module in your code by using the import statement followed by the module name.

Example

import my_module

x = my_module.add(10, 40)
y = my_module.substract(10, 5)
print(x)
print(y)

Module Naming Convention

A module file name can be anything but must have .py file extension. A module file name must start with a small letter and if you want to use multiple words then each word should be separated by _ underscore.

Module Alias Name

You can call your module with a different name by using the as keyword while importing the module.

Example

import my_module as md

x = md.add(10, 40)
y = md.substract(10, 5)
print(x)
print(y)

Import From Module

You can import only some functions, classes, or variables from a module instead of importing the entire module by using the from keyword.

Example

import add from my_module

x = add(10, 40)
print(x)

You can also import multiple parts from a module separated by , comma.

Example

import add, substract from my_module

x = add(10, 40)
y = substract(10, 5)
print(x)
print(y)

Built-in Modules

There are several built-in modules in Python that you can use anywhere in your code.

dir() Function in Python

The dir() function is a built-in function in Python that returns a list of function names and attribute names of the object it is called upon.

Example

import my_module

x = dir(my_module)
print(x)

len() Function in Python

The len() function is a built-in function in Python that returns the length of a string, array, tuple, list, dictionary, etc.

Example

x = "Hello Buddy"
y = [11,23,54,74,54]

x_length = len(x)
y_length = len(y)
print(x)
print(y)