'list comprehension in ipython embed mode

When I am using list comprehension in IPython embed() mode, I found it doesn't work:

In [1]: from IPython import embed

In [2]: embed()
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: k = 0

In [2]: [k for i in range(0,4)]

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-90af25eac9a7> in <module>()
----> 1 [k for i in range(0,4)]

<ipython-input-2-90af25eac9a7> in <listcomp>(.0)
----> 1 [k for i in range(0,4)]

NameError: name 'k' is not defined

However, if I am in origin ipython mode, it works well:

In [1]: k = 0

In [2]: [k for i in range(0,4)]
Out[2]: [0, 0, 0, 0]

So, why there's such a difference? What can I do if I want to check my list comprehension?



Solution 1:[1]

I'd had a same problem, and following was working-solution for me.

ns = locals().copy()
ns.update(globals())
IPython.embed(user_ns=ns)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jinwook Kim