Warning

This documentation covers a development version of IPython. The development version may differ significantly from the latest stable release.

Important

This documentation covers IPython versions 6.0 and higher. Beginning with version 6.0, IPython stopped supporting compatibility with Python versions lower than 3.3 including all versions of Python 2.7.

If you are looking for an IPython version compatible with Python 2.7, please use the IPython 5.x LTS release and refer to its documentation (LTS is the long term support release).

Module: core.magics.code

Implementation of code management magic functions.

3 Classes

class IPython.core.magics.code.MacroToEdit

Bases: ValueError

class IPython.core.magics.code.InteractivelyDefined(index)

Bases: Exception

Exception for interactively defined variable in magic_edit

__init__(index)
class IPython.core.magics.code.CodeMagics(**kwargs: Any)

Bases: Magics

Magics related to code management (loading, saving, editing, …).

__init__(*args, **kwargs)

Create a configurable given a config config.

Parameters:
  • config (Config) – If this is empty, default values are used. If config is a Config instance, it will be used to configure the instance.

  • parent (Configurable instance, optional) – The parent Configurable instance of this object.

Notes

Subclasses of Configurable must call the __init__() method of Configurable before doing anything else and using super():

class MyConfigurable(Configurable):
    def __init__(self, config=None):
        super(MyConfigurable, self).__init__(config=config)
        # Then any other code you need to finish initialization.

This ensures that instances will be configured properly.

edit(parameter_s='', last_call=['', ''])

Bring up an editor and execute the resulting code.

Usage:

%edit [options] [args]

%edit runs IPython’s editor hook. The default version of this hook is set to call the editor specified by your $EDITOR environment variable. If this isn’t found, it will default to vi under Linux/Unix and to notepad under Windows. See the end of this docstring for how to change the editor hook.

You can also set the value of this editor via the TerminalInteractiveShell.editor option in your configuration file. This is useful if you wish to use a different editor from your typical default with IPython (and for Windows users who typically don’t set environment variables).

This command allows you to conveniently edit multi-line code right in your IPython session.

If called without arguments, %edit opens up an empty editor with a temporary file and will execute the contents of this file when you close it (don’t forget to save it!).

Options:

-n <number>: open the editor at a specified line number. By default, the IPython editor hook uses the unix syntax ‘editor +N filename’, but you can configure this by providing your own modified hook if your favorite editor supports line-number specifications with a different syntax.

-p: this will call the editor with the same data as the previous time it was used, regardless of how long ago (in your current session) it was.

-r: use ‘raw’ input. This option only applies to input taken from the user’s history. By default, the ‘processed’ history is used, so that magics are loaded in their transformed version to valid Python. If this option is given, the raw input as typed as the command line is used instead. When you exit the editor, it will be executed by IPython’s own processor.

-x: do not execute the edited code immediately upon exit. This is mainly useful if you are editing programs which need to be called with command line arguments, which you can then do using %run.

Arguments:

If arguments are given, the following possibilities exist:

  • If the argument is a filename, IPython will load that into the editor. It will execute its contents with execfile() when you exit, loading any code in the file into your interactive namespace.

  • The arguments are ranges of input history, e.g. “7 ~1/4-6”. The syntax is the same as in the %history magic.

  • If the argument is a string variable, its contents are loaded into the editor. You can thus edit any string which contains python code (including the result of previous edits).

  • If the argument is the name of an object (other than a string), IPython will try to locate the file where it was defined and open the editor at the point where it is defined. You can use %edit function to load an editor exactly at the point where ‘function’ is defined, edit it and have the file be executed automatically.

  • If the object is a macro (see %macro for details), this opens up your specified editor with a temporary file containing the macro’s data. Upon exit, the macro is reloaded with the contents of the file.

Note: opening at an exact line is only supported under Unix, and some editors (like kedit and gedit up to Gnome 2.8) do not understand the ‘+NUMBER’ parameter necessary for this feature. Good editors like (X)Emacs, vi, jed, pico and joe all do.

After executing your code, %edit will return as output the code you typed in the editor (except when it was an existing file). This way you can reload the code in further invocations of %edit as a variable, via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of the output.

Note that %edit is also available through the alias %ed.

This is an example of creating a simple function inside the editor and then modifying it. First, start up the editor:

In [1]: edit
Editing... done. Executing edited code...
Out[1]: 'def foo():\n    print("foo() was defined in an editing
session")\n'

We can then call the function foo():

In [2]: foo()
foo() was defined in an editing session

Now we edit foo. IPython automatically loads the editor with the (temporary) file where foo() was previously defined:

In [3]: edit foo
Editing... done. Executing edited code...

And if we call foo() again we get the modified version:

In [4]: foo()
foo() has now been changed!

Here is an example of how to edit a code snippet successive times. First we call the editor:

In [5]: edit
Editing... done. Executing edited code...
hello
Out[5]: "print('hello')\n"

Now we call it again with the previous output (stored in _):

In [6]: edit _
Editing... done. Executing edited code...
hello world
Out[6]: "print('hello world')\n"

Now we call it with the output #8 (stored in _8, also as Out[8]):

In [7]: edit _8
Editing... done. Executing edited code...
hello again
Out[7]: "print('hello again')\n"

Changing the default editor hook:

If you wish to write your own editor hook, you can put it in a configuration file which you load at startup time. The default hook is defined in the IPython.core.hooks module, and you can use that as a starting example for further modifications. That file also has general instructions on how to set a new hook for use once you’ve defined it.

load(arg_s)

Load code into the current frontend.

Usage:

%load [options] source

where source can be a filename, URL, input history range, macro, or element in the user namespace

If no arguments are given, loads the history of this session up to this point.

Options:

-r <lines>: Specify lines or ranges of lines to load from the source. Ranges could be specified as x-y (x..y) or in python-style x:y (x..(y-1)). Both limits x and y can be left blank (meaning the beginning and end of the file, respectively).

-s <symbols>: Specify function or classes to load from python source.

-y : Don’t ask confirmation for loading source above 200 000 characters.

-n : Include the user’s namespace when searching for source code.

This magic command can either take a local filename, a URL, an history range (see %history) or a macro as argument, it will prompt for confirmation before loading source with more than 200 000 characters, unless -y flag is passed or if the frontend does not support raw_input:

%load
%load myscript.py
%load 7-27
%load myMacro
%load http://www.example.com/myscript.py
%load -r 5-10 myscript.py
%load -r 10-20,30,40: foo.py
%load -s MyClass,wonder_function myscript.py
%load -n MyClass
%load -n my_module.wonder_function
loadpy(arg_s)

Alias of %load

%loadpy has gained some flexibility and dropped the requirement of a .py extension. So it has been renamed simply into %load. You can look at %load’s docstring for more info.

pastebin(parameter_s='')

Upload code to dpaste.com, returning the URL.

Usage:

%pastebin [-d “Custom description”][-e 24] 1-7

The argument can be an input history range, a filename, or the name of a string or macro.

If no arguments are given, uploads the history of this session up to this point.

Options:

-d: Pass a custom description. The default will say

“Pasted from IPython”.

-e: Pass number of days for the link to be expired.

The default will be 7 days.

save(parameter_s='')

Save a set of lines or a macro to a given filename.

Usage:

%save [options] filename [history]

Options:

-r: use ‘raw’ input. By default, the ‘processed’ history is used, so that magics are loaded in their transformed version to valid Python. If this option is given, the raw input as typed as the command line is used instead.

-f: force overwrite. If file exists, %save will prompt for overwrite unless -f is given.

-a: append to the file instead of overwriting it.

The history argument uses the same syntax as %history for input ranges, then saves the lines to the filename you specify.

If no ranges are specified, saves history of the current session up to this point.

It adds a ‘.py’ extension to the file if you don’t do so yourself, and it asks for confirmation before overwriting existing files.

If -r option is used, the default extension is .ipy.

3 Functions

IPython.core.magics.code.extract_code_ranges(ranges_str)

Turn a string of range for %%load into 2-tuples of (start, stop) ready to use as a slice of the content split by lines.

Examples

list(extract_input_ranges(“5-10 2”)) [(4, 10), (1, 2)]

IPython.core.magics.code.extract_symbols(code, symbols)

Return a tuple (blocks, not_found) where blocks is a list of code fragments for each symbol parsed from code, and not_found are symbols not found in the code.

For example:

In [1]: code = '''a = 10
   ...: def b(): return 42
   ...: class A: pass'''

In [2]: extract_symbols(code, 'A,b,z')
Out[2]: (['class A: pass\n', 'def b(): return 42\n'], ['z'])
IPython.core.magics.code.strip_initial_indent(lines)

For %load, strip indent from lines until finding an unindented line.

https://github.com/ipython/ipython/issues/9775