I am trying to create decorator for classes which takes parent_klass
as an argument and modifies original class by inheriting parent_klass
and returns it. See below implementation of this idea:
class HelperClass:
def helper_method(self):
print("helper method...")
def inherit_from(parent_klass):
def wrapper(cls):
class DecoratedClass(cls, parent_klass):
pass
return DecoratedClass
return wrapper
@inherit_from(HelperClass)
class Foo:
pass
f = Foo()
f.helper_method() # prints helper method...
print(Foo.__name__) # prints DecoratedClass
Above code works as I expected except the last print
line. My problem is that __name__
attribute of original class (Foo
) is not preserved and replaced by DecoratedClass
. How can I apply functools.wraps
functionality in this case? Is there any other way than using wraps
function?
EDIT: Actually, I want to use this decorate in Django project, in which __name__
attribute is important for database mapping. This decorator is intended to generate dynamic models that also contains custom managers. Simply inheriting the class without decorator does not solve my problem, since supplied argument ('parent_klass' in this case, but 'custom queryset' class in actual implemetation), is also used in bases class's (Foo
) methods.