eval

Python: how do I call `print` from `eval` in a loop?

Python: how do I call `print` from `eval` in a loop? Question: When I call print from eval: def printList(myList): maxDigits = len(str(len(myList))) Format = ‘0{0}d’.format(maxDigits) for i in myList: eval(‘print “#{0:’ + Format + ‘}”.format(i+1), myList[i]’) it gives an error: print “#{0:01d}”.format(i+1), myList[i] ^ SyntaxError: invalid syntax I tried to make use of this, …

Total answers: 4

How to pass arguments to the __code__ of a function?

How to pass arguments to the __code__ of a function? Question: The following works: def spam(): print “spam” exec(spam.__code__) spam But what if spam takes arguments? def spam(eggs): print “spam and”, eggs exec(spam.__code__) TypeError: spam() takes exactly 1 argument (0 given) Given, that I don’t have access to the function itself but only to a …

Total answers: 6

Python: make eval safe

Python: make eval safe Question: I want an easy way to do a “calculator API” in Python. Right now I don’t care much about the exact set of features the calculator is going to support. I want it to receive a string, say “1+1” and return a string with the result, in our case “2”. …

Total answers: 4

What's the difference between eval, exec, and compile?

What's the difference between eval, exec, and compile? Question: I’ve been looking at dynamic evaluation of Python code, and come across the eval() and compile() functions, and the exec statement. Can someone please explain the difference between eval and exec, and how the different modes of compile() fit in? Asked By: andrewdotnich || Source Answers: …

Total answers: 3

Why is using 'eval' a bad practice?

Why is using 'eval' a bad practice? Question: I use the following class to easily store data of my songs. class Song: """The class to store the details of each song""" attsToStore=(‘Name’, ‘Artist’, ‘Album’, ‘Genre’, ‘Location’) def __init__(self): for att in self.attsToStore: exec ‘self.%s=None’%(att.lower()) in locals() def setDetail(self, key, val): if key in self.attsToStore: exec …

Total answers: 8

Use of eval in Python?

Use of eval in Python? Question: There is an eval() function in Python I stumbled upon while playing around. I cannot think of a case when this function is needed, except maybe as syntactic sugar. Can anyone give an example? Asked By: ooboo || Source Answers: The Wikipedia article on eval is pretty informative, and …

Total answers: 14

Security of Python's eval() on untrusted strings?

Security of Python's eval() on untrusted strings? Question: If I am evaluating a Python string using eval(), and have a class like: class Foo(object): a = 3 def bar(self, x): return x + a What are the security risks if I do not trust the string? In particular: Is eval(string, {“f”: Foo()}, {}) unsafe? That …

Total answers: 6