Introducing Python Modules: Organize, Reuse, and Simplify Your Code

In our previous discussion, we delved into the fundamental aspects of programming, introducing the core concepts of sequence, selection, and repetition. In the earlier evolution of programming, the coding landscape allowed us to place all our code within a single file, which would execute from top to bottom. This traditional coding paradigm, while functional, can become unwieldy as projects grow in complexity.

Previously, we mentioned our intention to delve into object-oriented programming (OOP). However, before we embark on that journey, it’s crucial to delve deeper into some fundamental concepts. These fundamentals will not only provide a solid foundation for our understanding of OOP but will also resurface as key principles in the realm of object-oriented programming.

In today’s exploration, we will further broaden our horizons. To begin, we’ll introduce the concept of functions and then venture into the basics of python modules. To facilitate this learning journey, let’s start by creating a new folder named “lesson2” and copying the Dockerfile and docker-compose.yaml file from our previous lesson into it.

Now, let’s consider an example:

# Defining two functions. Any function called by another must be defined before the calling function, hence the order here.
def my_other_function(value):
    print(f"My other function prints the passed value of: {value}")

def my_function():
    print("This function will call my other function")
    my_other_function(7)

Save this code in a file named “functions.py” and execute it using the command: docker-compose run my-environment python functions.py.

Surprisingly, nothing seems to happen! That’s because our “functions.py” file contains functions but lacks a call to “my_function” to trigger “my_other_function.”

Different programming languages handle the execution of such code in various ways. In Python, specifically for standalone scripts like this, we rely on a somewhat magical attribute called “name.” When we run a file directly, “name” is set to “main,” and we can determine if the file has been executed by comparing these two values.

To resolve this, let’s edit our file and add the following code at the bottom:

if __name__ == "__main__":
    my_function()

Now, execute this file again using the command: docker-compose run my-environment python functions.py

You’ll notice that it successfully runs the “my_function” function, effectively calling “my_other_function” as well.

Now lets try something a little different.  Create a new file called consumer.py and to it add:

# This line allows us to access the "my_function" method, which we created in the "functions" module.
from functions import my_function

if __name__ == "__main__":
    my_function()

Then run it with docker-compose run my-environment python consumer.py
You’ll notice that it successfully runs the “my_function” function from our other file. What we’ve accomplished here is the use of a module!

In Python, a module is essentially a file that contains Python definitions, statements, functions, classes (we’ll discuss these later), and variables. Modules can also include executable code. By grouping related code into a module, we make our code more understandable, maintainable, and reusable. This organizational approach also brings a logical structure to our codebase.

As we progress in our programming journey, we’ll explore modules further and learn how to harness their power for more complex projects. Stay tuned for more insights into code modularity and the world of Python programming!

Next time out, Objects. I promise!

Founder & Principal at Daptl | peter@daptl.com | Website | + posts

Nova Scotia-based software developer with a rich history in entrepreneurship and technology. In the year 2000, embarked on a collaborative journey to automate statistical data gathering for a hockey pool, which later evolved into a thriving business focused on curating sports statistics.

Through strategic contracting in various sectors, including telecommunications and insurance, contributed to the growth of the startup, eventually expanding it to a significant enterprise with over 100 employees and worldwide affiliates.

Now, in the phase of semi-retirement, founded 'Daptl' to explore new contracting opportunities, adding another chapter to an already impressive career.

Related posts