How can I set the name of a function using a string from a list?
listname = ["first", "second"]
def listname[0]():
(...)
After that the error appears
SyntaxError: Invalid Syntax
Is there any way to do that?
How can I set the name of a function using a string from a list?
listname = ["first", "second"]
def listname[0]():
(...)
After that the error appears
SyntaxError: Invalid Syntax
Is there any way to do that?
This can be done using python's compile()
and exec()
You can store the function code in a string like:
generic_func_code="""\
def func_name(x):
return x+1"""
Then replace the function name using str.replace()
and execute the newly created string.
func_code=generic_func_code.replace('func_name', listname[0])
exec(func_code)
# function named listname[0] has been created
However, as pointed out by @Ture Pålsson this probably isn't a good idea