gpt4 book ai didi

python - 如何逐行停止执行函数?

转载 作者:行者123 更新时间:2023-11-28 17:39:44 25 4
gpt4 key购买 nike

我很难概括这个问题,所以我将描述我正在尝试做的事情:

我正在为某种产品编写测试解决方案,比方说微波炉。目的是在使用微波的同时测量各种资源。为此,我编写了一个名为 measure() 的上下文管理器。

我使用微波 API 编写了一个模拟微波炉基本用例的函数,并用一个完成所有测量的函数对其进行了装饰:

def test_function(fn):
def wrapper(*args, **kwargs):
with measure():
fn(*args, **kwargs)

return wrapper

@test_function
def prepare_food():
microwave = Microwave()
microwave.open_door()
microwave.insert_food()
microwave.close_door()
microwave.turn_on(seconds = 60)

prepare_food()

当然微波炉只是一个例子,我有很多这样的“微波炉”。

经过几天的测试和测量,我的团队决定他们要分别测量每个 Action ,这意味着我的测试函数现在看起来像这样:

def test_prepare_food():
microwave = Microwave()
actions = {
microwave.open_door : [],
microwave.insert_food : [],
microwave.close_door() : [],
microwave.turn_on : [60]
}
for (action, args) in actions.items():
with measure():
action(*args)

新的 test_prepare_food 的问题是现在对于每个 prepare_food 函数,我需要添加另一个 test_* 函数(我有很多)。

我正在寻找一种优雅的方式来保持我的 prepare_food 功能不变,并用另一个函数包装它,这样我仍然可以获得与 test_prepare_food 相同的功能>.

编辑:目标是提供一个不依赖于 prepare_food() 实现的解决方案,因此 prepare_food() 的更改不需要额外的更改。此外,该解决方案不应影响 prepare_food 未使用的方法。

换句话说,我希望能够“步入”prepare_food 并且能够在每一行前后执行代码。这类似于调试时所做的,但我找不到任何类似的东西。

有什么想法吗?

谢谢!

最佳答案

您可以使用 measure 方法装饰 Microwave 类的每个实例方法。这可以通过 Microwave 类上的类装饰器来完成。对于这个例子,我将通过一个方法修改 Microwave 类。完成这项工作的方法是 wrapwrap_method

import inspect

class measure(object):
def __enter__(self):
print "Enter measure."
def __exit__(self, *args):
print "Exit measure."

class Microwave(object):
def f(self, x):
print "f: %s" % x
def g(self, x):
print "g: %s" % x

def wrap_method(method):
def wrapper(*args, **kwargs):
with measure():
method(*args, **kwargs)
return wrapper

def wrap(cls):
for name, method in inspect.getmembers(cls, predicate=inspect.ismethod):
setattr(cls, name, wrap_method(method))

wrap(Microwave)
m = Microwave()
m.f(1)
m.g(2)

输出是:

Enter measure.
f: 1
Exit measure.
Enter measure.
g: 2
Exit measure.

关于python - 如何逐行停止执行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26202985/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com