How to Write Modular Programs in Python

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”.

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:

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.

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.

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.