Search code examples
pythonmethodsoverwriteprefect

Overwrite methods but keep decorator (python)


I got a Class and a Subclass and want to inherit a method with the decorator @task from framework prefect.io.

Code Sample:

Class

@task
def test1(self):
     pass

Subclass

def test2(self):
     print("succeed")

But now the method test2 doesn´t have the decorator @task anymore. I can´t declarate @task in the Subclass. Is it possbile that i can overwrite the method but keep @task ?


Solution

  • I usually recommend something like

    class Base:
        @task
        def test1(self):
            return self.test1_impl()
    
        def test1_impl(self):
            ...
    
    
    class Child:
        def test1_impl(self):
            ...
    

    Now Child's job isn't to override the decorated function, but rather the undecorated function used by the inherited decorated function.