When defining a function in Python, you would normally use the def
statement and write it as follows.
python
def foo(x):
print(x)
What this function definition statement does is create a function object and assign it to the name foo
in the global namespace.
If the Python script that defines this function is given as text from the outside, the following code will achieve the same processing as the above function definition.
python
func = """def foo(x):
print(x)
"""
exec(func, globals())
The Built-in function ʻexecexecutes the Python code (string or Code object) of the first argument in the namespace of the second argument. In this example, the second argument,
globals (), passes the global namespace for this module, so a function object with the name
foois created in it. That is,
foo is created just as it would normally be defined in a
defstatement. In fact, when you run
foo, you can see that it can be used in the same way as it is normally defined in the
def` statement.
python
>>> foo("hello")
hello
Recommended Posts