In the over-simplifed example, say the original class, has many methods, all of them returns lower case strings. I want to wrap the Original class so that after calling its methods, follow by .upper()
class Original(object):
def get_assets(self):
# returns lower case string
class Wrap(Original):
# code that wraps Original's methods
So that calling Wrap().get_assets()
is equivalent to Original().get_assets().upper()
In a related but separate question, say, if Original's methods return json strings, how do I wrap it so that the result will be called with json.loads()
?
class Original(object):
def get_assets(self):
# returns json string
class Wrap(Original):
# code that wraps Original's methods
So that calling Wrap().get_assets()
is equivalent to json.loads(Original().get_assets())
Background
I came across this snipeit python library, but the every method requires me to specify url and token, so I have the following already to tackle the problem, but I haven't figured out how to solve the json string problem.
def snipeit_api_factory(kls):
class Cls(kls):
def __getattribute__(self, item):
attr = kls.__getattribute__(self, item)
if isinstance(attr, types.MethodType):
return partial(attr, settings.SNIPEIT_URL, settings.SNIPEIT_TOKEN)
return attr
return Cls()
ANSWER
Since this question is closed, I will post my answer here:
def snipeit_api_factory(kls):
"""
return an instance of the wrapped snipe-it API class to avoid specifying url and token for every method, and jsonify the result
"""
def jsonify(func):
def wrapper(*args, **kwargs):
return json.loads(func(*args, **kwargs))
return wrapper
class Cls(kls):
def __getattribute__(self, item):
attr = kls.__getattribute__(self, item)
if isinstance(attr, types.MethodType):
return jsonify(partial(attr, settings.SNIPEIT_URL, settings.SNIPEIT_TOKEN))
return attr
return Cls()