dynamic function parameters for **kwargs
Rotwang
sg552 at hotmail.co.uk
Fri Sep 20 12:08:13 EDT 2013
On 20/09/2013 16:51, bab mis wrote:
> 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).
More information about the Python-list
mailing list