Search code examples
pythonclasscommand-line-argumentskeyword-argument

Issue with command line arguments passed to function and returned as dictionary


class Cass(object):

    def __init__(self, **args):
        self.top_n = "endpoint1"
        self.time_series = "endpoint2"

    def get_args(**kwargs):
        print kwargs


def main(args):
    cass = Cass()
    cass.get_args()


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-r', '--regional', type=bool, default=False)
    parser.add_argument('-tn', '--top_n', type=bool, default=False)
    parser.add_argument('-tt', '--traffic_to', type=str, default=False)
    parser.add_argument('-tf', '--traffic_from', type=str, default=False)
    parser.add_argument('-s', '--start_time', type=int, default=False)
    parser.add_argument('-e', '--end_time', type=int, default=False)

    args = parser.parse_args()

    main(args)

When I run python cassa_revamp.py -r True -tn False -tt ca -tf ca -s 0 -e 10, I expect all of the arguments to be printed as a dictionary because I am using **kwargs. I am getting the following error:

Traceback (most recent call last):
  File "cassa_revamp.py", line 36, in <module>
    main(args)
  File "cassa_revamp.py", line 22, in main
    cassavania.get_args()
TypeError: get_args() takes exactly 0 arguments (1 given)

Solution

  • args is a Namespace object; get_args expects zero or more keyword arguments. You need to call get_args with

    cass.get_args(**vars(args))
    

    vars returns a dictionary of the attributes of its argument, and the ** syntax passes the dictionary as a sequence of keyword arguments instead of a single dict object.

    Also, get_args should be defined to take self as an argument in addition to the keyword arguments:

    def get_args(self, **kwargs):
        print kwargs