Note that there are some explanatory texts on larger screens.

plurals
  1. POEval not only with dictionaries
    primarykey
    data
    text
    <p>normaly I can use eval like that:</p> <pre><code>new_dict={'color':'green'} eval("color=='green'",new_dict) </code></pre> <p>in this case it would return true and therefore I would know that the color in new_dict is actually green. Now I found some code where somebody wanted to use eval but with a more general object instead of a dict. In the following code is basicly what this person did:</p> <pre><code>class myStuff(object): def __init__(self): self.color = "green" class Dummy(dict): def __init__(self, node): dict.__init__(self) self.node = node def __getitem__(self, key): return(getattr(self.node, key)) node=myStuff() new_dict = Dummy(node) print eval("color=='green'",new_dict) </code></pre> <p>I wonder now - how did the developer of the above code know that eval is using the method <code>__getitem__</code> on new_dict for color? I found the documentation and the python help function, but I couln't find a step-by-step documentation for a method (or the actual code), so that I would never ever came up on the idea to do just that what the above code does. Or is it bad to use the above method, because no one really knows how the eval method has been implemented and the code could therefore come up with some strange errors in future?</p> <p>EDIT: Here is why eval is used in the program: Imagine you got like 20 objects of myStuff in a list mylist and you want to filter them by color yellow, then one can simply call [ n for n in mylist if eval(query, Dummy(n) ] with `query="color=='yellow'". I am not an expert but I just want to know if this method can lead to problems.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload