I sometimes use embed
at a certain point in a script to quickly flesh out some local functionality. Minimal example:
#!/usr/bin/env python
# ...
import IPython
IPython.embed()
Developing a local function often requires a new import. However, importing a module in the IPython session does not seem to work, when used in a function. For instance:
In [1]: import os
In [2]: def local_func(): return os.path.sep
In [3]: local_func()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-3-f0e5d4635432> in <module>()
----> 1 local_func()
<ipython-input-2-c530ce486a2b> in local_func()
----> 1 def local_func(): return os.path.sep
NameError: global name 'os' is not defined
This is rather confusing, especially since I can even use tab completion to write os.path.sep
.
I noticed that the problem is even more fundamental: In general, functions created in the IPython embed session do not close over variables from the embed scope. For instance, this fails as well:
In [4]: x = 0
In [5]: def local_func(): return x
In [6]: local_func()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-6-f0e5d4635432> in <module>()
----> 1 local_func()
<ipython-input-5-2116e9532e5c> in local_func()
----> 1 def local_func(): return x
NameError: global name 'x' is not defined
Module names are probably just the most common thing to "close over"...
Is there any solution to this problem?
Update: The problem not only applies for closures, but also nested list comprehensions.
Disclaimer: I'll post an (unsatisfactory) answer to the question myself -- still hoping for a better solution though.
2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609]
. – Hectare