1

my question is in regard to eval() 'ing a string that contains trusted-user input. I am not sure how to properly package the string (first line after try:). An exception is raised on eval() in the example below. Any help would be highly appreciated. Here is an example code:

import ast

def do_set_operation_on_testids_file(str_filename1, str_filename2, str_set_operation):
  resulting_set = None
    with open(str_filename1) as fid1:
      with open(str_filename2) as fid2:
        list1 = fid1.readlines()
        list2 = fid2.readlines()

        try:
            str_complete_command = "set(list1)." + str_set_operation + "(set(list2))"
            resulting_set = ast.literal_eval(str_complete_command)
            for each_line in resulting_set:
                print(each_line.strip().strip('\n'))
        except:
            print('Invalid set operation provided: ' + str_set_operation)

Thanks very much!

8
  • 1
    What happens if you try this? Commented Jul 19, 2014 at 3:36
  • What is the value of str_complete_command before you try to eval it? Commented Jul 19, 2014 at 3:45
  • An exception is raised. But I am sure yet how to catch and print out the exception. Commented Jul 19, 2014 at 3:46
  • str_complete_command is: Commented Jul 19, 2014 at 3:47
  • 1
    Instead of except, use except Exception, e and then include str(e) in your print statement. Commented Jul 19, 2014 at 3:48

1 Answer 1

2

You don't need to use literal_eval() or eval() at all.

Use getattr() to get the set operation method by string:

>>> list1 = [1,2,3,2,4]
>>> list2 = [2,4,5,4]
>>> str_set_operation = "intersection"
>>> set1 = set(list1)
>>> set2 = set(list2)
>>> getattr(set1, str_set_operation)(set2)
set([2, 4])

Alternatively, you can pass an operator function instead of a string with set method name. Example:

>>> import operator
>>> def do_set_operation_on_sets(set1, set2, f):
...     return f(set1, set2)
... 
>>> do_set_operation_on_sets(set1, set2, operator.and_)
set([2, 4])

where and_ would call set1 & set2, which is an intersection of sets.

Sign up to request clarification or add additional context in comments.

Comments

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.