You can, but you really shouldn't: This raises about a hundred and one odd concerns and potential issues. However, if you insist, the implementation would look something like the following:
def define_function(scope):
name_of_function = input("Enter a name for the function: ")
function_body = """def {}():
print("Blah blah blah.")
""".format(name_of_function)
exec(function_body, scope)
Where from the Python shell, if you import the file containing this function (in my case, sandbox.py
) and pass globals()
or locals()
to it, you can very tentatively get the interface you want.
>>> from sandbox import *
>>> define_function(globals())
Enter a name for the function: hello
>>> hello()
Blah blah blah.