How to Create Your Own Module in Python: Simple Guide
To create your own module in Python, write your functions and variables in a
.py file and save it with a meaningful name. Then, you can import this file as a module in other Python scripts using the import statement.Syntax
A Python module is simply a file with a .py extension that contains Python code like functions, variables, or classes. You create a module by saving your code in a file, for example, mymodule.py. To use this module in another script, use the import mymodule statement.
Parts explained:
mymodule.py: Your module file name.- Functions, variables, classes: Code inside the module.
import mymodule: Loads the module so you can use its code.
python
def greet(name): return f"Hello, {name}!" pi = 3.14159
Example
This example shows how to create a module named mymodule.py with a function and a variable, then import and use them in another script.
python
# mymodule.py def greet(name): return f"Hello, {name}!" pi = 3.14159 # main.py import mymodule message = mymodule.greet("Alice") print(message) print(f"Value of pi: {mymodule.pi}")
Output
Hello, Alice!
Value of pi: 3.14159
Common Pitfalls
Common mistakes when creating modules include:
- Not saving the file with a
.pyextension. - Trying to import a module from a different folder without setting the path or using packages.
- Using the same name as a built-in Python module, causing conflicts.
- Not restarting the Python interpreter after changing the module code.
python
# Wrong: module file named 'mymodule.txt' (should be .py) # Wrong: importing a module not in the same folder or PYTHONPATH # Right way: # Save as mymodule.py # Place it in the same folder or add folder to PYTHONPATH # Use import mymodule
Quick Reference
Tips for creating and using your own Python modules:
- Always use meaningful file names ending with
.py. - Keep related functions and variables together in one module.
- Use
import module_nameto access module contents. - Use
from module_name import function_nameto import specific parts. - Restart your Python environment after editing modules to see changes.
Key Takeaways
Create a module by saving Python code in a file with a .py extension.
Import your module in other scripts using the import statement.
Avoid naming conflicts with built-in modules and keep your module in the Python path.
Restart your Python interpreter after modifying module code to apply changes.
Use meaningful names and organize related code together in modules.