Linked Questions

12 questions linked to/from exec() and variable scope
58 votes
3 answers
30k views

I thought this would print 3, but it prints 1: def f(): a = 1 exec("a = 3") print(a) f() I'm using Python 3. In Python 2, it works as expected (prints 3).
0 votes
0 answers
250 views

I've been working with Python's AST (abstract syntax tree) module recently and came upon an issue with it not seeming to run import statements. I couldn't find anything about this and I'm not exactly ...
0 votes
1 answer
127 views

I'm writing a library that involves codegen, and I'd like to test that the code I'm generating is doing what I expect it to. I want to generate the code, exec it, and then verify that the result is ...
alexgolec's user avatar
  • 28.5k
2 votes
0 answers
36 views

code1.py if(__name__=="__main__"): var = "first_name" inp = "hello" exec("%s = '%s'" % (var,inp)) print(first_name) code2.py def func(): var = "first_name" inp = "hello" ...
1 vote
1 answer
1k views

I'm begginer in Python and I'm in front of a problem that I can't understand. I tried to just define a variable with a exec() and then just print it. And it's working well. BUT when I do the same code ...
1 vote
2 answers
225 views

Edit: the problem is not related to ast module. it can be reproduced with just using exec: y = None exec("y = 5.0") print(y) # prints 5.0 vs def foo(): y = None exec("y = 5.0") print(...
ikamen's user avatar
  • 3,573
1 vote
2 answers
160 views

I have this configuration file (test_conf.txt): [function] exptime1 = |def foo(f): | result=float(f['a']) | return result and this code that works without problem c = ...
-1 votes
1 answer
168 views

How do i turn a python string that contains a function so that i can run it? i found :: How do I turn a string into a function? but i need python not javascript.. i tried running the following in a ...
user avatar
1 vote
2 answers
138 views

I'm doing the following in the python interpreter and it works: rhce=rhcsa=0 args=['rhce','rhcsa'] for cert in args: exec(cert+'+=1') print(eval(cert)) >>> 1 >>> 1 As you ...
musca999's user avatar
  • 381
-1 votes
1 answer
152 views

I am trying to run script2 from script1 with execfile and script2 contains closures: script1.py MyVar1 = 'value1' def fun1(): print(MyVar1) def fun2(): execfile('script2.py') fun1() fun2() ...
Dims's user avatar
  • 51.9k
2 votes
1 answer
87 views

I need to write a custom exec function in python (for several purposes but this is not the problem here, so this custom exec which is called myExec will do exactly as exec for now). I went into this ...
Roland's user avatar
  • 135
0 votes
1 answer
38 views

python 3.7 >>> exec('foobz = 3') >>> print(foobz) 3 why does the above work but the below does not? >>> def blah(): exec('foobz = 3') print(foobz) >>> ......
George Mauer's user avatar