Skip to content Skip to sidebar Skip to footer

How To Perform Automatic Type Conversion In Dynamic Argument Parsing

Most of my python codes I send a (sometimes long!) list of arguments to, which I know how to parse using getopt. All well and good so far... However I find it tiresome to type out

Solution 1:

You found a really neat way of solving this using argparse. You can take advantage of the Namespace object which can be passed to the parse_args() method to better handle the defaults. The idea is simple: instead of creating a new namespace object from the passed arguments and then augmenting it with the defaults, simply pre-create a namespace object from the defaults, and have argparse update it with the passed arguments.

This will reduce your code a bit:

defget_args(defaultpars):
    parser = argparse.ArgumentParser(description='Dynamic arguments')
    namespace = argparse.Namespace(**defaultpars)

    # add each key of the default dictionary as an argument expecting the same type for key, val in defaultpars.items():
        parser.add_argument('--'+key, type=type(val))
    
    parser.parse_args(namespace=namespace)

    returnvars(namespace)

Solution 2:

Thanks to @Wolfgang Kuehn for his pointer to argparse. That has the useful "type" option in add_argument, which solved my problem!

So here is my new solution written from scratch using argparse:

import argparse

defget_args(defaultpars):
    parser = argparse.ArgumentParser(description='Dynamic arguments')

    # add each key of the default dictionary as an argument expecting the same type for key,val in defaultpars.items():
        parser.add_argument('--'+key,type=type(val))
    newpars=vars(parser.parse_args())

    # Missing arguments=None need to be overwritten with default valuefor key,val in newpars.items():
        if val==None:
            newpars[key]=defaultpars[key]
    return(newpars)

if __name__ == "__main__":

    # default values:
    runpars={"a":1,"animal":"cat","f":3.3}
    runpars=get_args(runpars)
    print(runpars)

giving the correct types in the resulting dictionary:

getopts_test.py --a=4000 --animal="dog" 
{'a':4000, 'animal': 'dog', 'f': 3.3}

Post a Comment for "How To Perform Automatic Type Conversion In Dynamic Argument Parsing"