1

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.

8
  • 1
    What would be the advantage of your approach over the normal inheritance? Commented Jan 13, 2020 at 19:33
  • In this case, there is no advantage. But this is just a simple example for illustrating the problem. I will use it in other context that I can't use inheritance since multi-level composition exists. Commented Jan 13, 2020 at 19:38
  • That does not sound convincing. Especially not when your class returned by the decorator uses inheritance. Commented Jan 13, 2020 at 19:42
  • Does this answer your question? functools.wraps equivalent for class decorator Commented Jan 13, 2020 at 19:45
  • 1
    @inherit_from(HelperClass) is a really strange decorater, it appears to do nothing that simply class Foo(HelperClass) could do, with no discernible benefit. I'm not sure what "multi-level composition" is, nor how it would prevent regular inheritance, but anyway, take a look at stackoverflow.com/a/9541560/5014455 Commented Jan 13, 2020 at 19:51

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.