The Wayback Machine - https://web.archive.org/web/20240910103533/https://www.geeksforgeeks.org/understanding-code-reuse-modularity-python-3/
Open In App

Understanding Code Reuse and Modularity in Python 3

Last Updated : 21 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

What is Object Oriented Programming(OOP)?

OOP is a programming paradigm based on the concept of “objects”, which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods. Learn more here, or just Google “OOP”.
Objects have characteristics and features, known as attributes, and can do various things, through their methods. The biggest feature of OOP is how well objects can be interacted with, and even molded in the future, which makes them very friendly to developers, scale, change over time, testing, and much more.
 

What is Modularity?

Modularity refers to the concept of making multiple modules first and then linking and combining them to form a complete system (i.e, the extent to which a software/Web application may be divided into smaller modules is called modularity). Modularity enables re-usability and will minimize duplication.
 

Flow of the Article

Aim: To learn object oriented programming – Modularity. How can we turn some portions of our code into a library so that it can be used by anyone for future reference. Making the code modular will enable re-usability and minimizes duplication.

Dependencies: pygame

Summary: We are going to make a small game(not really a game) but just an environment and some objects in it. We will try to make the environment static and the objects( blobs in our case) modular. We will make use of PyGame, since it gives us a simple way to actually visualize what we’re doing and building, so we can see our objects in action. What we’re going to do is build Blob World, which is a world that consists of actors, known as blobs. Different blobs have different properties, and the blobs need to otherwise function within their Blob World environment. With this example, we’ll be able to illustrate modularity. 

We are dividing our learning process into two phases.  

  1. Creating the Environment and the Blobs
  2. Understanding Modularity

BLOB WORLD ( Python Code )

Python




import pygame
import random
  
STARTING_BLUE_BLOBS = 10
STARTING_RED_BLOBS = 3
  
WIDTH = 800
HEIGHT = 600
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
  
game_display = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Blob World")
clock = pygame.time.Clock()
  
class Blob:
  
    def __init__(self, color):
        self.x = random.randrange(0, WIDTH)
        self.y = random.randrange(0, HEIGHT)
        self.size = random.randrange(4,8)
        self.color = color
  
    def move(self):
        self.move_x = random.randrange(-1,2)
        self.move_y = random.randrange(-1,2)
        self.x += self.move_x
        self.y += self.move_y
  
        if self.x < 0: self.x = 0
        elif self.x > WIDTH: self.x = WIDTH
          
        if self.y < 0: self.y = 0
        elif self.y > HEIGHT: self.y = HEIGHT
  
  
def draw_environment(blob_list):
    game_display.fill(WHITE)
  
    for blob_dict in blob_list:
        for blob_id in blob_dict:
            blob = blob_dict[blob_id]
            pygame.draw.circle(game_display, blob.color, [blob.x, blob.y], blob.size)
            blob.move()
  
    pygame.display.update()
      
  
def main():
    blue_blobs = dict(enumerate([Blob(BLUE) for i in range(STARTING_BLUE_BLOBS)]))
    red_blobs = dict(enumerate([Blob(RED) for i in range(STARTING_RED_BLOBS)]))
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
        draw_environment([blue_blobs,red_blobs])
        clock.tick(60)
  
if __name__ == '__main__':
    main()


Output: 

PART(1/2): Blob World In this part, we are creating a simple game environment and some objects in it because visualizing what we have created is an exceptional way of learning programming. All we need to understand is how to make our code modular.

PART(2/2): Modularity In this second part, we are going to understand an essential feature of Object Oriented Programming, i.e Modularity. So far, we’ve not introduced anything that will make this (BLOB WORLD code) too hard to maintain or scale over time, at least within the scope of what we can do with PyGame. What about making it modular? There’s a really easy test for this, let’s try to import it! 

To do this, let’s have two files. Let’s copy the Blob class and random, and make a new file: blob.py  

import random

class Blob:

    def __init__(self, color):
        self.x = random.randrange(0, WIDTH)
        self.y = random.randrange(0, HEIGHT)
        self.size = random.randrange(4,8)
        self.color = color

    def move(self):
        self.move_x = random.randrange(-1,2)
        self.move_y = random.randrange(-1,2)
        self.x += self.move_x
        self.y += self.move_y

        if self.x  WIDTH: self.x = WIDTH
        
        if self.y  HEIGHT: self.y = HEIGHT

Back to our original file, let’s remove the Blob class, and then import Blob from blob.py.  

import pygame
import random
from blob import Blob

STARTING_BLUE_BLOBS = 10
...

Immediately, we’re given an error in the blob.py file, regarding our Blob class, where we have some undefined variables. This is definitely a problem with writing classes, we should try to avoid using constants or variables outside of the class. Let’s add these values to the __init__ method, then modify all of the parts where we used the constants. 
So, here is our new Blob class file :blob.py 

Next, within our original file, when we call the Blob class, it’s expecting some values for those arguments, so you’d add those in the main function:  

def main():
    blue_blobs = dict(enumerate([Blob(BLUE,WIDTH,HEIGHT) for i in range(STARTING_BLUE_BLOBS)]))
    red_blobs = dict(enumerate([Blob(RED,WIDTH,HEIGHT) for i in range(STARTING_RED_BLOBS)]))
    while True:
        ...

Great, so now our Blob class can at least be imported, so it’s modular by nature already! Another good idea is to attempt to give the developer that is using your code as much power as possible, and to make your class as generalize-able as possible. At least one example where we could definitely give more to the programmer using this class is in the definition of the blob’s size:  

  self.size = random.randrange(4,8) 

Is there any reason why we wouldn’t want to give the programmer an easy way to change these? I don’t think so. Unlike x_boundary and y_boundary, however, we do not necessarily *need* the programmer to provide us a value for the size, since we can at least use a reasonable starting default. Thus, we can do something like:  

class Blob:

    def __init__(self, color, x_boundary, y_boundary, size_range=(4,8)):
        self.x_boundary = x_boundary
        self.y_boundary = y_boundary
        self.x = random.randrange(0, self.x_boundary)
        self.y = random.randrange(0, self.y_boundary)
        self.size = random.randrange(size_range[0],size_range[1])
        self.color = color

Now, if the programmer wants to change the size, they can, otherwise they don’t have to. We might also want to allow the programmer to modify the speed of the blob if they want to: 

import random


class Blob:

    def __init__(self, color, x_boundary, y_boundary, size_range=(4,8), movement_range=(-1,2)):
        self.size = random.randrange(size_range[0],size_range[1])
        self.color = color
        self.x_boundary = x_boundary
        self.y_boundary = y_boundary
        self.x = random.randrange(0, self.x_boundary)
        self.y = random.randrange(0, self.y_boundary)
        self.movement_range = movement_range

    def move(self):
        self.move_x = random.randrange(self.movement_range[0],self.movement_range[1])
        self.move_y = random.randrange(self.movement_range[0],self.movement_range[1])
        self.x += self.move_x
        self.y += self.move_y

        if self.x  self.x_boundary: self.x = self.x_boundary
        
        if self.y  self.y_boundary: self.y = self.y_boundary

Now we’ve opened up the class quite a bit. Does anything else jump out at us? Yes, the line where we force the blob to remain in-bounds. Might there be examples where we’d like the blobs to be able to roam freely out of view? Certainly! Is this bounding code useful though? Is it likely that programmers will want to make use of this quite often? Certainly! however, that it makes more sense to either not have the code at all, or to give it its own method, like so: 

import random

class Blob:

    def __init__(self, color, x_boundary, y_boundary, size_range=(4,8), movement_range=(-1,2)):
        self.size = random.randrange(size_range[0],size_range[1])
        self.color = color
        self.x_boundary = x_boundary
        self.y_boundary = y_boundary
        self.x = random.randrange(0, self.x_boundary)
        self.y = random.randrange(0, self.y_boundary)
        self.movement_range = movement_range

    def move(self):
        self.move_x = random.randrange(self.movement_range[0],self.movement_range[1])
        self.move_y = random.randrange(self.movement_range[0],self.movement_range[1])
        self.x += self.move_x
        self.y += self.move_y

    def check_bounds(self):
        if self.x  self.x_boundary: self.x = self.x_boundary
        
        if self.y  self.y_boundary: self.y = self.y_boundary

Now, the programmer can decide to use it or not. You could also give some sort of argument in the move method, where, if True, then boundaries would be enforced. 
So we got a glimpse of how we can make our python code Modular.

Resources: 

 



Previous Article
Next Article

Similar Reads

Understanding ‘fork’ and ‘spawn’ in Python Multiprocessing
Python’s multiprocessing library provides a powerful way to leverage multiple processor cores for concurrent execution, enhancing the performance of computationally intensive tasks. One of the intriguing aspects of multiprocessing is the ability to initiate new processes using various start methods. These start methods not only facilitate the creat
6 min read
Understanding Versions, Ranges, and Constraints in Python Poetry
Managing dependencies is a fundamental aspect of maintaining a Python project. Poetry, a powerful dependency management tool, simplifies this process by providing a clear and concise way to declare, manage, and resolve dependencies. Here we check how to specify dependencies in Poetry, adding, removing, updating dependencies, and the use of versions
3 min read
Understanding for-loop in Python
A Pythonic for-loop is very different from for-loops of other programming language. A for-loop in Python is used to loop over an iterator however in other languages, it is used to loop over a condition. In this article, we will take a deeper dive into Pythonic for-loop and witness the reason behind this dissimilarity. Let's begin by familiarizing o
6 min read
Deconstructing Interpreter: Understanding Behind the Python Bytecode
When the CPython interpreter executes your program, it first translates onto a sequence of bytecode instructions. Bytecode is an intermediate language for the Python virtual machine that’s used as a performance optimization. Instead of directly executing the human-readable source code, compact numeric codes, constants, and references are used that
4 min read
Understanding Boolean Logic in Python 3
Booleans are simple and easy to use concepts that exist in every programming language. A boolean represents an idea of "true" or "false." While writing an algorithm or any program, there are often situations where we want to execute different code in different situations. Booleans help our code to do just that easy and effective. More often, a bool
3 min read
Understanding Python Dataclasses
DataClasses has been added in a recent addition in python 3.7 as a utility tool for storing data. DataClasses provides a decorator and functions for automatically adding generated special methods such as __init__() , __repr__() and __eq__() to user-defined classes. DataClass in Python DataClasses are like normal classes in Python, but they have som
7 min read
Understanding Recursive Functions with Python
Recursion is characterized as the process of describing something in terms of itself; in other words, it is the process of naming the function by itself. Recursion is the mechanism of a function calling itself directly or implicitly, and the resulting function is known as a Recursive function. Advantages:Code reusabilityEasily understandableTime co
3 min read
Understanding the Role of Parent Class's init() in Python Inheritance
In object-oriented programming (OOP) inheritance allows classes to inherit attributes and methods from other classes. This enables code reuse and the creation of complex systems. When creating a new class (child) from an existing class (parent) a common question is whether the __init__() method of the child class should call the __init__() method o
3 min read
Understanding Python PyInstaller Hooks
In the world of Python development, distributing applications can sometimes be a complex task. PyInstaller simplifies this process by packaging Python applications into standalone executables, enabling them to run on systems without requiring a Python interpreter. However, creating an executable that includes all necessary dependencies can be trick
5 min read
Understanding Python Pickling with example
In Python, we sometimes need to save the object on the disk for later use. This can be done by using Python pickle. In this article, we will learn about pickles in Python along with a few examples. Python Pickle — Python object serializationPython pickle module is used for serializing and de-serializing a Python object structure. Any object in Pyth
7 min read
Understanding Django: Model() vs Model.objects.create()
In Django, when working with models, understanding the differences between Model() and Model.objects.create() is crucial for effective database operations. Both methods serve distinct purposes and are used in different contexts within Django's ORM (Object-Relational Mapping). The Basics: Django ModelsIn Django, a model is a Python class that subcla
3 min read
Understanding Activation Functions in Depth
What is an Activation function ? In artificial neural networks, the activation function of a node defines the output of that node or neuron for a given input or set of inputs. This output is then used as input for the next node and so on until a desired solution to the original problem is found. It maps the resulting values into the desired range s
8 min read
Reusable piece of python functionality for wrapping arbitrary blocks of code : Python Context Managers
Context Managers are the tools for wrapping around arbitrary (free-form) blocks of code. One of the primary reasons to use a context manager is resource cleanliness. Context Manager ensures that the process performs steadily upon entering and on exit, it releases the resource. Even when the wrapped code raises an exception, the context manager guar
7 min read
Top 10 Python Built-In Decorators That Optimize Python Code Significantly
Python is a widely used high-level, general-purpose programming language. The language offers many benefits to developers, making it a popular choice for a wide range of applications including web development, backend development, machine learning applications, and all cutting-edge software technology, and is preferred for both beginners as well as
12 min read
Different Python IDEs and Code Editors
What Are IDEs and Code Editors : IDE is a combination of tools that help in software development. IDE makes coding easier. As the name implies the Integrated Development Environment(IDE), it is a pack of tools combined or integrated together to establish software development at ease. The combination of tools include, a code editor that helps with l
5 min read
Debugging Python code using breakpoint() and pdb
While developing an application or exploring some features of a language, one might need to debug the code anytime. Therefore, having an idea of debugging the code is quite necessary. Let's see some basics of debugging using the built-in breakpoint() function and pdb module. Python breakpoint() We know that a debugger plays an important role when w
3 min read
Build Python code editor using CodeMirror and pyodide
In this article, we will learn to develop an application which can run the Python code inside your web browser. To achieve this, we will use pyodide.org, which consists of the CPython interpreter compiled to WebAssembly which allows Python to run in the browser. We are going to use codemirror.net in Python-mode as a code-editor component. You can f
4 min read
Create Plotly Express charts in less lines of code using Python and Datamallet
In this article, we will see how to create all possible Plotly express charts in very less lines of code using a new Python Module known as datamallet. Introduction to the datamallet Library According to the PyPi website datamallet library is made by Data Scientists to help fellow Data Scientists easily Visualize data in the least amount of line of
5 min read
10 Tips and Tricks to Write the Better Python Code
Writing code is hard, and Python programmers often face a steep learning curve. One of the most common issues that can prevent you from writing readable code is bad practices in organizing your code. In this article, we'll discuss some ways to help you avoid making those mistakes and get better at writing Python code. The best thing in writing bett
9 min read
Packaging and Publishing Python code
If you have been coding in python, even for a while, you must be familiar with the concept of 'pip' by now. It is a package management system used to install and manage software packages/libraries written in Python. Then one may ask that where are all these packages/libraries stored? It is obvious that there must be a large "on-line repository" whi
7 min read
10 Best Python IDEs and Code Editors in 2024
Python... the most popular and favorite programming language in the world for programmers of all age groups. If you are a beginner this language is strongly recommended to learn first. Well, In programming, we all know the importance of code editor and IDEs to write our program and execute it but choosing the best code editor or IDE is always a con
10 min read
Python code to move spaces to front of string in single traversal
Given a string that has set of words and spaces, write a program to move all spaces to front of string, by traversing the string only once. Examples: Input : str = "geeks for geeks" Output : str = " geeksforgeeks" Input : str = "move these spaces to beginning" Output : str = " movethesespacestobeginning" There were four space characters in input, a
5 min read
Python code to print common characters of two Strings in alphabetical order
Given two strings, print all the common characters in lexicographical order. If there are no common letters, print -1. All letters are lower case. Examples: Input : string1 : geeks string2 : forgeeks Output : eegks Explanation: The letters that are common between the two strings are e(2 times), g(1 time), k(1 time) and s(1 time). Hence the lexicogr
2 min read
Code introspection in Python
.numpy-table { font-family: arial, sans-serif; border-collapse: collapse; border: 1px solid #5fb962; width: 100%; } .numpy-table td, th { background-color: #c6ebd9; border: 1px solid #5fb962; text-align: left; padding: 8px; } .numpy-table td:nth-child(odd) { background-color: #c6ebd9; } .numpy-table th { border: 1px solid #5fb962; text-align: left;
4 min read
Python Code for time Complexity plot of Heap Sort
Prerequisite : HeapSort Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element. We implement Heap Sort here, call it for different sized random lists, meas
3 min read
Python | Generate QR Code using pyqrcode module
Let's see how to generate QR code in Python using pyqrcode module. pyqrcode module is a QR code generator. The module automates most of the building process for creating QR codes. This module attempts to follow the QR code standard as closely as possible. The terminology and the encodings used in pyqrcode come directly from the standard. Installati
2 min read
Issues with using C code in Python | Set 1
Prerequisite: Using C codes in Python | Set 1, Set 2 Issue #1 : If using ctypes then there is a problem that the original C code may use language that don’t map cleanly to Python. Let's take the example of divide() function as it returns a value through one of its arguments. It is a common C technique but it is often not clear how it is supposed to
2 min read
Issues with using C code in Python | Set 2
Prerequisite: Issues with using C code in Python | Set 1 The DoubleArrayType class can handle the situation of Python having different forms like array, numpy array, list, tuple. In this class, a single method from_param() is defined. This method takes a single parameter and narrow it down to a compatible ctypes object (a pointer to a ctypes.c_doub
3 min read
Code Golfing in Python
Code Golf in Python refers to attempting to solve a problem using the least amount of characters possible. Like in Golf, the low score wins, the fewest amount of characters "wins". Python is a fantastic language for code golfing due to backward compatibility, quirks, it being a high-level language, and all the coercion. So, here we will look at som
8 min read
Python code formatting using Black
Writing well-formatted code is very important, small programs are easy to understand but as programs get complex they get harder and harder to understand. At some point, you can’t even understand the code written by you. To avoid this, it is needed to write code in a readable format. Here Black comes into play, Black ensures code quality. What is B
3 min read
Article Tags :
Practice Tags :