-1

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?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Vernaon
  • 7
  • 3
  • 1
    I don't understand exactly what you are asking. Do you mean, you want to create functions named dynamically? Like the name of the function is stored in a list and then you iterate over that list and create the function with the name? – sushant_padha Jun 19 '21 at 14:11
  • 2
    Notice that function names are not special, they're just variables that happen to contain functions, and generating variables dynamically is usually not a good idea. https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables – Ture Pålsson Jun 19 '21 at 14:17
  • 1
    You definitely do not want to do this. – rafaelc Jun 19 '21 at 14:46
  • 1
    What is your underlying goal? What do you aim to accomplish once you figure this out? This is a classic [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem): "...asking about your attempted *solution* rather than your actual *problem*. That is, you are trying to solve problem X, and you think solution Y would work, but instead of asking about X when you run into trouble, you ask about Y." – John Kugelman Jun 19 '21 at 14:48
  • Manually. 1) Create functions with an internal naming scheme (`x`, `y`, whatever) 2) use a dict to associate your desired name with that function: `mapping={'my_name_for_x':x, 'my_name_for_y':y}` 3) call with `mapping['my_name_for_x']()` – dawg Jun 19 '21 at 15:00
  • See [Why you don't want to dynamically create variables](https://stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html). – martineau Jun 19 '21 at 15:44

1 Answers1

1

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

sushant_padha
  • 159
  • 1
  • 8