0

I need to evaluate the string before assigning it, so I am using eval. But I read eval is not good to use and instead use ast.literal_eval. But when using ast.literal_eval, I am getting malformed string error.

import datetime
x = eval('datetime.datetime.now()')
print x

Result:

2017-12-29 11:15:22.191322

Code with Ast

import datetime
import ast
x = ast.literal_eval('datetime.datetime.now()')

Result:

Malformed String

James Z
  • 12,209
  • 10
  • 24
  • 44
gmrli
  • 63
  • 1
  • 1
  • 5
  • `literal_eval` is not a magical unicorn. There are limits to its uses. The only thing it can parse is string representations of data structures, not expressions like this. – cs95 Dec 29 '17 at 16:22
  • `datetime.datetime.now()` is not a literal. `literal_eval()` is only supposed to evaluate literals -- this is a security measure, ensuring that code can't be sneaked in in places where data is expected. – Charles Duffy Dec 29 '17 at 16:22
  • Err, my bad. I did mean that function only. – cs95 Dec 29 '17 at 16:26
  • @CharlesDuffy : In my scenario to evalute, I can use only eval ?? – gmrli Dec 29 '17 at 16:27
  • @gmrli, ...*can* use `eval` and *can't* use `literal_eval`, certainly. "can only use eval" is a bit too strong -- there are other approaches, even if they're not generalizable or practical. – Charles Duffy Dec 29 '17 at 16:31
  • @gmrli, ...basically, a "literal" is a value that can be directly expressed in a language, without needing to call a function / instantiate an object / etc. – Charles Duffy Dec 29 '17 at 16:32
  • 1
    This sounds like it might be an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). You want to do something (X) and `eval`ing a string may be a way to do it (Y), and you're asking for a better way to do Y (like `literal_eval`). That specific alternative solution doesn't work, but since you haven't actually described what X is (that is, why you are `eval`ing a string in the first place) we can't offer any suggestions for different approaches that might be better at solving the problem. – Blckknght Dec 29 '17 at 17:51

1 Answers1

1

ast.literal_eval document clearly says:

Safely evaluate an expression node or a string containing a Python literal or container display.

The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

Community
  • 1
  • 1
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126