Skip to content

Instantly share code, notes, and snippets.

@fragmuffin
Created October 8, 2017 01:19
Show Gist options
  • Save fragmuffin/f61aaed05c6ad2b0c82eddcc5c1b3cae to your computer and use it in GitHub Desktop.
Save fragmuffin/f61aaed05c6ad2b0c82eddcc5c1b3cae to your computer and use it in GitHub Desktop.
dynamic proxy for wrapped instances
#!/usr/bin/env python
class BaseVector(object):
def cross(self, v):
print("base vector cross")
def dot(self, v):
print("base vector dot")
def proxy(wrapper, function_list):
def inner(cls):
for func_name in function_list:
def func(self, *largs, **kwargs):
print("proxy %s" % func_name)
print(" me: %r" % func)
wrapped_func = getattr(getattr(self, wrapper), func_name)
print(" name: %s" % wrapped_func.__name__)
return wrapped_func(*largs, **kwargs)
func.__name__ = func_name
setattr(cls, func_name, func)
print("func: %s" % func_name)
print(" id: %s" % id(func))
print(" func repr: %r" % getattr(cls, func_name))
return cls
return inner
@proxy('_wrapped', ('cross', 'dot'))
class Vector(object):
def __init__(self, obj):
self._wrapped = obj
v = Vector(BaseVector())
print("")
v.cross(None)
print("")
v.dot(None)
@fragmuffin
Copy link
Author

@dcowden
regarding https://github.com/dcowden/cadquery/blob/master/cadquery/freecad_impl/geom.py#L124
Although I'm sure it's possible... I think the code above is a strong argument to avoid auto wrapping.
it would be faaaar to difficult to debug, and customize

anyway, I just wanted to see if I could do it...
apparently the answer is "no"... I still have no idea why the above doesn't work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment