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>You can determine this by inspecting the stack frame in the following sort of way:</p>

<pre><code>def f():
    try:
        raise ValueError
    except Exception as e:
        if e.__traceback__.tb_frame.f_back.f_code.co_name == '&lt;listcomp&gt;':
            return True
</code></pre>

<p>Then: </p>

<pre><code>&gt;&gt;&gt; print(f())
None
&gt;&gt;&gt; print([f() for x in range(10)])
[True, True, True, True, True, True, True, True, True, True]
</code></pre>

<p>Its not to be recommended though.  Really, its not.</p>

<h3>NOTE</h3>

<p>As it stands this only detects list comprehensions as requested.  It will not detect the use of a generator.  For example:</p>

<pre><code>&gt;&gt;&gt; print(list(f() for x in range(10)))
[None, None, None, None, None, None, None, None, None, None]
</code></pre>

python