Can a python function know when it's being called by a list comprehension?
<p>I want to make a python function that behaves differently when it's being called from a list comprehension:</p>

<pre><code>def f():
    # this function returns False when called normally,
    # and True when called from a list comprehension
    pass

&gt;&gt;&gt; f()
False
&gt;&gt;&gt; [f() for _ in range(3)]
[True, True, True]
</code></pre>

<p>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. There also might be a simple reason why this cannot exist, that I haven't thought of.</p>

<p>Addon to my comment:</p>

<pre><code>def f(lst=False):
    return True if lst else False

f() #False
[f(True) for _ in range(3)] # [True True True]
</code></pre>

<p>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.</p>

python