2020年9月21日 星期一

[ Python 常見問題 ] Determine function name from within that function (without using traceback)

 Source From Here

Question
In 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?
  1. #foo.py    
  2. def bar():  
  3.     print "my name is", __myname__ # <== how do I calculate this at runtime?  
HowTo
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:
This PEP is rejected. It is not clear how it should be implemented or what the precise semantics should be in edge cases, and there aren't enough important use cases given. response has been lukewarm at best.

However, you can still use inspect module to achieve your goal this way:
  1. import inspect  
  2.   
  3. def bar():  
  4.     current_frame = inspect.currentframe()  
  5.     print(f"I am inside function '{current_frame.f_code.co_name}'")  
  6.   
  7. bar()  
inspect.currentframe(): Return the frame object for the caller’s stack frame.
CPython implementation detail: This function relies on Python stack frame support in the interpreter, which isn’t guaranteed to exist in all implementations of Python. If running in an implementation without Python stack frame support this function returns None.

From Types and members:
* frame.f_code: code object being executed in this frame
* frame.f_code.co_name: name with which this code object was defined


Supplement
python 獲取當前函數的函數名sys._getframe().f_code.co_name

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...