exec
ΒΆexec
allows as to execute Python code stored in a string. For example:
s = "a = 42\nprint(a+1)\n"
s
is just a string, but it contains Python code. We can see that more clearly if we print it:
print(s)
We can execute this code with exec
:
exec(s)
Here is another example:
s = '''
def f():
return 45
print(f())
'''
s
We can execute this code using exec
again:
exec(s)
Now, we could also simply put the function g
in a string, without calling it:
s = '''
def g():
print("hi")
'''
Now, if we execute s
, then the functoin g()
will be read in (it will become a global variable), but it won't be called:
exec(s)
We can now call the function g()
:
g()