Search code examples
pythondecoratorpython-decorators

Different decorators for the same class


I have a decorator that takes arguments and I want to apply it to a class individually passing different arguments each time to create a separate different version of the same class. For example:

@decorator(arg1)
class SomeClass:
   pass

@decorator(arg2)
class SomeOtherClassWithSameContent:
    pass  # repetition of code here

How can I avoid creating two classes with the same functionality and avoid code repetition? Thanks!


Solution

  • Decorators don't have to be applied literally using @:

    class Foo:
        pass
    
    
    SomeClass = decorator(arg1)(Foo)
    SomeOtherClassWithSameContent = decorator(arg2)(Foo)
    

    The @ syntax is basically just shorthand for the above anyway.