0

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?

George Pamfilis
  • 1,397
  • 2
  • 19
  • 37
  • 14
    Why is this something you think you want to do? What's the context, the problem this solves? – jonrsharpe Aug 18 '18 at 16:41
  • Perhaps the `with_this()` decorator in [this answer](https://stackoverflow.com/a/19327712/355230) to another question might help—although it's hard for me to imagine why you would need to do this. – martineau Aug 18 '18 at 16:44

1 Answers1

1

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

Sushant
  • 3,499
  • 3
  • 17
  • 34