0

I'm working on a project that allows users to define filters to sort data in a csv file. They can create as many or as few filters as they want so I am trying to create an if statement from a string that will get longer as users define more filters.

I have an output for my string variable which is this: row[0]=="6/1/2014 0:00:00"

So for simplicity sake I'll just hard code that into a variable name in the sample code below

The problem is that it doesn't correctly evaluate this if statement. It returns every row of the file.

f = open("somefile.csv", "r")
r = csv.reader(f)

statement = 'row[0]=="6/1/2014 0:00:00"'
for row in r:
    if statment:
       print(row)
6
  • Of Course it will evaluate to True for every iteration, since you are checking against a value that is not False... Commented Dec 4, 2015 at 20:14
  • How much trust do you have in these users? In some ways, this looks like a case for eval, but if you don't have 100% trust in your users, then eval is not safe and you'll need to parse the string yourself (e.g. via ast). Commented Dec 4, 2015 at 20:17
  • Is there a way I could use that string in the if statement the same way I would do it if I type it out myself? Commented Dec 4, 2015 at 20:18
  • there is always a better way to do things than eval. might do you some good to create some sort of api for your users that will create filters in a safer manner Commented Dec 4, 2015 at 20:18
  • the string is a result of some other code I created to parse through user input so yeah I'll try eval Commented Dec 4, 2015 at 20:19

1 Answer 1

2

Despite the obvious security reasons you will have to take care of, you can use eval:

if eval(statement):
    print row
Sign up to request clarification or add additional context in comments.

5 Comments

Should consider ast module instead
If the users are explicitly trusted (i.e., this is a piece of code that runs on a local machine, and not a web service or the like), then eval() is perfectly fine.
Yup, better create a high level interface for your users to define filters and then you may interpret the choices into actual python statements. This was just a quick answer to your quick workaround, but doesn't mean this is the way to go.
What would be another approach that would be safer? what is the ast module?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.