Parameterize function name in Python

ibexy

I have a generic function for which I would like the name to change based on the value of predefined variable. Not sure this is possible in Python:

n = 'abc'
def f{n}(x):
  print(x)
  
f{n}(3)

In the above, the function name will end up becoming "fabc"?

wim

It is possible using a code-generation + exec pattern. It is also possible by instantiating a types.FunctionType instance directly. But a much simpler solution would be to leave the generic name, and then inject an alias (another reference to the same function object) for the dynamic name into whichever namespace you want.

>>> def generic_function(x):
...     print(x ** 2)
... 
>>> dynamic_name = "func_abc"
>>> globals()[dynamic_name] = generic_function
>>> func_abc(3)
9

To inject in some other module namespace that would be a setattr call:

setattr(other_mod, dynamic_name, generic_function)

You could also rewrite the function's __name__ attribute if you wanted to, but there's probably not much point.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Python: function and variable with same name

From Dev

function name is undefined in python class

From Dev

how to assign variable to module name in python function

From Dev

Python: function and variable with the same name

From Dev

Python: Importing a module with the same name as a function

From Dev

Python recognizes the function count as a name

From Dev

Function name is not reusable (python)

From Dev

Passing an attribute name to a function in Python

From Dev

Python: Get name of function which called this function

From Dev

Python print name of a unit test function in setup

From Dev

Parse Python Function's Class Name

From Dev

Dynamically name a function as the script, Python

From Dev

Python predicate function name convention

From Dev

Including the group name in the apply function pandas python

From Dev

In a custom R function that calls ezANOVA: How do I parameterize the dv?

From Dev

Python: Return the name of a function within a function within a function

From Dev

NameError: name is not defined in python init function

From Dev

python underscore function name

From Dev

how can I parameterize select function in scandir

From Dev

Parameterize the Decode Function

From Dev

Function name is not reusable (python)

From Dev

Passing an attribute name to a function in Python

From Dev

Python: Get name of function which called this function

From Dev

Parameterize pattern match as function argument in R

From Dev

Dynamically name a function as the script, Python

From Dev

Pass name to nested function in Python?

From Dev

Python local name in nest function

From Dev

Name error in python with nested function

From Dev

python passing variable name to function

Related Related

HotTag

Archive