How to Get the Object from String/Label?

Alex Martelli aleaxit at yahoo.com
Tue Sep 12 18:47:53 EDT 2000


"William Djaja Tjokroaminata" <billtj at y.glue.umd.edu> wrote in message
news:8plokq$41i$1 at hecate.umd.edu...
    [snip]
>     class MyObject:
>         def __init__ (self, myName):
>             self.myName = myName
>
>     myObject = MyObject ('xyz')
>
> Now, if I have the string 'myObject', how can I get the real object?

There are many ways.  A slight variation of yours, for example:

>     myString = 'myObject'
>     exec 'theObject = myString'
>
> This does not work, as theObject refers to the string myObject and not the
> object myObject.  In practice, myString gets the string/label not from a

That's because you'd need to do:

    exec 'theObject = ' + myString

to get the needed 'indirectness'.

    theObject = eval(myString)

has already been suggested, and should be faster.  Also,

    theObject = vars()[myString]

will work, and should likely be faster yet; if you know the string
is naming a variable in the global namespace (not within a given
function's local ns), a slight enhancement might be:

    theObject = globals()[myString]


Alex






More information about the Python-list mailing list