使用上下文管理器重构 if-else 块 python?

Refactoring if-else blocks python with context managers?

我正在寻求重构一些重复的代码块,如下所示:

if condition == True:
    print("Doing some light work.")
else:
    print("Doing some work.")

    pass # this may be different for different purposes.
    
    print("Doing some other work.")

其中所有 print 语句表示块重复中常见的一些任务。

有很多这样的代码块,我试图找出重复的部分——即上面块中 pass 表示的语句以外的所有内容。

换句话说,我正在寻找类似于 contextmanager 的东西,它环绕 pass 语句,并且能够处理 if-else 语句。 Python有什么好的方法吗?

为不同的部分编写一个接受回调函数的函数。

def do_stuff(condition, callback):
    if condition:
        print("Doing some light work")
    else:
        print("Doing some work")
        callback()
        print("Doing some other work")

您也可以将其重写为您在定义回调函数之前使用的装饰器。

也许您应该更广泛地审视您的代码并应用 OOP:

的基本原则重新设计它
class BaseWorker:
    def do_work(self, condition):
        if condition:
            print("Doing some light work.")
        else:
            print("Doing some work.")
            self.specific_work()
            print("Doing some other work.")

    def specific_work(self):
        raise NotImplementedError


class WorkerA(BaseWorker):
    def specific_work(self):
        """worker A processing"""
        ...


class WorkerB(BaseWorker):
    def specific_work(self):
        """worker B processing"""
        ...