2

Im trying to create a more dynamic program where I define a function's name based on a variable string.

Trying to define a function using a variable like this:

__func_name__ = "fun"

def __func_name__():
  print('Hello from ' + __func_name__)

fun()

Was wanting this to output:

Hello from fun

The only examples I found were: how to define a function from a string using python

13
  • You need to use exec. But don't. This is not a good thing to do. Commented Apr 30, 2019 at 6:31
  • @rdas Why isn't it a good thing? Commented Apr 30, 2019 at 6:31
  • This is not "more dynamic" - it is simply bad. Do not do it. Commented Apr 30, 2019 at 6:32
  • Apart from being a huge risk for RCE, it's not better than just normal code: stackoverflow.com/questions/1933451/… Commented Apr 30, 2019 at 6:33
  • 2
    @isethi why do you think dynamically naming a function is something you should do and why Python should allow you do it? It's dangerous/pretty much pointless... Python does try to avoid letting you shoot yourself in the foot... (although - it does let you if you really want to...) Commented Apr 30, 2019 at 6:41

2 Answers 2

5

You can update globals:

>>> globals()["my_function_name"] = lambda x: x + 1
>>> my_function_name(10)
11

But usually is more convinient to use a dictionary that have the functions related:

my_func_dict = {
    "__func_name__" : __func_name__,
}

def __func_name__():
  print('Hello')

And then use the dict to take the funtion back using the name as a key:

my_func_dict["__func_name__"]()
Sign up to request clarification or add additional context in comments.

2 Comments

is there any way to run multiple lines of code inside of that lambda like you would inside of a normal structured function?
@isethi, it is better you just define a function for that, I used lambda as an example, but you can use whatever callable object there.
1

This should do it as well, using the globals to update function name on the fly.

def __func_name__():
  print('Hello from ' + __func_name__.__name__)

globals()['fun'] = __func_name__

fun()

The output will be

Hello from __func_name__

2 Comments

Err... what does this offer over just doing: fun = __func_name__ ? (and while it's not clear... I get the feeling the OP probably wants that output to be "Hello from fun"....)
Yes you are right! Let me modify the answer to make it better :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.