Source From Here
QuestionIn Python, without using the traceback module, is there a way to determine a function's name from within that function?
Say I have a module foo with a function bar. When executing foo.bar(), is there a way for bar to know bar's name? Or better yet, foo.bar's name?
- #foo.py
- def bar():
- print "my name is", __myname__ # <== how do I calculate this at runtime?
Python doesn't have a feature to access the function or its name within the function itself. It has been proposed but rejected. If you don't want to play with the stack yourself, you should either use "bar" or bar.__name__ depending on context. The given rejection notice is:
However, you can still use inspect module to achieve your goal this way:
- import inspect
- def bar():
- current_frame = inspect.currentframe()
- print(f"I am inside function '{current_frame.f_code.co_name}'")
- bar()
From Types and members:
Supplement
* python 獲取當前函數的函數名sys._getframe().f_code.co_name
沒有留言:
張貼留言