tags:

views:

68

answers:

3

Hi Folks I have the following code in one of my classes along with checks when the code does not eval:

filterParam="self.recipientMSISDN==tmpBPSS.split('_')[3].split('#')[0] and   self.recipientIMSI==tmpBPSS.split('_')[3].split('#')[1]" 
if eval(filterParam):
   print "Evalled"
else:
   print "Not Evalled\nfilterParam\n'%s'\ntmpBPSS\n'%s'\nself.recipientMSISDN\n'%s'\nself.recipientIMSI\n'%s'" % (filterParam, tmpBPSS, self.recipientMSISDN, self.recipientIMSI)

I am not getting anything to 'eval'. Here are the results:

Not Evalled
filterParam
'self.recipientMSISDN==tmpBPSS.split('_')[3].split('#')[0] and    self.recipientIMSI==tmpBPSS.split('_')[3].split('#')[1]'
tmpBPSS
'bprm_DAILY_MO_919844000039#892000000'
self.recipientMSISDN
'919844000039'
self.recipientIMSI
'892000000'

So I used the outputs from the above to check the code in a python shell and as you can see the code evalled correctly:

>>> filterParam="recipientMSISDN==tmpBPSS.split('_')[3].split('#')[0] and recipientIMSI==tmpBPSS.split('_')[3].split('#')[1]"
>>> tmpBPSS='bprm_DAILY_MO_919844000039#892000000'
>>> recipientMSISDN='919844000039'
>>> recipientIMSI='892000000'
>>> if eval(filterParam):
...    print "Evalled"
... else:
...    print "Not Evalled"
...
Evalled

Am I off my rocker or what am I missing?

A

+1  A: 

Most likely, the type of self.recipientIMSI or self.recipientMSISDN is int, and comparing them with strings returns False. Add this line to see if this is the case:

print type(self.recipientIMSI), type(self.recipientMSISDN)

If not, try checking what the same expression evaluates to without eval.

That said, Are you sure you need to use eval? Usually there's a way of doing things without eval or exec, which will lead to safer, more maintainable code.

interjay
brilliant. I looked at everything but missed this. Thank you v much. I was tearing what little hair I had out trying so see what was wrong.
amadain
A: 

The return value from eval is not whether or the code was evaluated, but the actual value returned by doing so. Since you have an and statement in your code string, presumably one or both of the expressions evaluate to False.

Daniel Roseman
A: 

Why are you even doing the eval at all? Why not just make the comparison directly in the if statement?

It's possible there is a type mismatch. One of those values you specify could be unicode or some other type of string-like object. Whey you print it, you're casting it to a string and so they look equal, but they may be different types, and so evaluate to False.

Brendan Abel
I use eval because filterParam is a generated statement that is vastly different based on how the method is called
amadain
@amadain, That's what functions are for.
Mike Graham