Python 相当于 Ruby 的投掷/接球



我跟随构建Git,但在Python而不是Ruby中实现它。我遇到了一个地方,Ruby实现依赖于Ruby的一个特性,而这个特性似乎没有一个python的等效。

我的理解是Ruby的Throw/Catch机制可以用作流控制的一种形式,允许您从方法返回而不实际返回。方法抛出一个值。然后,堆栈中的每个方法沿着该值传递,直到有一个方法可以捕获它。

可以替代:

  • 从方法返回值
  • 使用Raise/Rescue和Exceptions

我正在编写封装程序子命令的类。我希望能够运行命令,然后使用从超类继承的方法状态集退出。


class Base:
"""
This class is the base class that all subcommands inherit from.
"""
def exit(self, status = 0):
"""
Exit the calling method using the specified status.
"""
self.status = status
# TODO, throw status?

class Add(Base):
"""
This class implements the add command.
"""
def run(self):
"""
Run the add subcommand.
""""
# Example of where we should exit before the end of the method
# An exception is called by a dependency of the subcommand.
try:
raise Exception()
except:
self.exit(128) # This should cause the run() method to return

print("This line should not be reached")

我使用这种设计的原因是,这样我就可以使用依赖注入,并且更容易地使用自动测试框架(如Pytest)测试命令。而不是直接使用sys.exit(),我可以等到子命令返回,然后得到它的状态:

def test_add():
"""
This tests a certain execution path of the add subcommand.
"""
cmd = Add()
cmd.run()
assert cmd.status == 128

使用继承的被调用方exit()方法来强制调用方run()方法返回的python等效方法是什么?我猜我将不得不简单地从每个run()方法返回一个整数值,并摆脱exit(),但我想问,看看是否有人有任何其他的想法。

正如Albin Paul上面评论的那样,我应该使用return self.exit(128)

最新更新