I have a problem in Python for which I cannot find any clean solution ...
When calling some methods, I want to execute some code before and after the method is executed. To (among many others) automatically set and clear a variable context.
To achieve this, I declared the following metaclass:
class MyType(type):
def __new__(cls, name, bases, attrs):
attrs['test'] = cls.other_wrapper(attrs['test'])
attrs['test'] = cls.context_wrapper(attrs['test'])
return super(MyType, cls).__new__(cls, name, bases, attrs)
@classmethod
def context_wrapper(cls, operation):
def _manage_context(self, *args, **kwargs):
self.context = 'blabla'
returned = operation(self, *args, **kwargs)
self.context = None
return returned
return _manage_context
@classmethod
def other_wrapper(cls, operation):
def _wrapped(self, *args, **kwargs):
return operation(self, *args, **kwargs)
return _wrapped
It works like a charm:
class Parent(object):
__metaclass__ = MyType
def test(self):
print self.context
But as soon as I want to subclass Parent, problems arise when I call the parent method with super:
class Child(Parent):
def test(self):
print self.context
super(Child, self).test()
print self.context
I thought about saving the context before setting it to a new value, but this partially solves the problem ...
, (, ), , , *args **kwargs, Parent.test, self - Child, self , *args **kwargs (, ), :
@classmethod
def validation_wrapper(cls, operation):
def _wrapped(self, *args, **kwargs):
if not kwarg['some_arg'] > self.some_minimum:
raise ValueError('Validation failed')
return operation(self, *args, **kwargs)
return _wrapped
, , :
super(Child, self)
self, ""
... - , ? ?