MCPcopy Create free account
hub / github.com/twisted/twisted / proxyForInterface

Function proxyForInterface

src/twisted/python/components.py:305–340  ·  view source on GitHub ↗

Create a class which proxies all method calls which adhere to an interface to another provider of that interface. This function is intended for creating specialized proxies. The typical way to use it is by subclassing the result:: class MySpecializedProxy(proxyForInterface(I

(iface, originalAttribute="original")

Source from the content-addressed store, hash-verified

303
304
305def proxyForInterface(iface, originalAttribute="original"):
306 """
307 Create a class which proxies all method calls which adhere to an interface
308 to another provider of that interface.
309
310 This function is intended for creating specialized proxies. The typical way
311 to use it is by subclassing the result::
312
313 class MySpecializedProxy(proxyForInterface(IFoo)):
314 def someInterfaceMethod(self, arg):
315 if arg == 3:
316 return 3
317 return self.original.someInterfaceMethod(arg)
318
319 @param iface: The Interface to which the resulting object will conform, and
320 which the wrapped object must provide.
321
322 @param originalAttribute: name of the attribute used to save the original
323 object in the resulting class. Default to C{original}.
324 @type originalAttribute: C{str}
325
326 @return: A class whose constructor takes the original object as its only
327 argument. Constructing the class creates the proxy.
328 """
329
330 def __init__(self, original):
331 setattr(self, originalAttribute, original)
332
333 contents: dict[str, object] = {"__init__": __init__}
334 for name in iface:
335 contents[name] = _ProxyDescriptor(name, originalAttribute)
336 proxy = type(f"(Proxy for {reflect.qual(iface)})", (object,), contents)
337 # mypy-zope declarations.classImplements only works when passing
338 # a concrete class type
339 declarations.classImplements(proxy, iface) # type: ignore[misc]
340 return proxy
341
342
343class _ProxiedClassMethod:

Callers 15

test_originalMethod · 0.90
test_proxyMethodMethod · 0.90
test_proxyAttributeMethod · 0.90
test_multipleMethodsMethod · 0.90
SpecializedProxyClass · 0.90
test_proxyNameMethod · 0.90
test_implementsMethod · 0.90
YayableWrapperClass · 0.90

Calls 1

_ProxyDescriptorClass · 0.85

Tested by 11

test_originalMethod · 0.72
test_proxyMethodMethod · 0.72
test_proxyAttributeMethod · 0.72
test_multipleMethodsMethod · 0.72
test_proxyNameMethod · 0.72
test_implementsMethod · 0.72