将参数传递给python中嵌套很深的函数



我想在bash脚本中运行python task.py——调试,现在我需要设置"调试";嵌套函数的参数如下:

main() : 
call A_1():
call A_2():
... 
call A_10():
if debug : 
print("error")

其中A_10是第10个嵌套函数,我只需要调试参数就可以在A_10中生效,如图所示。现在,强力方法是将参数debugA_1添加到A_10。还有其他更优雅的方式来实现我所需要的吗?

参数可用于读取sys.argv的脚本的任何部分,无论是否嵌套。

示例:

你好.py

import sys
def test():
print(sys.argv)
if "--debug" in sys.argv:
print("We're in debug mode.")
def main():
test()
if __name__ == "__main__":
main()

如果我运行python3 hello.py --debug,它会返回:

['hello.py', '--debug']
We're in debug mode.

只需将调试定义为main中的一个变量。这就足够了,它将在嵌套函数的范围内。

def main():
debug = True
def A_1():
def A_2():
def A_10():
if debug:
print("error")
A_10()
A_2()
A_1()
if __name__ == "__main__":
main()

或者

def main():
def A_1():
def A_2():
def A_10():
if debug:
print("error")
A_10()
A_2()
A_1()
if __name__ == "__main__":
debug = True
main()

在后者中,debug是一个全局变量。

根据您的偏好,我看到了两种可能的方法:

1.创建一个对象来分层管理参数

创建一个对象,例如顶层的Args


class Args:
"""store all your arguments here"""
foo = 42
class A_10:
debug = True
# from anywhere in the script at any nested position, call desired function with corresponding args
A_10(debug=Args.A_10.debug)

通过这样做,您可以简单地调用A_10(debug=Args.A10.debug)

Pro:

  • 不需要全局变量
  • 无需将Args传递给所有父函数
  • 简单
  • 类参数的自动补全支持

Con:

  • 脚本中变量args的硬编码

2.使用argparse子命令

使用argparse子命令可以一举两得(CLI args,分层组织的参数(,请参阅https://docs.python.org/3/library/argparse.html#sub-命令

Pro:

  • 解析CLI参数
  • 使用子命令拆分功能

Con:

  • 样板代码

最新更新