### Install modshim Source: https://pypi.org/project/modshim Install modshim using pip. This command installs the latest version of the library. ```bash pip install modshim ``` -------------------------------- ### Install modshim Source: https://pypi.org/project/modshim/0.5.1 Install the modshim library using pip. Ensure you specify the version if needed. ```bash pip install modshim ``` -------------------------------- ### Use the shimmed textwrap module Source: https://pypi.org/project/modshim Import and use functions from the newly created `super_textwrap` module. This example demonstrates using the `wrap` function with the custom `prefix` argument. ```python from super_textwrap import wrap text = "This is a long sentence that will be wrapped into multiple lines." for line in wrap(text, width=30, prefix="> "): print(line) ``` -------------------------------- ### Monkey-Patching Example Source: https://pypi.org/project/modshim This demonstrates the traditional monkey-patching approach, which involves altering a module or class at runtime. Modshim offers an alternative to this method. ```python # The monkey-patching way import textwrap from my_enhancements import PrefixedTextWrapper ``` -------------------------------- ### Enhance TextWrapper with Prefix Source: https://pypi.org/project/modshim This example shows how to subclass TextWrapper to add a prefix to each wrapped line and then use modshim to make this enhanced version available. ```python from textwrap import TextWrapper as OriginalTextWrapper from modshim import shim 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]: original_lines = super().wrap(text) if not self.prefix: return original_lines return [f"{self.prefix}{line}" for line in original_lines] shim(lower="textwrap") ``` ```python from super_textwrap import wrap text = "This is a long sentence that will be wrapped into multiple lines." for line in wrap(text, width=30, prefix="* "): print(line) ``` -------------------------------- ### Create Enhancement Package for Requests Source: https://pypi.org/project/modshim This example outlines the creation of an enhancement package 'requests_extra' that overlays the original 'requests' package using modshim. It sets up the entry point to merge submodules automatically. ```python # requests_extra/__init__.py from modshim import shim # This overlays our 'requests_extra' package on the original 'requests' package. # Because 'mount' isn't specified, it defaults to our package name ('requests_extra'). # When a submodule like 'requests_extra.sessions' is imported, modshim will # automatically merge it with the original 'requests.sessions'. shim(lower="requests") ``` -------------------------------- ### Mount Enhanced TextWrapper Over Original Source: https://pypi.org/project/modshim This example demonstrates how to use modshim to completely replace the original 'textwrap' module with an enhanced version, allowing existing code to use the new functionality without import changes. ```python from modshim import shim shim( lower="textwrap", upper="prefixed_textwrap", mount="textwrap", # Mount over the original module name ) ``` ```python # my_app/main.py from my_app import setup_enhancements # Apply the shim first # Now the standard import gets our enhanced version! from textwrap import wrap text = "This is a long sentence that will be wrapped into multiple lines." for line in wrap(text, width=30, prefix=">> "): print(line) ``` -------------------------------- ### Define TextWrapper subclass in prefixed_textwrap.py Source: https://pypi.org/project/modshim Create a Python module to hold your modifications. For classes, subclass the original and redefine methods. This example extends `textwrap.TextWrapper` to add a `prefix` argument. ```python # 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] ``` -------------------------------- ### Use Enhanced Requests with Automatic Retries Source: https://pypi.org/project/modshim Configure logging to observe retry attempts. Use the enhanced `requests_extra` module, which automatically uses the shimmed Session class for functions like `get()`. ```python # Configure logging to show the retry attempts import logging logger = logging.getLogger("urllib3.util.retry") logger.setLevel(logging.DEBUG) logger.addHandler(logging.StreamHandler()) # Use our enhanced module import requests_extra try: response = requests_extra.get("https://httpbin.org/status/503") except Exception as e: print(e) ``` -------------------------------- ### Global Namespace Pollution Example Source: https://pypi.org/project/modshim/0.5.1 This demonstrates how directly assigning to a module attribute pollutes the global namespace, affecting all code. Avoid this approach due to unpredictability and fragility. ```python import textwrap class PrefixedTextWrapper(textwrap.TextWrapper): pass textwrap.TextWrapper = PrefixedTextWrapper ``` -------------------------------- ### Global Namespace Pollution Example Source: https://pypi.org/project/modshim This code demonstrates how directly assigning to a module's attribute pollutes the global namespace, affecting all code in the application. This approach is discouraged due to unpredictable behavior and fragility. ```python textwrap.TextWrapper = PrefixedTextWrapper ``` -------------------------------- ### Create Enhancement Package for Requests Source: https://pypi.org/project/modshim/0.5.1 Sets up an enhancement package ('requests_extra') that overlays the original 'requests' package. This allows for extending 'requests' functionality, such as adding retries, by mirroring the original package structure. ```python # requests_extra/__init__.py from modshim import shim # This overlays our 'requests_extra' package on the original 'requests' package. # Because 'mount' isn't specified, it defaults to our package name ('requests_extra'). # When a submodule like 'requests_extra.sessions' is imported, modshim will # automatically merge it with the original 'requests.sessions'. shim(lower="requests") ``` ```python # requests_extra/sessions.py from requests.adapters import HTTPAdapter ``` -------------------------------- ### Verify Original Module Unchanged Source: https://pypi.org/project/modshim/0.5.1 Demonstrates that the original module is unaffected by the shim operation. Attempts to use new features with the original module will result in errors. ```python # The original module is untouched >>> from textwrap import wrap >>> # It works as it always did, without the 'prefix' argument >>> text = "This is a long sentence that will be wrapped into multiple lines." >>> for line in wrap(text, width=30): ... print(line) ... This is a long sentence that will be wrapped into multiple lines. # Trying to use our new feature with the original module will fail, as expected >>> wrap(text, width=30, prefix="> ") Traceback (most recent call last): ... TypeError: TextWrapper.__init__() got an unexpected keyword argument 'prefix' ``` -------------------------------- ### Shim Module and Rewrite Imports in Extras Source: https://pypi.org/project/modshim Use the `shim` function to replace a module with an enhanced version. The `extras` parameter allows specifying additional packages where imports of the original module should be rewritten to use the enhanced version. ```python from modshim import shim # Shim json with json_enhanced # Also rewrite imports in configparser to use the shimmed version shim( lower="json", upper="json_enhanced", extras=["configparser"], ) ``` -------------------------------- ### Verify original textwrap module is unchanged Source: https://pypi.org/project/modshim Confirm that the original `textwrap` module remains unaffected by the shimming process. This highlights the non-destructive nature of `modshim` compared to monkey-patching. ```python # The original module is untouched >>> from textwrap import wrap # It works as it always did, without the 'prefix' argument >>> text = "This is a long sentence that will be wrapped into multiple lines." >>> for line in wrap(text, width=30): ... print(line) ... This is a long sentence that will be wrapped into multiple lines. # Trying to use our new feature with the original module will fail, as expected >>> wrap(text, width=30, prefix="> ") Traceback (most recent call last): ... TypeError: TextWrapper.__init__() got an unexpected keyword argument 'prefix' ``` -------------------------------- ### Shim textwrap module with prefixed_textwrap modifications Source: https://pypi.org/project/modshim Use `modshim.shim` to merge the original `textwrap` module with your modifications from `prefixed_textwrap`. The result is a new module named `super_textwrap`. ```python from modshim import shim shim( lower="textwrap", # Original module to enhance upper="prefixed_textwrap", # Module with your modifications mount="super_textwrap", # Name for the new, merged module ) ``` -------------------------------- ### Create Enhanced Session with Retries Source: https://pypi.org/project/modshim Subclass the original `requests.sessions.Session` to add automatic retries. Configure retry attempts, backoff factor, and status codes to force retries. ```python from requests.sessions import Session as OriginalSession from urllib3.util.retry import Retry from requests.adapters import HTTPAdapter class Session(OriginalSession): """ Enhanced Session that adds automatic, configurable retries via a mounted HTTPAdapter. Accepts new keyword arguments in its constructor: - retries (int): Total number of retries to allow. - backoff_factor (float): A factor to apply between retry attempts. - status_forcelist (iterable): A set of HTTP status codes to force a retry on. """ def __init__(self, *args, **kwargs): # Extract our custom arguments before calling the parent constructor retries = kwargs.pop("retries", 3) backoff_factor = kwargs.pop("backoff_factor", 0.1) status_forcelist = kwargs.pop("status_forcelist", (500, 502, 503, 504)) super().__init__(*args, **kwargs) # If retries are configured, create a retry strategy and mount it if retries > 0: retry_strategy = Retry( total=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist, ) adapter = HTTPAdapter(max_retries=retry_strategy) self.mount("https://", adapter) self.mount("http://", adapter) ``` -------------------------------- ### Enhance JSON Across Dependencies with Modshim Source: https://pypi.org/project/modshim Use this snippet to make a module like `urllib.request` use an enhanced version of a dependency like `json`. Ensure the enhanced module (`json_enhanced`) is available. ```python from modshim import shim shim( lower="json", upper="json_enhanced", mount="json_enhanced", extras=["urllib.request"], ) # Now urllib.request will use json_enhanced internally import urllib.request # Any JSON operations within urllib.request use json_enhanced ``` -------------------------------- ### Subclassing Session for Enhanced Retries Source: https://pypi.org/project/modshim/0.5.1 Subclass the original `requests.sessions.Session` to add automatic, configurable retries. This enhanced Session can be mounted as an HTTPAdapter. ```python from requests.sessions import Session as OriginalSession from urllib3.util.retry import Retry from requests.adapters import HTTPAdapter class Session(OriginalSession): """ Enhanced Session that adds automatic, configurable retries via a mounted HTTPAdapter. Accepts new keyword arguments in its constructor: - retries (int): Total number of reties to allow. - backoff_factor (float): A factor to apply between retry attempts. - status_forcelist (iterable): A set of HTTP status codes to force a retry on. """ def __init__(self, *args, **kwargs): # Extract our custom arguments before calling the parent constructor retries = kwargs.pop("retries", 3) backoff_factor = kwargs.pop("backoff_factor", 0.1) status_forcelist = kwargs.pop("status_forcelist", (500, 502, 503, 504)) super().__init__(*args, **kwargs) # If retries are configured, create a retry strategy and mount it if retries > 0: retry_strategy = Retry( total=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist, ) adapter = HTTPAdapter(max_retries=retry_strategy) self.mount("https://", adapter) self.mount("http://", adapter) ``` -------------------------------- ### Define Enhanced Session Class for Requests Source: https://pypi.org/project/modshim This code defines an enhanced 'Session' class within 'requests_extra/sessions.py' that subclasses the original 'requests.adapters.HTTPAdapter' to add custom retry logic. ```python # requests_extra/sessions.py from requests.adapters import HTTPAdapter ``` -------------------------------- ### Apply Transparent Bug Fix to JSON Module Source: https://pypi.org/project/modshim This snippet shows how to use modshim to apply a bug fix or security patch to a library like 'json' globally, affecting all subsequent imports without modifying individual import statements. ```python from modshim import shim # Apply our fix to the json module globally shim(lower="json", upper="json_fixes", mount="json") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.