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.

10
  • Possible duplicate of Evaluating dynamically generated statements in Python Commented Jul 25, 2018 at 0:16
  • I would not suggest exec or eval, but can do locals()['a'] = 2 (not saying its good, but definitely safer) Commented Jul 25, 2018 at 0:17
  • 1
    @RafaelC: Modifying the dict returned by locals() is unsupported too. Commented Jul 25, 2018 at 0:19
  • 1
    @RafaelC: It fails inside a function, the same case where exec fails. Commented Jul 25, 2018 at 0:21
  • 1
    @user2357112 can do globals()['a']=2 , not sure recommended Commented Jul 25, 2018 at 0:22

1 Answer 1

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

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

2 Comments

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?
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.