Reputation: 1487
I would like to rename a python function by passing its name to itself as a string.
for example.
def ihavenoname(new_name="cheese"):
something.this_function.name= new_name
# https://stackoverflow.com/questions/251464/how-to-get-a-function-name-as-a-string-in-python
import traceback
stack = traceback.extract_stack()
filename, codeline, funcName, text = stack[-2]
return funcName
>>>"cheese"==ihavenoname() # True
is this possible?
Upvotes: 0
Views: 983
Reputation: 3669
You can rename a function by changing __name__
. You could simply create a decorator and use it to rename the function name -
def rename(newname):
def decorator(fn):
fn.__name__ = newname
return fn
return decorator
@rename('new name')
def f():
pass
But a side note, your function will only be reachable through the original name
Upvotes: 1