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,941
  • 2
  • 12
  • 33
Ogen
  • 6,499
  • 7
  • 58
  • 124
  • Possible duplicate of [Evaluating dynamically generated statements in Python](https://stackoverflow.com/questions/16951937/evaluating-dynamically-generated-statements-in-python) – ivan_pozdeev Jul 25 '18 at 00:16
  • I would not suggest `exec` or `eval`, but can do `locals()['a'] = 2` (not saying its good, but definitely safer) – rafaelc Jul 25 '18 at 00:17
  • 1
    @RafaelC: [Modifying the dict returned by `locals()` is unsupported too.](https://ideone.com/MlKtZJ) – user2357112 Jul 25 '18 at 00:19
  • Possible duplicate of [How can I assign the value of a variable using eval in python?](https://stackoverflow.com/questions/5599283/how-can-i-assign-the-value-of-a-variable-using-eval-in-python) – zwer Jul 25 '18 at 00:19
  • @user2357112 works in terminal/Ipython ? – rafaelc Jul 25 '18 at 00:21
  • 1
    @RafaelC: It fails inside a function, the same case where `exec` fails. – user2357112 Jul 25 '18 at 00:21
  • 1
    @user2357112 can do `globals()['a']=2` , not sure recommended – rafaelc Jul 25 '18 at 00:22
  • can you just share the snippet for a min in the comment and delete it – rawwar Jul 25 '18 at 00:27
  • @RafaelC And that creates a global variable, not a local variable, which the OP has expressed a need to do. – chepner Jul 25 '18 at 02:57
  • @chepner don't know about that, accepted answer used globals – rafaelc Jul 25 '18 at 03:24

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
  • 110,522
  • 12
  • 160
  • 179
  • 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