在调用函数之前,我可以先修补函数参数/变量吗?

2024-10-03 19:20:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个第三方软件包:

def build(debug=False):
    args = []
    if not (debug):
        args.append('--windowed')
    args.extend(['--icon', path('src/main/icons/Icon.ico')])
    # and much, much more

我想把这个功能变成:

def build(debug=False, args=[]):
    # remove the line: args = []
    # and retain the rest of the function

例如,我知道我可以做到以下几点:

def monkeypatched_build(debug=False, args=[]):
    # remove the line: args = []
    # and include all of the other code here

build = monkeypatched_build

但是,在我的例子中,build函数是复杂的,如果可能的话,我希望避免维护这个函数的一个单独版本,而只是改变修改args变量的方式。你知道吗

我不确定这是否可行,因为我需要在调用函数之前修改它。有什么想法吗?你知道吗


Tags: andofthe函数debugbuildfalseif
1条回答
网友
1楼 · 发布于 2024-10-03 19:20:47

对于一个不涉及此黑客攻击的潜在解决方案,是否允许您修改构建函数?如果是这样,您可以只添加一个默认值为true的flag参数。你知道吗

def build(debug=False, overwrite_flag = True, args = []):
    if overwrite_flag:
        args = []
    #rest of the function

但是,实际上,您所要求的是抑制函数中写入的指令之一,而不仅仅是添加新参数。新的参数可以用decorators来管理,但是我不知道如何推翻函数的指令。你知道吗

相关问题 更多 >