
PYTHON — Creating Python Modules
In the age of technology, ignorance is a choice. — Donny Miller
Creating Python Modules
In Python, modules are files containing Python definitions and statements. The filename becomes the module name. Within a module, the module’s name is available as a global variable __name__.
To create a Python module, follow the steps below:
- Open your preferred Python editor or IDLE and start a new editor window.
- Define a function within the editor window. For example, you can create a function called
addthat returns the sum of its two parameters:
def add(x, y): return x + y
- Save the file with a
.pyextension, for example asadder.py, in a new directory namedmyproject/. - Open another editor window and type the following code:
from adder import add value = add(2, 2) print(value)
- Save the file as
main.pyin the samemyproject/folder. - Run the module.
When you run the main.py module, you may encounter a NameError displayed in the interactive window. This occurs because the add() function is defined in the adder.py module and not in main.py, the file that was executed. To resolve this issue, you need to import the add() function from the adder.py module into main.py using the import statement:
from adder import addBy adding this line to main.py, you are able to use the add() function from the adder.py module within main.py.
Overall, the process involves creating a module by defining a function within a Python file, importing the function into another file, and then running the module.
This process demonstrates the basic concept of creating and using Python modules. It’s a fundamental aspect of structuring code in Python and enables you to organize and reuse your code effectively. By breaking down your code into separate modules, you can maintain a clean and modular codebase, making it easier to manage and maintain your projects.
