Issue
This is the behaviour I'm looking for...
"a = 2" # execute this line
print a
> 2
I know about the exec
statement but I need it to work in python 2 and 3 and python 3 does not allow exec to create local variables. Is there another way around this?
EDIT: Like I said - I know that I can't use exec
, the accepted answer of the supposed duplicate is saying to use exec
.
Solution
I dont necessarilly think this is a good idea ...
import ast
def parse_assignment(s):
lhs,rhs = s.split("=",1)
globals()[lhs] = ast.literal_eval(rhs)
parse_assignment("hello=5")
print(hello)
parse_assignment("hello2='words'")
print(hello2)
parse_assignment("hello3=[1,'hello']")
print(hello3)
https://repl.it/repls/BiodegradableLiveProgrammer
Answered By - Joran Beasley
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.