how to change function name dynamically in python

  • Last Update :
  • Techknowledgy :

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"

Suggestion : 2

The exec() function can take any source code as a string and run it within your script. It’s the perfect way to dynamically create a function in Python!,Here’s how you can use the exec() function to define 10 functions programmatically and run them afterwards:,First, define the factory function that dynamically creates a local function f only visible within the scope of the current function execution. The function f can do all the custom things you want it to do.,As you can see you can “hard-code” any behavior into the inner function based on the factory arguments to customize how functions are dynamically created.

For example, you may want to define ten functions f_0, f_1, …, f_9 programmatically that do something such as printing its function identifier. You could do the following:

def f_0(): print(0)
def f_1(): print(1)
def f_2(): print(2)
def f_3(): print(3)
def f_4(): print(4)
def f_5(): print(5)
def f_6(): print(6)
def f_7(): print(7)
def f_8(): print(8)
def f_9(): print(9)


The desired output would be:


Here’s how you can use the exec() function to define 10 functions programmatically and run them afterwards:

# Define functions f_0 to f_9
for i in range(10):
   exec(f "def f_{i}(): print({i})")

# Run functions f_0 to f_9
for i in range(10):
   exec(f "f_{i}()")

You can use the dir() function to check out whether the functions are really defined in the namespace:

>>> dir()['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'f_0', 'f_1', 'f_2', 'f_3', 'f_4', 'f_5', 'f_6', 'f_7', 'f_8', 'f_9', 'i']

A more elegant way to solve our problem would be to create a function factory—a function that creates other functions programmatically and returns them as function objects. You can then use the callable objects to run the dynamically-created functions.

# Define factory
def factory(argument):
   def f():

return f

# Define functions
functions = []
for i in range(10):

# Run functions
for f in functions:

Suggestion : 3

In Python, say I have a string that contains the name of a class function that I know a particular object will have, how can I invoke it?, How to invoke a function on an object dynamically... ,96548/how-to-invoke-a-function-on-an-object-dynamically-by-name,Combined mean and standard deviation from a collection of NumPy arrays of different shapes 3 days ago

That is:

obj = MyClass() # this class has a method doStuff()
func = "doStuff"
# how to call obj.doStuff() using the func variable ?

Use "getattr": 

obj = MyClass()
func = getattr(obj, "dostuff")
except AttributeError:
   print "dostuff not found"

Suggestion : 4

Sometimes a programmer gets an idea to make his/her work easier by creating magically working code that uses setattr() and getattr() functions to set some variable. While this may look like a good idea, because there is no need to write all the methods by hand, you are asking for trouble down the road., Maintainability using wildcard imports (from … import *) Not using with to open files Returning more than one variable type from function call Using the global statement Using single letter to name your variables Dynamically creating variable/method/function names ,Now the class contains also unknownX variables indexed by their count. Well, what a nice mess we created here. Try to find a year later where these variables come from.,While the approach in the examples above may be the easiest to write, it is the worst to maintain later. You should always try to find another way to solve your problem.

data_dict = {
   'var1': 'Data1',
   'var2': 'Data2'

class MyAwesomeClass:

   def __init__(self, data_dict):
   for key, value in data_dict.iteritems():
   setattr(self, key, value)
data_list = ['dat1', 'dat2', 'dat3']
data_dict = {
   'dat1': [1, 2, 3],
   'dat2': [4, 5, 6],
   'dat3': [7, 8, 9],
   'dat4': [0, 4, 6]

class MyAwesomeClass:

   def __init__(self, data_list, data_dict):
   counter = 0

for key, value in data_dict.iteritems():
   if key in data_list:
   setattr(self, key, value)
   setattr(self, 'unknown' + str(counter), value)
counter += 1

Suggestion : 5

The first three arguments are the components that make up a class definition header: the class name, the base classes (in order), the keyword arguments (such as metaclass).,The arguments are the components that make up a class definition header: the class name, the base classes (in order) and the keyword arguments (such as metaclass).,Creates a class object dynamically using the appropriate metaclass.,The exec_body argument is a callback that is used to populate the freshly created class namespace. It should accept the class namespace as its sole argument and update the namespace directly with the class contents. If no callback is provided, it has the same effect as passing in lambda ns: None.

>>> from types
import GenericAlias

   list[int] == GenericAlias(list, (int, ))
   dict[str, int] == GenericAlias(dict, (str, int))
class SimpleNamespace:
   def __init__(self, /, **kwargs):

      def __repr__(self):
      items = (f "{k}={v!r}"
         for k, v in self.__dict__.items()) return "{}({})".format(type(self).__name__, ", ".join(items))

      def __eq__(self, other):
      if isinstance(self, SimpleNamespace) and isinstance(other, SimpleNamespace):
      return self.__dict__ == other.__dict__
      return NotImplemented

Suggestion : 6

Post date May 15, 2022 ,© 2022 The Web Dev

For instance, we write

const name = "myFn";
const fn = {
   [name]() {}
} [name];