You’re the Expert!

pynfinity

Build mountain with each pebble 🧗

Topics | Stepping Stones

📚 Guides

🌍 Pebbles & Contributions

✍️ Write a Post
🗺️ Folium Maps
🗺️ Folium Maps
⏳ Time Series Resampling
⏳ Time Series Resampling
📦 Dataclasses
📦 Dataclasses
🔁 Itertools
🔁 Itertools
🗄️ SQLAlchemy Basics
🗄️ SQLAlchemy Basics
📄 JSON Handling
📄 JSON Handling
🖥️ OS Module
🖥️ OS Module
🔢 NumPy Arrays
🔢 NumPy Arrays
⚡ Generators
⚡ Generators
🐼 Pandas DataFrames
🐼 Pandas DataFrames
🎛️ Multiprocessing
🎛️ Multiprocessing
⚡ FastAPI Endpoints
⚡ FastAPI Endpoints
📜 List Comprehensions
📜 List Comprehensions
🪵 Logging
🪵 Logging
🚀 Streamlit Apps
🚀 Streamlit Apps
🧪 Pytest Testing
🧪 Pytest Testing
🧹 Data Cleaning with Dropna
🧹 Data Cleaning with Dropna
🧠 TensorFlow Basics
🧠 TensorFlow Basics
🌲 Git Basics
🌲 Git Basics
📦 Virtual Environments
📦 Virtual Environments
🏷️ Type Hinting
🏷️ Type Hinting
🚪 Context Managers
🚪 Context Managers
🛠️ Functools
🛠️ Functools
🤖 Scikit-Learn Linear Regression
🤖 Scikit-Learn Linear Regression
🧩 Regular Expressions
🧩 Regular Expressions
🎀 Decorators
🎀 Decorators
📸 OpenCV Image Reading
📸 OpenCV Image Reading
💻 Argparse CLI
💻 Argparse CLI
✨ Jupyter Magic Commands
✨ Jupyter Magic Commands
🛡️ Pydantic Models
🛡️ Pydantic Models
🕸️ Web Scraping with BeautifulSoup
🕸️ Web Scraping with BeautifulSoup
📊 Interactive Plots with Plotly
📊 Interactive Plots with Plotly
📚 Collections Module
📚 Collections Module
📝 NLTK Tokenization
📝 NLTK Tokenization
λ Lambda Functions
λ Lambda Functions
📉 Matplotlib Plotting
📉 Matplotlib Plotting
🔥 Seaborn Heatmaps
🔥 Seaborn Heatmaps
🧵 Multithreading
🧵 Multithreading
⏳ AsyncIO
⏳ AsyncIO
🔥 PyTorch Tensors
🔥 PyTorch Tensors
⚙️ Sys Module
⚙️ Sys Module
☁️ AWS S3 with Boto3
☁️ AWS S3 with Boto3
🥒 Pickle Serialization
🥒 Pickle Serialization
🕸️ NetworkX Graphs
🕸️ NetworkX Graphs
➗ Math Module
➗ Math Module
🔍 Exploratory Data Analysis (EDA)
🔍 Exploratory Data Analysis (EDA)
📊 CSV Processing
📊 CSV Processing
🐳 Dockerfiles
🐳 Dockerfiles
📉 Statsmodels OLS
📉 Statsmodels OLS
+ New Post

🎨 Design Patterns in Python

Design patterns are typical solutions to common problems in software design. Python's dynamic nature often allows for simpler implementations of these patterns compared to languages like Java or C++.


1️⃣ Singleton Pattern

Ensures a class has only one instance.

Pythonic Way (Module):
Modules are singletons in Python. Just define variables/functions in a module and import it.

Class Way:

class Singleton:
    _instance = None
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

s1 = Singleton()
s2 = Singleton()
print(s1 is s2) # True

2️⃣ Factory Pattern

Creates objects without specifying the exact class of object that will be created.

class Dog:
    def speak(self): return "Woof!"

class Cat:
    def speak(self): return "Meow!"

def get_pet(pet="dog"):
    pets = dict(dog=Dog(), cat=Cat())
    return pets[pet]

d = get_pet("dog")
print(d.speak())

3️⃣ Observer Pattern

Defines a dependency between objects so that when one changes state, all its dependents are notified.

class Subject:
    def __init__(self):
        self._observers = []

    def attach(self, observer):
        self._observers.append(observer)

    def notify(self, message):
        for observer in self._observers:
            observer.update(message)

class Observer:
    def update(self, message):
        print(f"Received: {message}")

subject = Subject()
observer = Observer()
subject.attach(observer)
subject.notify("Hello Observers!")

4️⃣ Strategy Pattern

Enables selecting an algorithm at runtime.

import types

class Strategy:
    def __init__(self, func=None):
        if func:
            self.execute = types.MethodType(func, self)

    def execute(self):
        print("Default Strategy")

def strategy_one(self):
    print("Strategy One")

def strategy_two(self):
    print("Strategy Two")

s = Strategy(strategy_one)
s.execute() # Strategy One

s = Strategy(strategy_two)
s.execute() # Strategy Two

📝 Summary

  • Singleton: One instance (Modules, __new__).
  • Factory: Object creation abstraction.
  • Observer: Event handling system.
  • Strategy: Swappable algorithms.
  • Pythonic: Python often simplifies these patterns significantly.

Created with ❤️ by Pynfinity



Pynfinity
Install Pynfinity Add to home screen for the best experience