Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass on argparse argument to function as kwargs?

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.
like image 719
Alex Avatar asked Mar 04 '13 16:03

Alex


People also ask

How do you pass things in Kwargs?

Kwargs allow you to pass keyword arguments to a function. They are used when you are not sure of the number of keyword arguments that will be passed in the function. Kwargs can be used for unpacking dictionary key, value pairs. This is done using the double asterisk notation ( ** ).

What does * args and * Kwargs mean?

**kwargs in Python *args enable us to pass the variable number of non-keyword arguments to functions, but we cannot use this to pass keyword arguments. Keyword arguments mean that they contain a key-value pair, like a Python dictionary. **kwargs allows us to pass any number of keyword arguments.

What is the difference between ARG and Kwargs?

The term Kwargs generally represents keyword arguments, suggesting that this format uses keyword-based Python dictionaries. Let's try an example. **kwargs stands for keyword arguments. The only difference from args is that it uses keywords and returns the values in the form of a dictionary.


1 Answers

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.

like image 77
Martijn Pieters Avatar answered Oct 09 '22 10:10

Martijn Pieters