[BangPypers] Evaluating a string against mapping in python.

Okan bhan rajalokan at gmail.com
Sun Oct 26 06:21:00 CET 2014


Hello everyone,

Hope you all celebrated festival of Diwali with your loved ones. Wishes
from my side to each one of you.

I'm facing issue in understanding python's 'eval' function's behaviour.
I've no previous deep knowledge of using 'eval' except that "it is used to
evaluate a string just like on python prompt". While working on a feature
on pytest, I encountered usage of eval against a map.

For a very simple case, I wanted to check if a string exists within a list.
Very simple
>>>   'foo' in list_foo.

But string 'foo' can contain expression (like 'foo and bar'). To check
this, I see they have used something like

>>> eval('foo and bar', {}, mapping).

A simple implementation of this is:

class SimpleMapping:
  def __init__(self, items):
    self._items = items

  def __getitems__(self, subitem):
    print('*' * 20)
    for item in self._items:
      if subitem in item:
        return True
    return False

Playing around against it for a bit.
>>>  mapping = SimpleMapping(set(['aaa', 'bbb', 'ccc']))
>>>  eval('ppp', {}, mapping)
        ********************
        False
>>>  eval('aa', {}, mapping)
        ********************
        True
>>>  eval('xxx and aaa', {}, mapping)
        ********************
        False
>>>  eval('xxx or aaa', {}, mapping)
        ********************
        ********************
        True

Struggled in beginning but now they all seem obvious to me. Tricky is:

>>>  eval('5.6', {}, mapping)
        5.6
>>>  eval('aa.a', {}, mapping)
        AttributeError: 'bool' object has no attribute 'a'

My doubts are:
a. Why it didn't run for numeric 5.6? Also why is dot separated '5.6' any
different to 'aa.a'? I looked around on eval documentation and examples but
couldn't find use of eval with a mapping.

b. I see many blogs suggesting to refrain from using eval unless absolutely
needed. Is this one use case we must use it? Do we have any better way to
evaluate this?

c. If indeed, I have to evaluate a string containing dots, how to do in the
above scenario?

Would appreciate any pointers or more clarity on this.

Thanks & Regards
Alok


More information about the BangPypers mailing list