Skip to content

Variable not recognized in nested or filtered list comprehension under IPython.embed() #12199

Description

@mfripp

If I run IPython.embed() and then try to execute the following code from the command line, I get a NameError. Variables defined in the local namespace seem to become invisible when there is a nested list comprehension. They are visible for a single-level list comprehension, but I get a NameError if I refer to a variable from a second or deeper level.

This does not happen with a normal IPython shell or when I use IPython.start_ipython().

Here is the code to reproduce the error.

In [1]: x = [1, 2, 3]                                                                                                                                                                            
In [2]: [i for i in x]                                                                                                                                                                           
Out[2]: [1, 2, 3]  # fine

In [3]: [i for i in x for j in x]                                                                                                                                                                
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-ebe839e86c71> in <module>
----> 1 [i for i in x for j in x]

<ipython-input-2-ebe839e86c71> in <listcomp>(.0)
----> 1 [i for i in x for j in x]

NameError: name 'x' is not defined

In [4]: y = [4, 5, 6]                                                                                                                                                                            
In [5]: [i for i in x for j in y]                                                                                                                                                                
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-5-ba9a21c5a38c> in <module>
----> 1 [i for i in x for j in y]

<ipython-input-5-ba9a21c5a38c> in <listcomp>(.0)
----> 1 [i for i in x for j in y]

NameError: name 'y' is not defined

This is in IPython 7.9.0 with Python 3.7.3.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions