converting a string to a function parameter

koranthala koranthala at gmail.com
Fri Mar 13 04:15:16 EDT 2009


On Mar 13, 1:01 pm, Chris Rebert <c... at rebertia.com> wrote:
> On Fri, Mar 13, 2009 at 12:52 AM, koranthala <koranth... at gmail.com> 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.
>
> > Is there any mechanism with which we can do this straight away?
>
> Firstly, don't use `str` as a variable name since it conflicts with
> the name of the builtin type.
>
> Now here's how to use eval() properly:
>
> [insert standard 'eval() is EVIL!' warning/lecture here]
>
> eval("test("+the_str+")")
>
> or
>
> eval(test.__name__+"("+the_str+")")
>
> Cheers,
> Chris
>
> --
> I have a blog:http://blog.rebertia.com

Thank you very much Chris.
I also thought about the first method a second after I posted this.
But I never thought about the second method.
I will heed the warning about the str part.

Thank you very much again, Chris.





More information about the Python-list mailing list