
PYTHON — Working with Python Modules
Innovation distinguishes between a leader and a follower. — Steve Jobs
Working With Python Modules
Python provides a way to organize code into reusable and manageable parts called modules. A module is essentially a file containing Python code. In this article, you will learn how to create and work with modules in Python.
Creating Modules
As mentioned, a module is a file containing Python code that can be reused in other Python code files. Let’s start by creating a simple module.
Create a file named my_module.py and add the following code:
# my_module.py
def greet(name):
print(f"Hello, {name}!")
def calculate_square(num):
return num ** 2In this example, the my_module.py file contains a greet function and a calculate_square function. This file can now be used as a module in other Python files.
Using Modules
Once a module is created, you can use its functions and variables in other Python files by importing it.
Create a new file named main.py and import the my_module module:
# main.py
import my_module
my_module.greet("Alice")
result = my_module.calculate_square(5)
print(result)In this example, the main.py file imports the my_module module and uses its greet and calculate_square functions.
Accessing Objects From Inside a Module
If you want to access objects from inside a module, you can use dot notation.
For example, to access the greet function from the my_module module:
# main.py
import my_module
my_module.greet("Bob")Adjusting Import Statements
In Python, you can adjust import statements to rename imported modules or import specific objects from a module.
To rename an imported module:
# main.py
import my_module as custom_module
custom_module.greet("Charlie")To import specific objects from a module:
# main.py
from my_module import greet
greet("David")Conclusion
In summary, modules in Python allow you to organize code into reusable components. You can create modules by defining functions and variables in a separate file and then use these modules in other Python files by importing them. Additionally, you can adjust import statements to rename modules or import specific objects. Start using modules to organize and reuse your Python code effectively.
