Using the python inspect module, in a function, I would like to get the source code of the line that called that function.
So in the following situation:
def fct1():
# Retrieve the line that called me and extract 'a'
return an object containing name='a'
a = fct1()
Run Code Online (Sandbox Code Playgroud)
I would like to retrieve the string "a = fct1()" in fct1
All I can do so far is to retrieve the code of the whole module with :
code = inspect.getsource(sys._getframe().f_back)
Run Code Online (Sandbox Code Playgroud)
Please note that fct1() can be called many times in the main module.
Eventually, what I want is to retrieve the variable name "a" which is easy if I can get s = "a = fct1()" in fct1() :
a_name = s.split("=")[0].strip()
Run Code Online (Sandbox Code Playgroud)
一个非常愚蠢的解决方案是捕获堆栈跟踪并获取第二行:
import traceback
def fct1():
stack = traceback.extract_stack(limit=2)
print(traceback.format_list(stack)[0].split('\n')[1].strip()) # prints "a = fct1()"
return None
a = fct1()
Run Code Online (Sandbox Code Playgroud)
@jtlz2 在装饰器中请求它
import traceback
def add_caller(func):
def wrapper(*args, **kwargs):
stack = traceback.extract_stack(limit=2)
func(*args, caller=traceback.format_list(stack)[0].split('\n')[1].strip(), **kwargs)
return wrapper
@add_caller
def fct1(caller):
print(caller)
fct1()
Run Code Online (Sandbox Code Playgroud)
它确实有效
| 归档时间: |
|
| 查看次数: |
338 次 |
| 最近记录: |