2

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"?

1
  • Note that if you just want to reference a function by a dynamic name, a better solution is to use a dict, e.g. funcs = {'abc': fun1} Then you could call the function corresponding to 'abc' as funcs['abc'](). Commented Nov 18, 2020 at 7:52

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You could do it with something like the below:

def f(n):    
    exec(f"def f{n}(x): print(x)") 
    return eval(f"f{n}")

2 Comments

This doesn't work when f uses names from outer scopes, though.
Yes you are right, your solution is definitely a better approach. Just thought I would share this method as well as proof of concept since it achieves what OP was asking with the same syntax

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.