2018年11月8日 星期四

[ Python 常見問題 ] Getting the caller function name inside another function in Python?

Source From Here 
Question 
If you have 2 functions like: 
  1. def A  
  2. def B  
and A calls B, can you get who is calling B inside B, like: 
  1. def A () :  
  2.     B ()  
  3.   
  4. def B () :  
  5.     this.caller.name  
How-To 
You can use the inspect module to get the calling stack. It returns a list of frame records. The third element in each record is the caller name. What you want is this: 
  1. >>> import inspect  
  2. >>> def f():  
  3. ...     for frame in inspect.stack():  
  4. ...             print(frame[3])  
  5. ...  
  6. >>> def g():  
  7. ...     f()  
  8. ...  
  9. >>> g()  
  10. f  
  11. g  
  12.   


沒有留言:

張貼留言

[ Python 文章收集 ] SQLAlchemy Core - Using Functions (7)

Source From   Here   Using Functions   Standard SQL has recommended many functions which are implemented by most dialects. They return a si...