命令行参数默认为另一个模块中定义的函数

时间:2013-06-07 17:06:35

标签: python environment-variables

假设我在一个包中有两个模块,one.pytwo.py,加上config.py。我想在命令行上执行one.py并将一个可用作默认值的参数传递给two.py中的函数...举例来说:

one.py:

import sys, getopt
import config

def main(argv):
    opts, _ = getopt.getopt(argv, 'hs', ['--strict='])
    for opt, _ in opts:
        if opt in ('-s', '--strict'):
            config.strict = True

    import two
    two.foo()        

if __name__ == '__main__':
    main(sys.argv[1:])

two.py

from config import strict
def foo(s=strict):
    if s:
        print "We're strict"
    else:
        print "We're relaxed around these parts"

config.py

strict = False

现在,这可行,但看起来很笨拙而且很糟糕,在我的main函数中间导入了...我假设有一种方法可以用装饰器做到这一点?或者其中一个懒惰的评估模块,但我不知所措!使用命令行参数作为另一个模块中定义的函数的默认值的最pythonic方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以通过覆盖函数的func_defaults(python3.x中的__defaults__)属性来更改默认值:

>>> def foo(a=True):
...     print a
... 
>>> foo()
True
>>> foo.func_defaults
(True,)
>>> foo.func_defaults = (False,)
>>> foo()
False
>>> 

我不知道我会说这是“pythonic”。就我而言,最狡猾的解决方案就是通过论证:

import two
def main(argv):
    opts, _ = getopt.getopt(argv, 'hs', ['--strict='])
    for opt, _ in opts:
        if opt in ('-s', '--strict'):
            config.strict = True

    two.foo(s=config.strict)