2

The %pylab magic in IPython imports a bunch of functions into the user's workspace, which is very convenient. Looking at the code, it's not at all obvious how this is done. What I have so far is a magic function in my startup folder:

from IPython.core.magic import register_line_magic

@register_line_magic
def import_my_functions(line):
    """
    Import functions into namespace somehow....
    e.g. import numpy as np
    """

It then should be possible:

In[1]: %import_my_functions
 imported the following:
   numpy as np
   .....
In[2]: np
Out[2]: <module 'numpy' from ..../venv/lib/python2.7/site-packages/numpy/__init__.pyc'>

Bonus would be if the command also reloads changed modules.

Peter
  • 12,274
  • 9
  • 71
  • 86

1 Answers1

3

Advice 1: Don't use %pylab.

Advice 2: don't try to imitate pylab usage it will bite you

If you want to have convenient import create your own package and do from mypackage import *

If you really want a magic that have access to python namespace you should see this question. and add the @needs_local_scope decorator.

Community
  • 1
  • 1
Matt
  • 27,170
  • 6
  • 80
  • 74
  • I've been using `from mypackage import *` but it lacks certain things. (1) It cannot reload changed modules. (2) It won't let me define things differently based on an argument (e.g., I'd like to define a "redraw" function differently based on whether I've specified inline plotting or not. (3) I cannot invoke other magics (like the mysterious `%matplotlib inline`) from the import. – Peter Feb 26 '15 at 09:27
  • Fair enough for (1) though, you could probably have a function that takes arguments, go up one frame and modify globals. But that might be a bit too hackish. – Matt Feb 26 '15 at 17:47