Search code examples
pythonpython-2.6optparseoptional-arguments

Passing optional arguments from optparse


I'm trying to figure out how to pass optional arguments from optparse. The problem I'm having is if an optparse option is not specified, it defaults to a None type, but if I pass the None type into a function, it yells at me instead of using the default (Which is understandable and valid).

conn = psycopg2.connect(database=options.db, hostname=options.hostname, port=options.port)

The question is, how do I use the function's defaults for optional arguments but still pass in user inputs if there is an input without having a huge number of if statements.


Solution

  • Define a function remove_none_values that filters a dictionary for none-valued arguments.

    def remove_none_values(d):
        return dict((k,v) for (k,v) in d.iteritems() if not v is None)
    
    kwargs = {
      'database': options.db,
      'hostname': options.hostname,
      ...
    }
    conn = psycopg2.connect(**remove_none_values(kwargs))
    

    Or, define a function wrapper that removes none values before passing the data on to the original function.

    def ignore_none_valued_kwargs(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            newkwargs = dict((k,v) for (k,v) in d.iteritems() if not v is None)
            return f(*args, **kwargs)
        return wrapper
    
    my_connect = ignore_none_valued_kwargs(psycopg2)
    conn = my_connect(database=options.db, hostname=options.hostname, port=options.port)