I’ve got a dynamic Python service that will be defining functions on a per-record basis and I ran into something I couldn’t quite figure out. Say I’ve got a test program set up like so:
func_str = """
def func():
print "top"
"""
exec func_str
func_str = """
def func():
print "bottom"
"""
exec func_str
func()
This will, of course, print "bottom", as the second call to exec func_str overwrites the first. I’m curious what happens under the hood. Is the first function definition deleted in some way?
The function body is compiled, then it assigned to the local namespace under the variable name
func.When you then run the second
execstatement a new function is stored under that same name, overwriting the first. You can preserve the first one by storing a reference to it in a new name:so you can later on refer to it still as
foo:You could also store it in a dictionary, a list, or as an attribute on another object.