Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change function name dynamically in python

Tags:

python

I want to change the function name according to result obtained from another function but the function definition remains same How can i do this i tried the following example but it didn't work

def f(text):
   def x(text):
     return text+"example"
   name=x(text)
   def name(y):
     return y
   return name
p=f("hi ")
print p("hello")
print p.__name__

OUTPUT

hello
name

But i want the function name p.__name__ as "hi example" not name

like image 602
user1275375 Avatar asked Sep 14 '12 05:09

user1275375


People also ask

How do you change a function name in Python?

The only way to rename a function is to change the code .

How do you make a function dynamic in Python?

Method 1: exec() ? Python's built-in exec() executes the Python code you pass as a string or executable object argument. This is called dynamic execution because, in contrast to normal static Python code, you can generate code and execute it at runtime. This way, you can run programmatically-created Python code.

Can you redefine a function in Python?

Python is dynamic in nature. It is possible to redefine an already defined function.

How do you pass a dynamic value in Python?

Using exec() method to create dynamically named variables Here we are using the exec() method for creating dynamically named variable and later assigning it some value, then finally printing its value.


1 Answers

You can simply assign to __name__:

def f(text):
   def r(y):
     return y
   r.__name__ = text + "example"
   return r
p = f("hi ")
print (p("hello")) # Outputs "hello"
print (p.__name__) # Outputs "hi example"

Note that a function name does not have any influence on the function's behavior though, and does not have any meaning except as a part of the string representation or a debugging aid.

like image 127
phihag Avatar answered Oct 23 '22 20:10

phihag