[英]Can a python function know when it's being called by a list comprehension?
I want to make a python function that behaves differently when it's being called from a list comprehension: 我想创建一个python函数,当它从列表推导中调用时表现不同:
def f():
# this function returns False when called normally,
# and True when called from a list comprehension
pass
>>> f()
False
>>> [f() for _ in range(3)]
[True, True, True]
I tried looking at the inspect module, the dis module, and lib2to3's parser for something to make this trick work, but haven't found anything. 我试着查看inspect模块,dis模块和lib2to3的解析器,以便使这个技巧有效,但是没有找到任何东西。 There also might be a simple reason why this cannot exist, that I haven't thought of.
还有一个简单的原因,为什么这个不存在,我没有想到。
You can determine this by inspecting the stack frame in the following sort of way: 您可以通过以下方式检查堆栈帧来确定这一点:
def f():
try:
raise ValueError
except Exception as e:
if e.__traceback__.tb_frame.f_back.f_code.co_name == '<listcomp>':
return True
Then: 然后:
>>> print(f())
None
>>> print([f() for x in range(10)])
[True, True, True, True, True, True, True, True, True, True]
Its not to be recommended though. 但不建议这样做。 Really, its not.
真的,不是。
As it stands this only detects list comprehensions as requested. 目前,这仅按要求检测列表推导。 It will not detect the use of a generator.
它不会检测发电机的使用。 For example:
例如:
>>> print(list(f() for x in range(10)))
[None, None, None, None, None, None, None, None, None, None]
Addon to my comment: Addon到我的评论:
def f(lst=False):
return True if lst else False
f() #False
[f(True) for _ in range(3)] # [True True True]
This would work, but is this the real problem that you're trying to solve? 这可行,但这是你想要解决的真正问题吗? It seems a really unintuitive use-case which can be solved better by other means.
这似乎是一个非常不直观的用例,可以通过其他方式更好地解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.