execΒΆ

exec allows as to execute Python code stored in a string. For example:

In [1]:
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:

In [2]:
print(s)
a = 42
print(a+1)

We can execute this code with exec:

In [3]:
exec(s)
43

Here is another example:

In [4]:
s = '''
def f():
  return 45
print(f())
'''
In [5]:
s
Out[5]:
'\ndef f():\n  return 45\nprint(f())\n'

We can execute this code using exec again:

In [6]:
exec(s)
45

Now, we could also simply put the function g in a string, without calling it:

In [7]:
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:

In [8]:
exec(s)

We can now call the function g():

In [9]:
g()
hi