oro*_*aki 6 python introspection
我有一个功能:
# utils.py
def hello(name='World'):
# Detect where I'm being called from.
print('Hi, %s. You called this from %s at line # %d.' % (name, mod, lineno))
# ``mod`` and ``lineno`` on previous line would have been set in real use.
Run Code Online (Sandbox Code Playgroud)
我导入该函数并在其他地方运行它
# other.py (this comment at line # 138)
from utils import hello
hello('Johnny') # From inside ``hello`` I want to be able to detect that this
# was called from other.py at line # 140
Run Code Online (Sandbox Code Playgroud)
Sve*_*ach 13
访问封闭框架inspect.currentframe():
import inspect
def hello(name='World'):
f = inspect.currentframe().f_back
mod = f.f_code.co_filename
lineno = f.f_lineno
print('Hi, %s. You called this from %s at line # %d.' %
(name, mod, lineno))
Run Code Online (Sandbox Code Playgroud)