### Running Autowrapt Example Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/14-automatic-patching-of-python-applications.md Demonstrates how to run the autowrapt example by installing the package and then importing the 'this' module, which triggers the Zen of Python display. ```bash pip install autowrapt ``` ```python import this ``` -------------------------------- ### Install wrapt using pip Source: https://github.com/grahamdumpleton/wrapt/blob/develop/README.md Use this command to install the wrapt package. ```bash pip install wrapt ``` -------------------------------- ### Basic wrapt Setup for Method Replacement Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/12-using-wrapt-to-support-testing-of-software.md Provides a basic setup using wrapt's transient_function_wrapper to replace a method on an instance with a wrapper that encapsulates the original method. ```python from wrapt import transient_function_wrapper, function_wrapper ``` -------------------------------- ### Setup Configuration for Autowrapt Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/14-automatic-patching-of-python-applications.md Configures the setup.py file for the autowrapt package, specifying package details, data files (including the .pth file), entry points, and installation requirements. ```python import sys import os from setuptools import setup from distutils.sysconfig import get_python_lib setup_kwargs = dict( name = 'autowrapt', packages = ['autowrapt'], package_dir = {'autowrapt': 'src'}, data_files = [(get_python_lib(prefix=''), ['autowrapt-init.pth'])], entry_points = {'autowrapt.examples’: ['this = autowrapt.examples:autowrapt_this']}, install_requires = ['wrapt>=1.10.4'], ) setup(**setup_kwargs) ``` -------------------------------- ### Callable Decorator Example Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/decorators.md Illustrates a simple callable decorator that returns a factory. ```python def __call__(self, wrapped): return self.factory(wrapped) ``` -------------------------------- ### Decorated Method Example Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/10-performance-overhead-when-applying-decorators-to-methods.md An example of how to apply the custom decorator to a method. This demonstrates the usage pattern for the `decorator` function. ```python @decorator def my_function_wrapper(wrapped, instance, args, kwargs): return wrapped(*args, **kwargs) ``` -------------------------------- ### Decorator Factory Usage Example Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/03-implementing-a-factory-for-creating-decorators.md An example demonstrating how to use a decorator factory to create a decorator. The user only needs to provide a wrapper function that handles the actual work. ```python @decorator def my_function_wrapper(wrapped, args, kwargs): return wrapped(*args, **kwargs) @my_function_wrapper def function(): pass ``` -------------------------------- ### Setuptools Setup for Monkey Patch Package Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/13-ordering-issues-when-monkey-patching-in-python.md Configuration for a setuptools package that provides monkey patches. It defines entry points for discovering and applying patches. ```python from setuptools import setup NAME = 'wrapt_patches.tempfile_debugging' def patch_module(module, function=None): function = function or 'patch_%s' % module.replace('.', '_') return '%s = %s:%s' % (module, NAME, function) ENTRY_POINTS = [ patch_module('tempfile'), ] setup_kwargs = dict( name = NAME, version = '0.1', packages = ['wrapt_patches'], package_dir = {'wrapt_patches': 'src'}, entry_points = { NAME: ENTRY_POINTS }, ) setup(**setup_kwargs) ``` -------------------------------- ### Running Autowrapt with Environment Variable Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/14-automatic-patching-of-python-applications.md Runs the Python interpreter with the AUTOWRAPT_BOOTSTRAP environment variable set to 'autowrapt.examples', enabling the example monkey patch to be applied. ```bash AUTOWRAPT_BOOTSTRAP=autowrapt.examples python ``` -------------------------------- ### Building a Mocking Framework Base with wrapt Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/12-using-wrapt-to-support-testing-of-software.md An example illustrating how wrapt can serve as a foundation for building more sophisticated mocking libraries. This snippet shows a basic structure for a 'patch' function that could be extended. ```python from wrapt import transient_function_wrapper class ProductionClass: def method(self, a, b, c, key): pass def patch(module, name): def _decorator(wrapped): class Wrapper: pass ``` -------------------------------- ### Instance Method Synchronization Example Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/07-the-missing-synchronized-decorator.md Demonstrates that instance methods on the same object share a single lock, ensuring mutual exclusion. The lock is stored on the instance. ```python >>> o1 = Object() >>> o2 = Object() >>> o1.method_im() >>> o1._synchronized_lock <_RLock owner=None count=0> >>> id(o1._synchronized_lock) 4386605392 >>> o2.method_im() >>> o2._synchronized_lock <_RLock owner=None count=0> >>> id(o2._synchronized_lock) 4386605456 ``` -------------------------------- ### Implement __reduce__ for Pickle Compatibility Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/examples.md In older versions of wrapt (< 2.2.0), both __reduce__ and __reduce_ex__ needed to be overridden. This example shows the delegation from __reduce_ex__ to __reduce__ for backward compatibility. ```default def __reduce_ex__(self, protocol): return self.__reduce__() ``` -------------------------------- ### Minimal Object Proxy Example Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/02-the-interaction-between-decorators-and-descriptors.md A basic implementation of an object proxy that forwards attribute access to the wrapped object. This serves as a foundation for more complex proxying mechanisms. ```python class object_proxy: def __init__(self, wrapped): self.wrapped = wrapped try: self.__name__= wrapped.__name__ except AttributeError: pass @property def __class__(self): return self.wrapped.__class__ def __getattr__(self, name): return getattr(self.wrapped, name) ``` -------------------------------- ### Declaring Entry Points in `pyproject.toml` Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/monkey.md An example of how to declare entry points for patches in a plugin's `pyproject.toml` file. The entry point name corresponds to the target module name. ```toml [project.entry-points."my_app.patches"] requests = "my_patches.requests_patches:apply" ``` -------------------------------- ### Accessing Decorated Function Documentation Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/decorators.md Use the standard Python help system to get documentation for a decorated function. This will display the documentation string of the original wrapped function. ```python @wrapt.decorator def my_decorator(wrapped, instance, args, kwargs): return wrapped(*args, **kwargs) @my_decorator def function(arg1, arg2): """Function documentation.""" pass >>> help(function) Help on function function in module __main__: function(arg1, arg2) Function documentation. ``` -------------------------------- ### Usage examples of the original @synchronized decorator Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/08-the-synchronized-decorator-as-context-manager.md Demonstrates various ways the @synchronized decorator can be applied to different types of functions and methods. ```python @synchronized # lock bound to function1 def function1(): pass @synchronized # lock bound to function2 def function2(): pass @synchronized # lock bound to Class class Class: @synchronized # lock bound to instance of Class def function_im(self): pass @synchronized # lock bound to Class @classmethod def function_cm(cls): pass @synchronized # lock bound to function_sm @staticmethod def function_sm(): pass ``` -------------------------------- ### Java Synchronized Counter Example Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/07-the-missing-synchronized-decorator.md Demonstrates how to make methods synchronized in Java using the 'synchronized' keyword. This ensures that only one thread can execute synchronized methods on the same object at a time. ```java public class SynchronizedCounter { private int c = 0; public synchronized void increment() { c++; } public synchronized void decrement() { c--; } public synchronized int value() { return c; } } ``` -------------------------------- ### Executable Code in .pth Files Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/14-automatic-patching-of-python-applications.md Demonstrates how lines starting with 'import' in a .pth file are executed as Python code during interpreter startup. This allows for automatic execution of arbitrary code, such as setting up package paths or performing other initialization tasks. ```python import sys; sys.__plen = len(sys.path) ./antigravity-0.1-py2.7.egg import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sys.path[p:p]=new; sys.__egginsert = p+len(new) ``` -------------------------------- ### Universal Decorator Example Source: https://github.com/grahamdumpleton/wrapt/blob/develop/RELEASE.rst Demonstrates a universal decorator that handles functions, methods, and classes by inspecting the 'instance' and 'wrapped' arguments. It checks if the decorator is applied to a class, classmethod, function, staticmethod, or instancemethod. ```python import inspect @wrapt.decorator def universal(wrapped, instance, args, kwargs): if instance is None: if inspect.isclass(wrapped): # Decorator was applied to a class. return wrapped(*args, **kwargs) else: # Decorator was applied to a function or staticmethod. return wrapped(*args, **kwargs) else: if inspect.isclass(instance): # Decorator was applied to a classmethod. return wrapped(*args, **kwargs) else: # Decorator was applied to an instancemethod. ``` -------------------------------- ### Java Fine-Grained Locking Example Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/07-the-missing-synchronized-decorator.md Shows how to achieve finer-grained locking in Java by using separate objects for synchronization. This allows different parts of a class to be synchronized independently. ```java public class MsLunch { private long c1 = 0; private long c2 = 0; private Object lock1 = new Object(); private Object lock2 = new Object(); public void inc1() { synchronized(lock1) { c1++; } } public void inc2() { synchronized(lock2) { c2++; } } } ``` -------------------------------- ### Using wrapt.lazy_import for Module Loading Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/wrappers.md Demonstrates how to use `wrapt.lazy_import()` to defer module loading until its attributes are accessed. This example also shows the use of `@wrapt.when_imported` for side effects upon module import. ```python import wrapt @wrapt.when_imported("graphlib") def module_imported(module): print(f"{module.__name__} imported") # Replaces "import graphlib". graphlib = wrapt.lazy_import("graphlib") print("waiting for import") print(graphlib.TopologicalSorter) ``` -------------------------------- ### Decorating Class Methods Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/04-implementing-a-universal-decorator.md Illustrates applying the universal decorator to instance methods, class methods, and static methods within a class. This setup is used to observe how the decorator behaves with each method type. ```python class Class: @my_function_wrapper def function_im(self, a, b): pass @my_function_wrapper @classmethod def function_cm(self, a, b): pass @my_function_wrapper @staticmethod def function_sm(a, b): pass ``` -------------------------------- ### Demonstrate NotImplementedError with dill Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/issues.md This example shows how attempting to serialize a function decorated with @wrapt.decorator using dill results in a NotImplementedError because the underlying FunctionWrapper inherits the base proxy's __reduce__ method. ```python import dill import wrapt @wrapt.decorator def trace(wrapped, instance, args, kwargs): return wrapped(*args, **kwargs) @trace def add(a, b): return a + b dill.dumps(add, byref=True) # NotImplementedError: object proxy must define __reduce__() ``` -------------------------------- ### Decorator Application on Class and Static Methods Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/04-implementing-a-universal-decorator.md Illustrates the syntax for applying the decorator to class methods and static methods within a class. Note that this setup may cause issues with the current universal decorator implementation. ```python class Class: @my_function_wrapper @classmethod def function_cm(self, a, b): pass @my_function_wrapper @staticmethod def function_sm(a, b): pass ``` -------------------------------- ### Create a Callback Wrapper Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/wrappers.md Demonstrates creating a wrapper instance using `wrapt.function_wrapper` and then applying it to a callback function. This pattern is often used when dynamically generating wrappers. ```python @function_wrapper def wrapper(wrapped, instance, args, kwargs): return wrapped(*args, **kwargs) callback = wrapper(fetch_callback()) ``` -------------------------------- ### Example of Valid and Invalid Type Checked Calls Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/examples.md Shows a successful call to a type-checked function and an example that raises a TypeError due to a mismatched argument type. ```default >>> add(1, 2) 3 >>> add(1, "2") Traceback (most recent call last): ... TypeError: Argument 'y' must be int, got str ``` -------------------------------- ### Basic Function Decorator Example Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/typing.md A simple example of a function decorator using @wrapt.decorator without type hints. The type checker cannot infer types in this case. ```python @wrapt.decorator def pass_through(wrapped, instance, args, kwargs): return wrapped(*args, **kwargs) @pass_through def add(a, b): return a + b result = add(2, 3) ``` -------------------------------- ### Site Module Initialization Function Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/14-automatic-patching-of-python-applications.md This snippet shows the main() function from Python's site module, illustrating the sequence of operations during interpreter initialization, including site package loading and customization execution. ```python def main(): global ENABLE_USER_SITE abs__file__() known_paths = removeduppaths() if ENABLE_USER_SITE is None: ENABLE_USER_SITE = check_enableusersite() known_paths = addusersitepackages(known_paths) known_paths = addsitepackages(known_paths) if sys.platform == 'os2emx': setBEGINLIBPATH() setquit() setcopyright() sethelper() aliasmbcs() setencoding() execsitecustomize() if ENABLE_USER_SITE: execusercustomize() # Remove sys.setdefaultencoding() so that users cannot change the # encoding after initialization. The test for presence is needed when # this module is run as a script, because this code is executed twice. if hasattr(sys, "setdefaultencoding"): del sys.setdefaultencoding ``` -------------------------------- ### Discovering Patches via Entry Points Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/monkey.md Use `discover_post_import_hooks` to load entry points from a specified group, registering them as post import hooks. This allows patches to be packaged as plugins. ```python wrapt.discover_post_import_hooks("my_app.patches") ``` -------------------------------- ### Universal Wrapper Function Example Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/wrappers.md This example shows a universal wrapper function that can handle decorators applied to classes, functions, static methods, class methods, and instance methods. It uses inspect to determine the type of the wrapped object and its binding. ```python import inspect def wrapper(wrapped, instance, args, kwargs): if instance is None: if inspect.isclass(wrapped): # Decorator was applied to a class. return wrapped(*args, **kwargs) else: # Decorator was applied to a function or staticmethod. return wrapped(*args, **kwargs) else: if inspect.isclass(instance): # Decorator was applied to a classmethod. return wrapped(*args, **kwargs) else: # Decorator was applied to an instancemethod. return wrapped(*args, **kwargs) ``` -------------------------------- ### Run Tests with Tox using Just Source: https://github.com/grahamdumpleton/wrapt/blob/develop/TESTING.md Executes tests using the traditional tox configuration. ```bash just test-tox ``` -------------------------------- ### Decorator with Custom Wrapper Function Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/05-decorators-which-accept-arguments.md Example of defining a custom wrapper function for a decorator. ```python @decorator def my_function_wrapper(wrapped, instance, args, kwargs): print('INSTANCE', instance) print('ARGS', args) print('KWARGS', kwargs) return wrapped(*args, **kwargs) @my_function_wrapper def function(a, b): pass ``` -------------------------------- ### Type Checking Error Example Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/typing.md Illustrates how a type checker flags an error when an incompatible type is assigned to the result of a decorated function with type hints. ```python result: str = add("hello", "world") # Error: incompatible types ``` -------------------------------- ### Python Console Output: Initial Method Calls Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/04-implementing-a-universal-decorator.md Demonstrates the output of various method calls (instance, class, static) before decorator adjustments. ```python >>> c.function_im(1,2) INSTANCE <__main__.Class object at 0x101f973d0> ARGS (1, 2) >>> Class.function_im(c, 1, 2) INSTANCE <__main__.Class object at 0x101f973d0> ARGS (1, 2) >>> c.function_cm(1,2) INSTANCE <__main__.Class object at 0x101f973d0> ARGS (1, 2) >>> Class.function_cm(1, 2) INSTANCE None ARGS (1, 2) >>> c.function_sm(1,2) INSTANCE <__main__.Class object at 0x101f973d0> ARGS (1, 2) >>> Class.function_sm(1, 2) INSTANCE None ARGS (1, 2) ``` -------------------------------- ### Basic ObjectProxy Usage Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/wrappers.md Demonstrates wrapping a dictionary with ObjectProxy and performing operations. Operations on the proxy are reflected in the original dictionary. It also shows that isinstance(proxy, dict) evaluates to True. ```python >>> table = {} >>> proxy = wrapt.ObjectProxy(table) >>> proxy['key-1'] = 'value-1' >>> proxy['key-2'] = 'value-2' >>> proxy.keys() ['key-2', 'key-1'] >>> table.keys() ['key-2', 'key-1'] >>> isinstance(proxy, dict) True >>> dir(proxy) ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] ``` -------------------------------- ### Apply Configurable CallTracker Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/examples.md Demonstrates both styles of applying the configurable CallTracker: directly as a decorator and with arguments to pre-configure its state. ```python @CallTracker.track def add(x, y): return x + y @CallTracker.track(call_count=10) def add_starting_at_ten(x, y): return x + y ``` -------------------------------- ### Use ValueChecker for Positive Arguments Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/examples.md This example demonstrates using the value_checker decorator to ensure that arguments 'x' and 'y' are positive. If a negative value is provided, a ValueError is raised. ```default def is_positive(value): return value > 0 @value_checker(x=is_positive, y=is_positive) def multiply(x, y): return x * y >>> multiply(2, 3) 6 >>> multiply(-1, 3) Traceback (most recent call last): ... ValueError: Argument 'x' with value -1 failed constraint is_positive ``` -------------------------------- ### Time Function Call Without Decorator Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/09-performance-overhead-of-using-decorators.md Use this as a baseline to measure the performance impact of decorators. No specific setup or imports are required beyond standard Python. ```python import timeit def my_function(): pass print(timeit.timeit(my_function, number=1000000)) ``` -------------------------------- ### Running Python Application with Monkey Patches Enabled Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/13-ordering-issues-when-monkey-patching-in-python.md This shell command demonstrates how to run a Python application (entrypoints.py) with specific monkey patches enabled by setting the WRAPT_PATCHES environment variable. This is useful for testing or applying patches during development. ```shell $ WRAPT_PATCHES=wrapt_patches.tempfile_debugging python -i entrypoints.py ``` -------------------------------- ### Wrapper for execusercustomize Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/14-automatic-patching-of-python-applications.md This Python code defines a wrapper function for 'execusercustomize'. It is intended to be used to defer actions until after user site customization has completed. ```python def _execusercustomize_wrapper(wrapped): ``` -------------------------------- ### Temporary Function Wrapper for Tests Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/monkey.md Use `@wrapt.transient_function_wrapper` to apply a patch only for the duration of a function call. The patch is installed before each call and removed afterwards, even if the call raises an exception. ```python import wrapt import logging @wrapt.transient_function_wrapper("logging", "Logger.info") def capture_info(wrapped, instance, args, kwargs): calls.append((args, kwargs)) return wrapped(*args, **kwargs) calls = [] @capture_info def run(): logging.getLogger().info("hello") run() ``` -------------------------------- ### Run All Tests with Just Source: https://github.com/grahamdumpleton/wrapt/blob/develop/TESTING.md Executes the complete test suite across all supported Python versions, testing scenarios with and without C extensions. ```bash just test ``` -------------------------------- ### Intercepting Attribute Access with ObjectProxy Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/12-using-wrapt-to-support-testing-of-software.md Extends the ObjectProxy example to demonstrate how to intercept attribute access. By defining a property on the proxy, you can control how attributes of the wrapped object are accessed during testing. ```python from wrapt import transient_function_wrapper, ObjectProxy class StorageClass: def __init__(self): self.name = 'name' storage = StorageClass() class ProductionClass: def method(self, a, b, c, key): return storage class StorageClassProxy(ObjectProxy): @property def name(self): return self.__wrapped__.name @transient_function_wrapper(__name__, 'ProductionClass.method') def apply_ProductionClass_method_wrapper(wrapped, instance, args, kwargs): storage = wrapped(*args, **kwargs) return StorageClassProxy(storage) @apply_ProductionClass_method_wrapper def test_method(): real = ProductionClass() data = real.method(3, 4, 5, key='value') assert data.name == 'name' ``` -------------------------------- ### Create Mypy Test File Source: https://github.com/grahamdumpleton/wrapt/blob/develop/TESTING.md Use this command to create a new Python file for mypy tests. Ensure the file follows the `mypy_your_test_name.py` naming convention. ```bash # Create tests/mypy/mypy_your_test_name.py ``` -------------------------------- ### Basic Function Wrapper for Testing Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/12-using-wrapt-to-support-testing-of-software.md A simple function wrapper using wrapt to intercept and potentially modify the behavior of a function call during testing. This is a foundational example for more complex wrapping scenarios. ```python from wrapt import function_wrapper @function_wrapper def run_method_wrapper(wrapped, instance, args, kwargs): return wrapped(*args, **kwargs) ``` -------------------------------- ### Run Tests with Pip and Pytest using Just Source: https://github.com/grahamdumpleton/wrapt/blob/develop/TESTING.md Runs tests using pip-installed pytest within the main virtual environment for backward compatibility. ```bash just test-pip ``` -------------------------------- ### Java Synchronized Statement Example Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/07-the-missing-synchronized-decorator.md Illustrates using synchronized statements in Java to control access to a block of code. This approach requires explicitly specifying the object that provides the intrinsic lock. ```java public void addName(String name) { synchronized(this) { lastName = name; nameCount++; } nameList.add(name); } ``` -------------------------------- ### Decorating a Class with a Universal Wrapper Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/04-implementing-a-universal-decorator.md Demonstrates applying a function wrapper decorator to a class. The output shows the initial state before distinguishing between different wrapped types. ```python @my_function_wrapper class Class: pass >>> c = Class() INSTANCE None ARGS () ``` -------------------------------- ### Wrapping Instance Attributes with wrapt.wrap_object_attribute Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/monkey.md Use wrapt.wrap_object_attribute to install a descriptor on a class for patching instance attributes. This is suitable for attributes stored in `self.__dict__` and should not be used on attributes already implemented by data descriptors. ```python import wrapt class LoggedValue(wrapt.ObjectProxy): def __repr__(self): return f"LoggedValue({self.__wrapped__!r})" class Widget: def __init__(self, name): self.name = name wrapt.wrap_object_attribute(__name__, "Widget.name", LoggedValue) >>> Widget("spinner").name LoggedValue('spinner') ``` -------------------------------- ### Deferred Adapter Creation with wrapt.adapter_factory Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/decorators.md Use `wrapt.adapter_factory` to defer the creation of the adapter until the decorator is applied. This is a convenience that avoids the need for explicit closures when generating signatures on demand. ```python def argspec_factory(wrapped): argspec = inspect.getfullargspec(wrapped) args = argspec.args[1:] defaults = argspec.defaults and argspec.defaults[-len(argspec.args):] return inspect.ArgSpec(args, argspec.varargs, argspec.keywords, defaults) @wrapt.decorator(adapter=wrapt.adapter_factory(argspec_factory)) def _session(wrapped, instance, args, kwargs): with transaction() as session: return wrapped(session, *args, **kwargs) ``` -------------------------------- ### ObjectProxy __qualname__ Snapshot vs Live-Read Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/issues.md Demonstrates the divergence in __qualname__ handling between pure-Python and C extension ObjectProxy implementations when the wrapped object's __qualname__ is mutated after proxy creation. The pure-Python version captures a snapshot, while the C extension performs a live-read. ```python import wrapt def foo(): pass proxy = wrapt.ObjectProxy(foo) foo.__qualname__ = "Changed" # Pure-Python: proxy.__qualname__ returns the original value (snapshot) # C extension: proxy.__qualname__ returns "Changed" (live-read) ``` -------------------------------- ### Calling Class Methods and Static Methods Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/04-implementing-a-universal-decorator.md Demonstrates the output when calling class methods and static methods via the class. This is used to illustrate differences in how methods are bound. ```python >>> Class.function_cm(1, 2) INSTANCE 1 ARGS (2,) >>> Class.function_sm(1, 2) INSTANCE 1 ARGS (2,) ``` -------------------------------- ### Transient Wrapper for Class Method Modification Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/12-using-wrapt-to-support-testing-of-software.md Applies a transient wrapper to a class method to modify its behavior specifically for a test. This example shows how to intercept the return value of a method and apply further wrapping to it. ```python from wrapt import transient_function_wrapper @transient_function_wrapper(__name__, 'ProductionClass.method') def apply_ProductionClass_method_wrapper(wrapped, instance, args, kwargs): storage = wrapped(*args, **kwargs) storage.run = run_method_wrapper(storage.run) return storage ``` -------------------------------- ### Using a Dummy Function as an Adapter Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/decorators.md Provide a dummy function prototype to the `adapter` argument when the decorator changes the wrapped function's signature. This ensures `inspect.getargspec` returns the desired signature. The `help()` output will reflect the adapter's signature. ```python def _my_adapter_prototype(arg1, arg2): pass @wrapt.decorator(adapter=_my_adapter_prototype) def my_adapter(wrapped, instance, args, kwargs): """Adapter documentation.""" def _execute(arg1, arg2, *_args, **_kwargs): # We actually multiply the first two arguments together # and pass that in as a single argument. The prototype # exposed by the decorator is thus different to that of # the wrapped function. return wrapped(arg1*arg2, *_args, **_kwargs) return _execute(*args, **kwargs) @my_adapter def function(arg): """Function documentation.""" pass >>> help(function) Help on function function in module __main__: function(arg1, arg2) Function documentation. ``` -------------------------------- ### Timeit Benchmark: Instance Method with C Extension Decorator Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/10-performance-overhead-when-applying-decorators-to-methods.md Measures the performance of an instance method decorated using a C extension implementation for the object proxy and function wrapper. This demonstrates the performance improvement over a pure Python implementation. ```sh 1000000 loops, best of 3: 0.836 usec per loop ``` -------------------------------- ### Apply Transient Wrapper Directly to Test Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/examples.md Apply @wrapt.transient_function_wrapper directly to a test function to make the patch active for the entire test's execution. This simplifies setup and teardown for test-specific patches. ```python @wrapt.transient_function_wrapper("tempfile", "mkdtemp") def stub_mkdtemp(wrapped, instance, args, kwargs): return "/fake/path" @stub_mkdtemp def test_build_workspace_returns_path(): assert build_workspace() == "/fake/path" ``` -------------------------------- ### Wrapper for Sitecustomize Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/14-automatic-patching-of-python-applications.md Defines a wrapper function for sitecustomize that ensures bootstrap functions are registered. This is used when support for usersitecustomize is enabled. ```python def _execusercustomize(*args, **kwargs): try: return wrapped(*args, **kwargs) finally: _register_bootstrap_functions() return _execusercustomize ``` -------------------------------- ### Decorator with Arguments using wrapt Source: https://github.com/grahamdumpleton/wrapt/blob/develop/README.md Shows how to create a decorator that accepts arguments. The arguments are passed to the outer function and then used within the wrapper. ```python import wrapt def with_arguments(myarg1, myarg2): @wrapt.decorator def wrapper(wrapped, instance, args, kwargs): print(f"Arguments: {myarg1}, {myarg2}") return wrapped(*args, **kwargs) return wrapper @with_arguments(1, 2) def function(): pass ``` -------------------------------- ### Illustrating Pytest Hook Bypass with Wrapt Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/issues.md This example demonstrates the issue where a @wrapt.decorator applied to a @classmethod setup_class hook is bypassed by pytest. When run, the test fails because the decorator's modification to kwargs is not applied. ```python import wrapt @wrapt.decorator def pass_through(wrapped, instance, args, kwargs): return wrapped(*args, foo=1, **kwargs) class TestMyClass: @pass_through @classmethod def setup_class(cls, **kwargs): cls.kwargs = kwargs def test_something(self): assert self.kwargs == {'foo': 1} ``` -------------------------------- ### Stack TypeChecker and ValueChecker Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/examples.md This example shows how to stack TypeChecker and ValueChecker decorators. TypeChecker should be the outer decorator to ensure type validation occurs before value validation, preventing unexpected errors from incorrect types. ```default @type_checker @value_checker(x=is_positive, y=is_positive) def scale(x: int, y: int) -> int: return x * y >>> scale(2, 3) 6 >>> scale(-1, 3) Traceback (most recent call last): ... ValueError: Argument 'x' with value -1 failed constraint is_positive >>> scale("a", 3) Traceback (most recent call last): ... TypeError: Argument 'x' must be int, got str ``` -------------------------------- ### Pickle and Unpickle StatsProxy Instance Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/examples.md Demonstrates pickling and unpickling a StatsProxy instance using the standard pickle module. The restored proxy retains its state. ```default >>> original = StatsProxy({"count": 3, "sum": 6}, label="demo") >>> data = pickle.dumps(original) >>> restored = pickle.loads(data) >>> restored.label 'demo' >>> dict(restored) {'count': 3, 'sum': 6} ``` -------------------------------- ### Mypy Type Checking Example Source: https://github.com/grahamdumpleton/wrapt/blob/develop/TESTING.md Demonstrates type checking for FunctionWrapper using mypy. It includes type revelation and checks for valid and invalid usage, expecting mypy to report errors for invalid cases. ```python from wrapt import FunctionWrapper def f(a: bool, b: str) -> int: return 1 def standard_wrapper(wrapped, instance, *args, **kwargs): pass f1 = FunctionWrapper(f, standard_wrapper) reveal_type(f1) # Should reveal the original function's type result1a: int = f1(True, "test") # Valid usage result1b: str = f1(1, None) # Invalid usage - should error ``` -------------------------------- ### Class Method Binding Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/02-the-interaction-between-decorators-and-descriptors.md Illustrates how accessing a class method via an instance results in a bound method, showcasing the descriptor protocol in action. ```python >>> class Object: ... def f(self): pass >>> obj = Object() >>> obj.f > ``` -------------------------------- ### Interactive Python Session After Applying Patches Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/13-ordering-issues-when-monkey-patching-in-python.md This output shows an interactive Python session after the application has started with monkey patches enabled. It indicates that a specific patch (wrapt_patches.tempfile_debugging) was discovered and applied, affecting the 'tempfile' module. ```pycon discover wrapt_patches.tempfile_debugging >>> import tempfile patching tempfile ``` -------------------------------- ### Wrapper for execsitecustomize Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/14-automatic-patching-of-python-applications.md This Python code defines a wrapper function for 'execsitecustomize'. It ensures that the original function is called and then conditionally registers bootstrap functions if user site customization is not enabled. ```python def _execsitecustomize_wrapper(wrapped): def _execsitecustomize(*args, **kwargs): try: return wrapped(*args, **kwargs) finally: if not site.ENABLE_USER_SITE: _register_bootstrap_functions() return _execsitecustomize ``` -------------------------------- ### Decorator for Class Method Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/03-implementing-a-factory-for-creating-decorators.md This example shows how a decorator, when applied to a class method, can lead to unexpected behavior. The instance argument passed to the decorator wrapper is None, and the actual first argument becomes the instance, causing issues. ```python class Class: @my_function_wrapper @classmethod def function_cm(cls, a, b): pass ``` -------------------------------- ### Synchronized Decorator Usage Examples Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/07-the-missing-synchronized-decorator.md Demonstrates the application of the @synchronized decorator to different types of functions and methods: a standalone function, an instance method, and a class method. This shows how the decorator can be used to ensure thread safety in various contexts. ```python @synchronized def function(): pass class Object: @synchronized def method_im(self): pass @synchronized @classmethod def method_cm(cls): pass ``` -------------------------------- ### Testing with Transient Wrapper and Function Wrapper Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/12-using-wrapt-to-support-testing-of-software.md Demonstrates a test method that utilizes a transient wrapper to modify a class method's return value, which is then further wrapped by a function wrapper. This setup allows for isolated testing of specific behaviors. ```python class StorageClass: def run(self): pass storage = StorageClass() class ProductionClass: def method(self, a, b, c, key): return storage @function_wrapper def run_method_wrapper(wrapped, instance, args, kwargs): return wrapped(*args, **kwargs) @transient_function_wrapper(__name__, 'ProductionClass.method') def apply_ProductionClass_method_wrapper(wrapped, instance, args, kwargs): storage = wrapped(*args, **kwargs) storage.run = run_method_wrapper(storage.run) return storage @apply_ProductionClass_method_wrapper def test_method(): real = ProductionClass() data = real.method(3, 4, 5, key='value') result = data.run() ``` -------------------------------- ### Testing Decorator on a Normal Function Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/04-implementing-a-universal-decorator.md Demonstrates applying the custom decorator to a simple function and shows the output when called, illustrating the 'instance' as None and arguments passed. ```python @my_function_wrapper def function(a, b): pass ``` ```python >>> function(1, 2) INSTANCE None ARGS (1, 2) ``` -------------------------------- ### Trace Output of Decorated Method Call Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/10-performance-overhead-when-applying-decorators-to-methods.md This trace output illustrates the sequence of method calls, including `__get__` and `__call__`, when a decorated instance method is invoked. It highlights the internal workings of the decorator and wrapper. ```text ('__get__', 'call') # function_wrapper ('__init__', 'call') # bound_function_wrapper ('__init__', 'call') # object_proxy ('__init__', 'return') ('__init__', 'return') ('__get__', 'return') ('__call__', 'call') # bound_function_wrapper ('my_function_wrapper', 'call') ('method', 'call') ('method', 'return') ('my_function_wrapper', 'return') ('__call__', 'return') ``` -------------------------------- ### Discover Post Import Hooks using Environment Variable Source: https://github.com/grahamdumpleton/wrapt/blob/develop/blog/14-automatic-patching-of-python-applications.md This code snippet uses an environment variable to specify packages for which post-import hooks should be discovered and applied. It requires the 'wrapt' library. ```python import os from wrapt import discover_post_import_hooks patches = os.environ.get('WRAPT_PATCHES') if patches: for name in patches.split(','): name = name.strip() if name: print 'discover', name discover_post_import_hooks(name) ``` -------------------------------- ### Patch a Function or Method using @wrapt.patch_function_wrapper Decorator Source: https://github.com/grahamdumpleton/wrapt/blob/develop/docs/monkey.md The `@wrapt.patch_function_wrapper` decorator provides a more readable way to apply patches at module scope. Importing the module containing the decorated wrapper automatically installs the patch. The target and attribute are specified as decorator arguments. ```python import wrapt @wrapt.patch_function_wrapper("logging", "Logger.info") def notify(wrapped, instance, args, kwargs): print(f"calling {wrapped.__name__}") return wrapped(*args, **kwargs) ```