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 常見問題 ] How to shift a datetime object by 12 hours in python

Source From   Here   Question   Datetime   objects hurt my head for some reason. I am writing to figure out   how to shift a date time obje...