Last active
August 29, 2015 14:02
-
-
Save dutc/b93ee9aa5d5dc9008de1 to your computer and use it in GitHub Desktop.
dinky proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import update_wrapper | |
from collections import Callable | |
from logging import info, basicConfig, INFO | |
basicConfig(level=INFO) | |
def dec(name, obj, meth): | |
def wrapped(*args, **kwargs): | |
rv = meth(*args, **kwargs) | |
info('%r:0x%x:%s.%r(*%r, **%r) -> %r', obj, id(obj), name, meth, args, kwargs, rv) | |
return rv | |
update_wrapper(wrapped, meth, assigned=('__name__', '__doc__')) | |
return staticmethod(wrapped) | |
def proxy(name, value, ctor=lambda x:x, registry={}): | |
if type(value) not in registry: | |
class proxied(type(value)): | |
for attr in set(dir(value)) - {'__new__', '__init__', '__str__', '__repr__'}: | |
if isinstance(getattr(value, attr), Callable): | |
locals()[attr] = dec(name, value, getattr(value, attr)) | |
registry[type(value)] = proxied | |
return registry[type(value)](ctor(value)) # ): | |
if __name__ == '__main__': | |
a, b = 10, 20 | |
ap = proxy('a', a) | |
bp = proxy('b', b) | |
assert a + b == ap + bp | |
assert a - b == ap - bp | |
assert a * b == ap * bp | |
assert a / b == ap / bp | |
assert a % b == ap % bp | |
assert a // b == ap // bp | |
xs = [1,2,4,8] | |
xsp = proxy('xs', xs) | |
assert xs[0] == xsp[0] | |
#xsp[1] = xsp[1] * 10 # mutable or just value types? | |
#assert xs[1] == xsp[1] | |
assert list(xs) == list(xsp) | |
#assert tuple(xs) == tuple(xsp) | |
assert xs == xsp | |
assert len(xs) == len(xsp) | |
x = 10.2 | |
y = 10+3j | |
xp = proxy('x', x) | |
yp = proxy('y', y) | |
assert int(x) == int(xp) | |
assert float(int(x)) == float(int(xp)) | |
assert complex(int(x)) == complex(int(xp)) | |
assert y.conjugate() == yp.conjugate() | |
s = 'Silas is great!' | |
sp = proxy('s', s) | |
assert s * 3 == sp * 3 | |
assert s.replace('Silas', 'Meg') == sp.replace('Silas', 'Meg') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment