0

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

一个.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:])

二.py

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

配置文件

strict = False

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

4

1 回答 1

1

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

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

我不知道我会说这是“pythonic”。就我而言,最 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)     
于 2013-06-07T17:29:33.547 回答