Converting string to argument

Tristan Seligmann mithrandi at mithrandi.za.net
Fri Jul 2 22:01:23 CEST 2004


On Fri, Jul 02, 2004 at 19:22:04 +0000, Tobiah wrote:
> What you really want is this:
> 
> class Foo:
>         x = "blah"
>         y = "blah some more"
> 
> 
> foo = Foo()
> 
> x_string = 'x'
> y_string = 'y'
> 
> print eval('foo.' + x_string)
> print eval('foo.' + y_string)

Using eval is overkill; something like:

    print getattr(foo, x_string)
    print getattr(foo, y_string)

should work just fine. In general, I'd suggest avoiding the use of eval
unless you really want something involving arbitrary code execution.
-- 
mithrandi, i Ainil en-Balandor, a faer Ambar
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 196 bytes
Desc: Digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20040702/9987b9fd/attachment.pgp>


More information about the Python-list mailing list