Get attribute this way

Carl Banks pavlovevidence at gmail.com
Tue Nov 17 03:29:38 EST 2009


On Nov 16, 11:37 pm, King <animator... at gmail.com> wrote:
> "eval" can solve this problem right away but I am concerned about
> security issues. If not "eval" could you suggest something more
> efficient way. It won't be a big deal to change the format as
> application is still at development stage?


You are stuck parsing it yourself, then.  Apart from eval, there's not
a really handy way to do what you want.

Here's something that might help you get started; it is not by any
means a final solution.

First of all, for simplicity's sake, change the subscript notation to
attribute notation; that is, change "gradient.positions[0]" to
"gradient.positions.0".  Then you can find the object you're seeking
like this (untested):


obj = self
while '.' in attr:
    next,attr = attr.split('.',1)
    try:
        index = int(next)
    except TypeError:
        obj = getattr(obj,next)
    else:
        obj = obj[index]


Notice what's happening: we're splitting the string at the dot and
using getattr to descend further into the structure.  Also, if the
part of the string before the dot is an integer, we index instead.

Hopefully this example will help you understand what doing this
entails and what you have to do to get it work.


Carl Banks



More information about the Python-list mailing list