Python中如何判断函数是否被特定函数调用?
问题
我希望让一个函数在被特定函数调用时表现出特定行为。例如:
def addition(a, b): math_operations(a, b) def math_operations(a, b): if this function is called by addition(a, b): return a + b else: return a * b
请问这样的需求是否可以实现?
可以实现,以下是几种实用方案:
1. 显式传递调用标识(推荐)
这是最直观、可读性最高的方案,直接在调用时传递标记参数:
def addition(a, b): return math_operations(a, b, caller="addition") def math_operations(a, b, caller=None): if caller == "addition": return a + b else: return a * b
这种方式不依赖底层机制,调试和维护都很方便,不会因为代码重构(比如修改函数名)而失效。
2. 利用inspect模块追踪调用栈
通过Python内置的inspect模块获取调用栈信息,判断调用方:
import inspect def addition(a, b): return math_operations(a, b) def math_operations(a, b): # 获取调用当前函数的上层帧信息 caller_frame = inspect.currentframe().f_back caller_name = caller_frame.f_code.co_name if caller_name == "addition": return a + b else: return a * b
注意:这种方式依赖Python解释器的实现,在优化编译、沙箱等特殊环境下可能失效,性能也略低于显式传参。
3. 上下文变量标记调用链
适合复杂调用场景,用上下文变量传递调用标识,无需逐层传参:
import contextvars # 创建上下文变量存储调用方标识 caller_ctx = contextvars.ContextVar("caller", default=None) def mark_caller(name): def decorator(func): def wrapper(*args, **kwargs): token = caller_ctx.set(name) try: return func(*args, **kwargs) finally: caller_ctx.reset(token) return wrapper return decorator # 给调用函数打上标识装饰器 @mark_caller("addition") def addition(a, b): return math_operations(a, b) def math_operations(a, b): caller = caller_ctx.get() if caller == "addition": return a + b else: return a * b
内容的提问来源于stack exchange,提问作者Seb_
相关产品推荐
相关产品推荐

