0

我有一个创建 Python 代码并运行它的应用程序。在此过程中,我想清除两个方法分配,因为它们在第二次运行中会产生错误:

push = Writer.Push  
...  
def appPush(self):
    push(self)
    dumpRow(self)
...  
Writer.Push=appPush

这是我必须修复的遗留代码。如果你多次运行它,Python 会宣布存在递归。
我一直在寻找一种清除环境的方法,但 'os.system('CLS')' 没有帮助。我怎样才能清理这些作业?
谢谢。

编辑:
它是遗留代码。我还不是很熟悉。我的应用程序创建的 Python 代码包含一般内容(如我在上面发布的部分)以及将用户工作流程转换为 Python 的过程。如果用户创建的流程最终调用了“appPush”,则应用程序必须在运行 1 次后重新启动。
我可以在上面的代码之后添加东西。我正在寻找一种从这些任务中清除解释器环境的方法。可能吗?

4

3 回答 3

2

OK, I see what your problem is.

This code:

push = Writer.Push  
def appPush(self):
    push(self)
    dumpRow(self)
Writer.Push=appPush

Would cause infinite recursion if push were ever changed to appPush. What you basically want there is a decorator, so if you could change that to:

def appPushCreator(func):
    def appPush(self):
        func(self)
        dumpRow(self)
    return appPush

Writer.Push = appPushCreator(Writer.Push)

This would keep the implied semantics of doing another dumpRow every time you used that bit of code.

I don't think you can fix your error by only adding code after the broken bit. You can't 'clear the environment' and get your original Writer.Push back.

于 2012-07-09T12:18:19.580 回答
1

像这样的东西应该工作:

real_push = None
if real_push is None:
    real_push = push
Writer.Push = real_push

在损坏的代码之前放入代码可能会更好:

real_push = None
if real_push is None:
    real_push = Writer.Push
Writer.Push = real_push

本质上,您正在尝试使代码具有幂等性,即多次运行它与运行一次具有相同的效果。

于 2012-07-09T12:15:02.137 回答
0

您不能只Writer.Push is appPush在 Python 2.x 中进行测试,因为Writer.Push它被包装在一个未绑定的方法中,但是您可以访问属性Writer.Push并且它们会传递给原始函数。此外,如果您使用一个属性,这意味着如果您没有原始的补丁函数来测试也没关系。这意味着这应该有效:

def appPush(self):
    push(self)
    dumpRow(self)
appPush.is_patch = True
...

if not hasattr(Writer.Push, 'is_patch'):
    push = Writer.Push
    Writer.Push=appPush

请注意,您希望将分配移动到push内部if以避免在代码第二次运行时覆盖它。

于 2012-07-09T12:56:27.273 回答