Why this topic matters: Organizing your Python code into modules is a fundamental practice for maintaining a clean and scalable codebase. It promotes reusability, improves readability, and simplifies testing and debugging processes.
What you'll learn: In this tutorial, we will discuss how to create custom Python modules, import them into other scripts, and explore best practices for module design.
A Python module is a file containing Python definitions and statements. The names defined in the module can be used from other Python programs after the module has been loaded. To create a new module, simply save your code in a .py
file.
Let's create a simple module called math_utils.py
that contains some useful mathematical functions:
# math_utils.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
Now, in another script main.py
, we can import the math_utils
module and use its functions:
# main.py
import math_utils
result = math_utils.add(3, 4)
print(result) # Output: 7
result = math_utils.multiply(3, 5)
print(result) # Output: 15
What causes it: When you try to use a function or variable that is defined in another module but have not imported the module first.
# Wrong_approach.py
result = math_utils.add(3, 4) # Import statement missing!
Error message:
Traceback (most recent call last):
File "Wrong_approach.py", line 2, in <module>
result = math_utils.add(3, 4)
NameError: name 'math_utils' is not defined
Solution: Always include the import statement at the beginning of your scripts.
Why it happens: Not including the import statement makes the interpreter unable to find the required module.
How to prevent it: Import the necessary modules before using their functions or variables.
What causes it: Trying to access a non-existent attribute, function, or variable within a module.
# Wrong_function.py
import math_utils
result = math_utils.wrong_function(3, 4)
Error message:
Traceback (most recent call last):
File "Wrong_function.py", line 2, in <module>
result = math_utils.wrong_function(3, 4)
AttributeError: module 'math_utils' has no attribute 'wrong_function'
Solution: Ensure that the function or variable you are trying to access is defined within the imported module.
Why it happens: The function or variable does not exist in the specified module, or there might be a typo in its name.
How to prevent it: Double-check your code for typos and make sure that the functions or variables you want to use are defined in the appropriate modules.
__init__.py
files, and the built-in importlib
library.