Make IPython Import What I Mean

Viewed 502

I want to modify how IPython handles import errors by default. When I prototype something in the IPython shell, I usually forget to first import os, re or whatever I need. The first few statements often follow this pattern:

In [1]: os.path.exists("~/myfile.txt")
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-0ffb6014a804> in <module>()
----> 1 os.path.exists("~/myfile.txt")

NameError: name 'os' is not defined

In [2]: import os

In [3]: os.path.exists("~/myfile.txt")
Out[3]: False

Sure, that's my fault for having bad habits and, sure, in a script or real program that makes sense, but in the shell I'd rather that IPython follow the DWIM principle, by at least trying to import what I am trying to use.

In [1]: os.path.exists("~/myfile.txt")
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-0ffb6014a804> in <module>()
----> 1 os.path.exists("~/myfile.txt")

NameError: name 'os' is not defined

Catching this for you and trying to import "os" … success!
Retrying …
---------------------------------------------------------------------------
Out[1]: False

If this is not possible with a vanilla IPython, what would I have to do to make this work? Is a wrapper kernel the easiest way forward? Or should this be implemented directly in the core, with a magic command?

Note, this is different from those kind of question where someone wants to always load pre-defined modules. I don't. Cuz I don't know what I will be working on, and I don't want to load everything (nor do I want to keep the list of everything updated.

1 Answers
Related