Command line argument as default to a function defined in another module
Question: Lets say I have two modules within a package, `one.py` and `two.py`, plus a
`config.py`. I want to execute `one.py` on the command line and pass an
argument that is available as the default to a function in `two.py`... By way
of example:

## 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
    

Now, this works but seems clunky and poor form what with the import in the
middle of my `main` function... I assume there is a way to do this with
decorators? Or one of the lazy evaluation modules, but I'm at a loss! What is
the most pythonic way to use a command line argument as a default to a
function defined in another module?


Answer: You can change the default by overwriting the function's `func_defaults`
(`__defaults__` in python3.x) attribute:

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

I don't know that I would say that this is "pythonic". As far as I'm
concerned, the most pythonic solution would be to just pass the argument:

    
    
    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)     
    

