You are not logged in.

#1 2009-08-27 12:12:52

FeatherMonkey
Member
Registered: 2007-02-26
Posts: 313

[Solved]Python safe use of eval...

I have these snippets which is creating a list from a pickle file..

    def unpack(self):
        self.__init__(self.perms)
        globallist = []
        self.items = self.inFridgeFile
        for each in self.items.keys():
            self.__dict__[each] = self.items[each]
            globallist.append(each)
        return globallist

Now this works in I get a globallist, now to call the other bits as unpack.foo where foo is unknown(But in globallist) I reiterate over globallist.

    for each in self.greet.unpack():
        part ="self.greet."
        compiled = part+str(each)
        print eval(compiled)

Now this works in I can do what I want I have a list of what my dynamic foo's are and they can be created and called but... I use eval, everything I've read has said I shouldn't be using it, as I can not guarantee the pickle as it is generated from user input. So what is the safe way to do this?

I'm sure I'm missing something in creating the globallist I tried

globallist.append(ast.literal_eval(each))

this errors ValueError('malformed string')

So could someone please point me in the right direction please, I'm sure it is to use ast.literal_eval but I seem to be struggling in how to use it in this context.

Any additional criticism also welcome as I'm learning.

Last edited by FeatherMonkey (2009-08-27 14:07:04)

Offline

#2 2009-08-27 13:23:41

Trent
Member
From: Baltimore, MD (US)
Registered: 2009-04-16
Posts: 990

Re: [Solved]Python safe use of eval...

I'm not entirely sure I've understood your question, but I think you want the getattr built-in, which takes an object and a string and returns the attribute named in the string.

>>> class A:
...     x = 0
...     y = 1
... 
>>> A.x
0
>>> getattr(A, 'x')
0
>>> getattr(A, 'y')
1

Offline

#3 2009-08-27 13:56:13

FeatherMonkey
Member
Registered: 2007-02-26
Posts: 313

Re: [Solved]Python safe use of eval...

Thank you so much that is exactly what I needed, now I don't need the eval.

Offline

Board footer

Powered by FluxBB