Show HN: Modshim – a new alternative to monkey-patching in Python

https://news.ycombinator.com/rss Hits: 10
Summary

modshim A Python library for enhancing existing modules without modifying their source code - a clean alternative to forking, vendoring, and monkey-patching. Overview modshim allows you to overlay custom functionality onto existing Python modules while preserving their original behavior. This is particularly useful when you need to: Fix bugs in third-party libraries without forking Modify the behavior of existing functions Add new features or options to existing classes Test alternative implementations in an isolated way It works by creating a new, "shimmed" module that combines the original code with your enhancements, without modifying the original module. Installation pip install modshim Usage Suppose we want to enhance the standard library's textwrap module. Our goal is to add a prefix argument to TextWrapper to prepend a string to every wrapped line. First, create a Python module containing your modifications. It should mirror the structure of the original textwrap module, redefining only the parts we want to modify. For classes like TextWrapper , this can be done by creating a subclass with the same name as the original class: # prefixed_textwrap.py # Import the class you want to extend from the original module from textwrap import TextWrapper as OriginalTextWrapper # Sub-class to override and extend functionality class TextWrapper ( OriginalTextWrapper ): """Enhanced TextWrapper that adds a prefix to each line.""" def __init__ ( self , * args , prefix : str = "" , ** kwargs ) -> None : self . prefix = prefix super (). __init__ ( * args , ** kwargs ) def wrap ( self , text : str ) -> list [ str ]: """Wrap text and add prefix to each line.""" original_lines = super (). wrap ( text ) if not self . prefix : return original_lines return [ f" { self . prefix } { line } " for line in original_lines ] Next, use modshim to mount your modifications over the original textwrap module, creating a new, combined module. > >> from modshim import shim > >> shim ( ... upper = ...

First seen: 2025-10-22 04:16

Last seen: 2025-10-22 13:22