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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.