I have written the following code in Python 3.6.2:
user=0
def test():
global user
d = locals()
exec('user=1', globals(), d)
test()
print(user)
I want to use variable user (it is global) in exec and change its value to 1 and in print(user) print its value, but it is printing 0.
How can fix it?
You need to declare the variable global in the executed code:
>>> user = 0
>>> def test():
... exec('global user; user=1', globals())
...
>>> test()
>>> print(user)
1
Related
def a():
print("Hello World!")
b = 1
return b
c = a()
print(c)
I just want to display 1 in the console window, but the string'Hello world' also appears. How can I fix this?
def a(printing):
if printing == True:
print("Hello World!")
b = 1
return b
c = a(printing = False)
print(c)
Thank you very much! I solved this problem with parameter :)
You could try this.
def a(printing=False):
if printing:
print("Hello World!")
b = 1
return b
c = a()
print(c)
# Print Hello World and 1
print_hello = a(printing=True)
print(print_hello)
Alternatively you could nest methods.
def a()
return 1
def A():
print("Hello World!")
return a()
c = a()
print(c)
# To print hello world and 1
print_hello = A()
print(print_hello)
You could also have use a variable in the outer scope of the method and set it to True/False before you run the method.
I do not see an obvious way of doing this without some kind of extra variable, parameter or method call. All 3 of these methods would allow you to call a() without any parameters and have it not print Hello world!
I'm trying to convert a String containing a Python variable assignment into an actual variable.
The following was working for me.
s = "VAR = [1,55]"
exec(s)
print(VAR)
But then when places this code in a function, VAR never gets defined.
def myFunction():
s = "VAR = [1,55]"
exec(s)
print(VAR)
myFunction()
I'm not sure what I am missing. Thanks in advance for the help!
Responses to a few of the questions...
Error message: "NameError: name 'VAR' is not defined"
Using: Python 3
You can also pass globals to exec:
def myFunction():
s = "VAR = [1,55]"
exec(s, globals())
print(VAR)
related
python 2.7
def myfunc():
v1 = 11
exec "v1 = 22"
print v1
myfunc() # 22
def myFunction():
VAR = None
s = "VAR = [1,55]"
exec(s)
print(VAR)
myFunction() # [1, 55]
OR
def myFunction():
#VAR = None
s = "VAR = [1,55]"
exec(s)
print(locals()["VAR"])
myFunction() # [1,55]
In Python 2.7 you can simply do:
>> s = "VAR=55"
>> exec(s)
>> VAR
55
If you need custom namespace do:
>> my_ns = {}
>> exec "VAR=55" in my_ns
>> my_ns["VAR"]
55
Similar applies for Python 3 but exec there is actually a function so exec(...) is to be used. For example:
>> s = "VAR=55"
>> exec(s)
>> VAR
55
When you use functions scope comes into play. You can use locals(), globals() or use your custom namespace:
>>def foo():
ns = {}
s = "VAR=55"
exec(s) in ns
print(ns["VAR"])
>>foo()
55
I have a text file that contains Python function like this:
a.txt
def func():
var = 5
return var
And then I read this file in a Python script:
b.py
python_file = open("a.txt").read()
Now I want to assign the a.txt file's function to a variable without worrying about the function name and execute it. I tried something like this:
python_file = open("a.txt").read()
b = exec(python_file)
b()
But it didn't work, I tried execfile as well.
After you've executed the string, you can call func directly, as it has been added to your current namespace:
>>> exec("""def func():
var = 5 # note that the semicolons are redundant and unpythonic
return var""")
>>> func()
5
Per its documentation exec doesn't actually return anything, so there's no point assigning e.g. foo = exec(...).
To see what names are locally defined in the code being executed, pass an empty dictionary to exec as the locals parameter:
>>> ns = {}
>>> exec("""def func():
var = 5
return var""", globals(), ns)
>>> ns
{'func': <function func at 0x0315F540>}
You can then assign the function and call it as you normally would:
>>> b, = ns.values() # this will only work if only one name was defined
>>> b()
5
Before offering my solution, I highly warn against do this unless you know for sure there is no malicious code in a.txt.
My solution uses the execfile function to load the text file and return the first object (could be a variable or function):
def load_function(filename):
""" Assume that filename contains only 1 function """
global_var = dict()
execfile(filename, global_var)
del global_var['__builtins__']
return next(global_var.itervalues())
# Use it
myfunction = load_function('a.txt')
print myfunction()
Update
To be a little more careful, modify the return line like the following so that it skips variables (it cannot skip class declaration, however).
return next(f for f in global_var.itervalues() if callable(f))
Update 2
Thank you johnsharpe for pointing out that there is no execfile in Python 3. Here is a modified solution which use exec instead. This time, the function should be found in the "local" scope.
def load_function(filename):
""" Assume that filename contains only 1 function """
with open(filename) as f:
file_contents = f.read()
global_var = dict()
local_var = dict()
exec file_contents in global_var, local_var
return next(f for f in local_var.itervalues() if callable(f))
# Use it
myfunction = load_function('a.txt')
print myfunction()
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Short Description of Python Scoping Rules
I wrote two simple functions:
# coding: utf-8
def test():
var = 1
def print_var():
print var
print_var()
print var
test()
# 1
# 1
def test1():
var = 2
def print_var():
print var
var = 3
print_var()
print var
test1()
# raise Exception
In comparison, test1() assigns value after print var, then raise an Exception: UnboundLocalError: local variable 'var' referenced before assignment, I think the moment I call inner print var, var has a value of 2, am I wrong?
Yes, you're incorrect here. Function definition introduces a new scope.
# coding: utf-8
def test():
var = 1
def print_var():
print var <--- var is not in local scope, the var from outer scope gets used
print_var()
print var
test()
# 1
# 1
def test1():
var = 2
def print_var():
print var <---- var is in local scope, but not defined yet, ouch
var = 3
print_var()
print var
test1()
# raise Exception
I have two code which really confused me.
def get_context():
__gc = globals()
__lc = locals()
def precompiler(code):
exec code in __lc
def compiler(script, scope):
return compile(script, scope, 'eval')
def executor(expr):
return eval(expr, __gc, __lc)
return precompiler, compiler, executor
maker1, compiler1, executor1 = get_context()
maker2, compiler2, executor2 = get_context()
maker1("abc = 123")
maker2("abc = 345")
expr1 = compiler1("abc == 123", "test.py")
print "executor1(abc == 123):", executor1(expr1)
print "executor2(abc == 123):", executor2(expr1)
the result is:
executor1(abc == 123): True
executor2(abc == 123): False
Why the compile execute in the closure only once and the byte-code could run in both?
And there is another code here:
def get_context():
__gc = globals()
__lc = locals()
test_var = 123
def compiler(script, scope):
return compile(script, scope, 'eval')
def executor(expr):
return eval(expr, __gc, __lc)
return compiler, executor
compiler1, executor1 = get_context()
compiler2, executor2 = get_context()
expr1 = compiler1("test_var == 123", "test.py")
print "executor1(test_var == 123):", executor1(expr1)
print "executor2(test_var == 123):", executor2(expr1)
the result is:
NameError: name 'test_var' is not defined
And how did this happen?
Why does the compile need to check the environment(variable or some others) of the closure while it is not dependent on the closure? This is what I confused!
In your first example, you are executing 'abc=123' in your first context, and 'abc=345' in your second context. So 'test_var==123' is true in your first context and false in your second context.
In your second example, you have caught an interesting situation where the interpreter has removed test_var from the context because test_var isn't referenced.
For your first question, compile just takes the python code and produces the bytecode. It it is not dependent in any way on the closure where you compiled it. Its not different then if you had produced say, a string. That string isn't permantely tied to the function where it was created and neither is the code object.
For your second question, locals() builds a dictionary of the local variables when it is called. Since you setup test_var after calling locals it doesn't have it. If you want test_var inside locals, you need to call it afterwards.