0

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.

Mahir Islam
  • 1,811
  • 2
  • 10
  • 31
Ogen
  • 6,396
  • 5
  • 46
  • 119

1 Answers1

3

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

Joran Beasley
  • 103,130
  • 11
  • 146
  • 174
  • I'm just writing a simple script - not an enterprise level python project so this is working fine. I'm curious, what are the ramifications if this kind of code existed in a huge python project that many people were using? – Ogen Jul 25 '18 at 22:30
  • its just a weird way of setting variables that becomes hard to debug when things dont go right basically ... theres not much security ramifications, mosty it can become hard to track down problems – Joran Beasley Jul 25 '18 at 23:59