Skip to main content

Introduction to Python Modules

Python Modules

A module is a file that contains Python definitions, statements, and functions.

Modules allow you to organize your Python code logically into separate files, making it easier to manage and reuse code across different projects.

You can think of a module as a library of code that you can import and use in your programs.

To use a module, you need to perform the following steps:

Module Creation

Create a new Python file with a .py extension, which will serve as your module.

In this file, you can define functions, classes, variables, and any other Python code that you want to include in your module.

As an example:

Let's create a module named my_module.py

# my_module.py

def greet(name):
print(f"Hello, {name}!")

def square(x):
return x * x

pi = 3.14159

In this example:

  • The my_module.py file defines two functions (greet() and square()) and a variable (pi).

Module Import

To use the code from your module in another Python file, you need to import it.

You can import the entire module or specific functions, classes, or variables from the module.

As an example:

Let's import the my_module module and using its functions and variables.

# main.py

import my_module

my_module.greet("Alice") # Output: Hello, Alice!
result = my_module.square(5)
print(result) # Output: 25
print(my_module.pi) # Output: 3.14159

In this example:

  • The my_module module is imported using the import statement.
  • You can access the functions and variables from the module using the module_name.function_name or module_name.variable_name syntax.

Selective Import

If you only need specific functions or variables from a module, you can selectively import them using the from keyword.

This allows you to use the imported functions or variables directly without specifying the module name.

As an example:

# main.py

from my_module import greet, square

greet("Bob") # Output: Hello, Bob!
result = square(3)
print(result) # Output: 9

In this example:

  • Only the greet and square functions are imported from the my_module module.
  • They can be used directly without referencing the module name.
tip

Modules provide a way to organize your code into separate files, promote code reusability, and make your codebase more maintainable.