2

I have a python function to which a string is passed as parameter, the parameter may be a string representation of int, array,dictionary or a normal string

for int,array and dictionary its working properly, but if the parameter is a normal string the ast.literal_eval() throws error

import ast # below statements throw error #output_value = ast.literal_eval('someNormalString') #output_value = ast.literal_eval('name1 name2 name3') #below statements work fine output_value = ast.literal_eval('5') output_value = ast.literal_eval('[{"id":"XYZ_GTTC_TYR", "name":"Suction"}]') output_value = ast.literal_eval('["name1","name2"]') print(output_value) 

is there any way to to handle it if the param is just a normal string?

below is my python function

def func(key): value = ast.literal_eval(value) return value 
2
  • 1
    You should preferably know whether your value is supposed to represent something that can be eval'd or not. What if you have a string that looks like a valid literal, but is supposed to be a plain string? Commented Jun 10, 2021 at 9:24
  • Side note: those are valid list and dictionary literals, but they also happen to be valid JSON. Are you sure JSON isn't what you need to be using? Commented Jun 10, 2021 at 10:22

2 Answers 2

5

A good way to understand what's happening here is to think of ast.literal_eval as a (highly simplified) python interpreter, which evaluates what's inside the string.

When you run ast.literal_eval('someNormalString'), it's as if you told python to evaluate someNormalString - which obviosuly raises an error.

Try: ast.literal_eval("'someNormalString'") so ast is evaluating 'someNormalString' instead.

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

Comments

3

The code is viewing the string as someNormalString but it actually needs to use 'someNormalString'. To achieve this, alter the code like so:

output_value = ast.literal_eval("'someNormalString'") output_value = ast.literal_eval("'name1 name2 name3'") 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.