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
变量的方式。
我不确定这是可能的,因为我需要在调用之前修改函数。有任何想法吗?
解决方案
对于不涉及此 hack 的潜在解决方案,您是否可以修改构建功能?如果是这样,您可以添加一个默认为 true 的标志参数。
def build(debug=False, overwrite_flag = True, args = []):
if overwrite_flag:
args = []
#rest of the function
但是,您要问的实际上是抑制函数中编写的指令之一,而不仅仅是添加新参数。可以使用装饰器管理新参数,但是我不知道是否会否决函数的指令。
推荐阅读
- excel - Excel VBA - 如何将给定条件的多个范围复制到新工作表
- python - 如何在python中用漂亮的汤从div中选择(id)或find_all(id)
- ffmpeg - ffmpeg 选择文件名中带有扩展名和空格的所有文件
- c# - 如何加快数据网格视图?
- python - 熊猫 pd.pivot_table 的更快更有效的替代方案?
- php - Symfony 5 Form 在会话中改变用户
- python - Tkinter - 用笔记本改变框架
- sqlite - 如何选择具有最大计数的所有行而不仅仅是第一行?
- java - 如何为 Java JCSG 对象设置颜色?[JavaFX]
- swift - 如何在 swift 5 中将自定义字体设置为 UIdate 选择器?