How to pass on argparse argument to function as kwargs?

我只是一个虾纸丫 提交于 2019-11-29 16:04:40

问题


I have a class defined as follows

class M(object):
    def __init__(self, **kwargs):
        ...do_something

and I have the result of argparse.parse_args(), for example:

> args = parse_args()
> print args
Namespace(value=5, message='test', message_type='email', extra="blah", param="whatever")

I want to pass on the values of this namespace (except message_type) to create an instance of the class M. I have tried

M(args)

but got an error

TypeError: __init__() takes exactly 1 argument (2 given)

which I do not understand. How can I

  1. remove the value message_type from the list in args
  2. pass on the values as if I would type M(value=5, message='test', extra="blah", param="whatever") directly.

回答1:


You need to pass in the result of vars(args) instead:

M(**vars(args))

The vars() function returns the namespace of the Namespace instance (its __dict__ attribute) as a dictionary.

Inside M.__init__(), simply ignore the message_type key.



来源:https://stackoverflow.com/questions/15206010/how-to-pass-on-argparse-argument-to-function-as-kwargs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!