Skip to content

Instantly share code, notes, and snippets.

@csomh
Last active December 11, 2019 16:00
Show Gist options
  • Save csomh/add1896eb584f2265f53f3bbf1122b24 to your computer and use it in GitHub Desktop.
Save csomh/add1896eb584f2265f53f3bbf1122b24 to your computer and use it in GitHub Desktop.
Wrapping objects
import functools
class This:
def __init__(self):
self.other = 'wow'
def one(self):
print("one")
def two(self, other_param):
print(other_param)
def three(self):
print("three")
def retry(fn):
@functools.wraps(fn)
def inner(*args, **kwargs):
print("wrapped")
return fn(*args, **kwargs)
return inner
class That():
def __init__(self, wrapped):
self.wrapped = wrapped
def __getattr__(self, attr):
if callable(getattr(self.wrapped, attr, None)):
return retry(getattr(self.wrapped, attr))
else:
return getattr(self.wrapped, attr)
o = This()
t = That(o)
# calls This.one()
t.one()
# Passing params should work
t.two("apple")
# Accesing attributes of the wrapped class
print(t.other)
# calling the wrong attribute, has a relatively understandable traceback
t.nooop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment