【问题标题】:Refactoring legacy synchronous Python code重构遗留的同步 Python 代码
【发布时间】:2013-10-31 22:34:44
【问题描述】:

我正在尝试重构一些类似于以下内容的 Python 代码:-

1) if condition1:
2)      lookupID = showSomeModalForm()
3)      result = dbLookUp(lookUpID)
     if result == 3:
        doSomething(result)
        value = showSomeModalForm2()
elif condition2:
     id = showSomeModalForm()
     doSomethingInDB(id)
     id = 0

目前,如您所见,有几个地方显示了模态表单 - 只要模态表单返回相关 if(嵌套 if)执行下的代码。因此,例如,只要第 2) 行返回第 3) 行,就会执行

我参与了一些工作,这意味着在某些情况下代码将是同步的,并像现在一样显示为模态形式,但在其他情况下它将是异步调用。

首先,我已将所有对 showModalForm* 的调用替换为指向一个名为 askForInput 的回调函数,如下所示。 askForInput 将在同步和异步情况下实现。

def refactor(self):
   4)  if condition1:
   5)     lookupID = askForInput()
   6)     result = dbLookUp(lookUpID)
   7)     if result == 3:
   8)        doSomething(result)
   9)        value = askForInput()
  10)        value += 2
   10)  elif condition2:
  11)     id = askForInput()
  12)     doSomethingInDB(id)
   13)    id = 0

如果代码是同步的,这可以正常工作,因为代码将执行第 1 行)假设条件 1 为真,它将执行第 2 行),一旦选择了某些内容,它将执行第 3 行)

由于这是遗留代码,这组 if(嵌套 if)编码了许多需要保留的逻辑,如果对 askForInput 的调用是异步的,我不确定如何重构它。例如,如果在第 5 行进行了异步调用),我希望它返回到重构方法并在第 6 行恢复执行)。如果异步调用在第 9 行)我希望代码在第 10 行恢复)并且 11)将转到 12)。

最初,我认为我可以使用回调并发送重构方法作为参数来做到这一点 - 但是这会从顶部开始执行,我想要做的几乎是暂停保持重构方法调用的状态askForInput 方法并将控制权返回到调用 askForInput 的正下方的重构方法。

阅读后我开始认为这可能与生成器和协同例程有关,但我不确定我是否找错了树。

任何关于如何重构它的帮助都将非常感激。

提前致谢。

【问题讨论】:

  • 您现在是否在使用任何特定的异步库(例如twisted/gevent)?
  • @Gerrat,代码现在是纯 Python。目前没有异步库。不过,使用一个不是问题。

标签: python asynchronous refactoring


【解决方案1】:

你也许可以使用线程——比如:

import threading, time

def askForInput(arg):
    arg.append("some ID")
    time.sleep(2)

def main():
    print("starting time: {}".format(time.asctime()))
    my_input = []  # want an argument we can mutate
    thr = threading.Thread(target=askForInput, args=(my_input,))
    thr.start()
    thr.join()  # will wait here
    lookupID = my_input[0]
    print("ending time: {}".format(time.asctime()))
    print("Result back from async call: {}".format(lookupID))

if __name__ == '__main__':  
    main()

结果:

starting time: Thu Oct 31 10:32:51 2013
ending time: Thu Oct 31 10:32:53 2013
Result back from async call: some ID

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    • 2010-11-18
    相关资源
    最近更新 更多