This module provides a way to build lazy proxies to any kind of Python entity.
To make a proxy to a module, instanciate the Proxy
class with a
string representing the import name of the module as parameter:
from object_proxy.lazy import LazyProxy path = LazyProxy('os.path')
Only when the proxy is used for the first time, the target module is imported.
To make a proxy to an object or a class, use the colon (:
) syntax:
environ = LazyProxy('os:environ')
When the proxy is used, it’s equivalent to:
from os import environ
The functions repr()
and id()
are not proxied to target.
The proxy can be context-dependent.
You must instanciate a context:
from object_proxy.lazy import LazyProxy from object_proxy.context import Context gevent_context = Context('gevent') eventlet_context = Context('eventlet') patch = LazyProxy('gevent.monkey:patch_all', context=gevent_context) eventlet_context.register(patch, 'eventlet:monkey_patch') # Run monkey patch from gevent Context.activate('gevent') # Or: Context.activate(gevent_context) # Or: gevent_context.activate() patch() # Run monkey patch from eventlet Context.activate('eventlet') # Identical to the previous patch()
You can know whether a proxy belongs to a context using id()
and
in
:
>>> id(patch) in gevent_context True
To discover which contexts a proxy belongs:
>>> Context.find_proxy(patch) [('gevent', 'gevent.monkey:patch_all'), ('eventlet', 'eventlet:monkey_patch')]
Contexts can get children:
>>> context = gevent_context.get_child('with_path') >>> context.name 'gevent.with_path' >>> path = LazyProxy('os.path', context=context) >>> context.activate() >>> path <module 'posixpath' from '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'> >>> patch <function patch_all at 0x109b1a848>
The function patch()
is inherited from super context.
ObjectProxy can be downloaded from GitHUB or installed using pip
:
pip install ObjectProxy
There’s a lot work to do. You can mail me with suggestions or see the project issues.
ObjectProxy is licensed under BSD New. See LICENSE
file.
Rodrigo Cacilhας <[email protected]>