Zope Proxy
zope.proxy is a Python library providing generic, transparent proxies. It allows you to wrap an object with a proxy that delegates most operations to the underlying object, while still allowing for custom behavior or interception. The current version is 7.1, with releases typically tied to Python version support and bug fixes.
Warnings
- breaking Major versions (5.x, 6.x, 7.x) of zope.proxy have progressively dropped support for older Python versions. Version 7.x (including 7.1) requires Python 3.10 or newer. Attempting to install or use it on older Python versions will fail.
- breaking Starting with version 5.0.0, the `zope.interface` dependency and its integration (like `zope.proxy.non_proxied` and automatic interface implementation) were removed. If your application relied on proxies automatically adapting to or implementing `zope.interface` definitions, this will break.
- gotcha While `zope.proxy` aims for transparency, `type(proxied_object)` will return `<class 'zope.proxy.Proxy'>`, not the type of the underlying proxied object. Code that strictly checks `type()` for identity will not see the original object's type.
Install
-
pip install zope-proxy
Imports
- Proxy
from zope.proxy import Proxy
- getProxiedObject
from zope.proxy import getProxiedObject
- isproxy
from zope.proxy import isproxy
Quickstart
from zope.proxy import Proxy, getProxiedObject
class MyObject:
def __init__(self, value):
self.value = value
def get_value(self):
return self.value
def __repr__(self):
return f"<MyObject value={self.value}>"
# Create an instance of MyObject
obj = MyObject(42)
print(f"Original object: {obj}")
# Wrap it with a Proxy
proxied_obj = Proxy(obj)
print(f"Proxied object: {proxied_obj}")
# Interact with the proxy - it behaves like the original object
print(f"Value via proxy: {proxied_obj.value}")
print(f"Method call via proxy: {proxied_obj.get_value()}")
# Check if it's a proxy
from zope.proxy import isproxy
print(f"Is proxied_obj a proxy? {isproxy(proxied_obj)}")
# Get the original object back from the proxy
original_from_proxy = getProxiedObject(proxied_obj)
print(f"Original object retrieved from proxy: {original_from_proxy}")
assert original_from_proxy is obj
# Demonstrate transparency for isinstance
print(f"isinstance(proxied_obj, MyObject)? {isinstance(proxied_obj, MyObject)}")