converting a string to a function parameter

Scott David Daniels Scott.Daniels at Acm.Org
Fri Mar 13 12:20:23 EDT 2009


koranthala wrote:
> Hi,
>     Is it possible to convert a string to a function parameter?
> Ex:
> str = 'True, type=rect, sizes=[3, 4]'
> and I should be able to use it as:
> test(convert(str)) and the behaviour should be same as calling test
> with those values :
> i.e. test(True, type=rect, sizes=[3, 4])
> 
> I tried eval, but it did not work. And any other mechanism I think
> turns out to be creating a full fledged python parser.

This might work [again be avoid eval if possible].
You _might want to do something like:

     def _args(*_nargs, **_kwargs):
         '''Collect call parameters from a call'''
         return _nargs, _kwargs
     ...
     nargs, kwargs = eval('_args(%s)' % arglist
     ...
     test(*nargs, **kwargs)

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list