Learning how to write modular programs in Python not only increases code readability but also enhances code re-usability. Modules allow you to logically organize your Python code, making it easier to understand and use.
A module is basically a file containing Python code, and that code can define functions, classes, or variables. Additionally, a module can also include runnable code. Let’s dive into how to write modular programs in Python.
Step 1 – Create a Module
Start off by creating a module. Modules in Python are simply Python files with the .py extension, which implements a set of functions. Modules are imported from other modules using the import command. As an example, let’s create a module named “mymodule.py”.
1 2 3 |
# Python code to create a module def greet(name): print("Hello, " + name) |
Step 2 – Import a Module
Once a module is created, you can use it in your script by leveraging Python’s import statement. To use the function we defined in our module above, we format the import statement as such:
1 2 3 4 5 6 |
# Python code to illustrate the import statement # import statement example import mymodule # using the function defined in 'mymodule' mymodule.greet('User') |
Step 3 – The dir( ) function
The dir() built-in function in Python, when applied to a module name, returns a sorted list of strings containing the names defined by that module. Check out the Python documentation on the dir() function for more information.
1 2 3 4 5 |
# Python code to illustrate dir() function import mymodule content = dir(mymodule) print(content) |
Step 4 – The globals() and locals() functions
Two other functions that allow us to check the contents of modules are the globals() and locals() functions. As the names suggest, globals() returns a dictionary of the module’s global variables, while locals() returns a dictionary of the module’s local variables.
1 2 3 4 5 6 7 8 |
# Python code to illustrate globals() and locals() functions import mymodule content = globals() print(content) content = locals() print(content) |
Conclusion
Understanding how to write modular code in Python is an important part of becoming a proficient programmer. It not only makes your code more manageable and readable but also fosters code reusability.
As shown in the examples above, creating modules, importing them, and analyzing them with built-in functions such as dir(), globals(), and locals() is quite straightforward in Python.