dynamic function parameters for **kwargs


B

bab mis

Hi ,
I have a function as below:

def func(**kwargs):
...
...



====
args="a='b',c='d'"

i want to call func(args) so that my function call will take a var as an parameter.

it fails with an error "typeError: fun() takes exactly 0 arguments (1 given)"

.. Is there any other way to get the same.
 
Ad

Advertisements

Ad

Advertisements

R

Rotwang

Hi ,
I have a function as below:

def func(**kwargs):
...
...



====
args="a='b',c='d'"

i want to call func(args) so that my function call will take a var as an parameter.
it fails with an error "typeError: fun() takes exactly 0 arguments (1 given)"
. Is there any other way to get the same.

It fails because args is a string and func(args) is passing a single
string as a positional argument to func, rather than passing the keyword
arguments a and c. Not sure if I've understood your question, but

args = {'a': 'b', 'c': 'd'}
# or equivalently args = dict(a='b', c='d')
func(**args)

will work. If you need args to be a string like the one in your post
then you could try

eval('func(%s)' % args)

or

func(**eval('dict(%s)' % args))

but that's only something that should be done if you trust the user who
will decide what args is (since malicious code passed to eval() can do
pretty much anything).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top