How to pass on argparse argument to function as kwargs?

2024/11/19 13:19:49

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.
Answer

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://en.xdnf.cn/q/26430.html

Related Q&A

How do you check whether a python method is bound or not?

Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that its bound to?

Most Pythonic way to declare an abstract class property

Assume youre writing an abstract class and one or more of its non-abstract class methods require the concrete class to have a specific class attribute; e.g., if instances of each concrete class can be …

PyQt on Android

Im working on PyQt now, and I have to create the application on Android, Ive seen the kivy library, but its too crude.Is there any way now to run an application on Android made on PyQt?

How to elementwise-multiply a scipy.sparse matrix by a broadcasted dense 1d array?

Suppose I have a 2d sparse array. In my real usecase both the number of rows and columns are much bigger (say 20000 and 50000) hence it cannot fit in memory when a dense representation is used:>>…

Do I have to do StringIO.close()?

Some code:import cStringIOdef f():buffer = cStringIO.StringIO()buffer.write(something)return buffer.getvalue()The documentation says:StringIO.close(): Free the memory buffer. Attempting to do furtherop…

Python: ulimit and nice for subprocess.call / subprocess.Popen?

I need to limit the amount of time and cpu taken by external command line apps I spawn from a python process using subprocess.call , mainly because sometimes the spawned process gets stuck and pins the…

array.shape() giving error tuple not callable

I have a 2D numpy array called results, which contains its own array of data, and I want to go into it and use each list: for r in results:print "r:"print ry_pred = np.array(r)print y_pred.sh…

Python unittest - Ran 0 tests in 0.000s

So I want to do this code Kata for practice. I want to implement the kata with tdd in separate files:The algorithm:# stringcalculator.py def Add(string):return 1and the tests:# stringcalculator.spec.…

How and where does py.test find fixtures

Where and how does py.test look for fixtures? I have the same code in 2 files in the same folder. When I delete conftest.py, cmdopt cannot be found running test_conf.py (also in same fo…

Python match a string with regex [duplicate]

This question already has answers here:What exactly do "u" and "r" string prefixes do, and what are raw string literals?(7 answers)What exactly is a "raw string regex" an…