ipapi

Module: ipapi

Inheritance diagram for IPython.ipapi:

IPython customization API

Your one-stop module for configuring & extending ipython

The API will probably break when ipython 1.0 is released, but so will the other configuration method (rc files).

All names prefixed by underscores are for internal use, not part of the public api.

Below is an example that you can just put to a module and import from ipython.

A good practice is to install the config script below as e.g.

~/.ipython/my_private_conf.py

And do

import_mod my_private_conf

in ~/.ipython/ipythonrc

That way the module is imported at startup and you can have all your personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME stuff) in there.

import IPython.ipapi ip = IPython.ipapi.get()

def ankka_f(self, arg):
print ‘Ankka’,self,’says uppercase:’,arg.upper()

ip.expose_magic(‘ankka’,ankka_f)

ip.magic(‘alias sayhi echo “Testing, hi ok”’) ip.magic(‘alias helloworld echo “Hello world”’) ip.system(‘pwd’)

ip.ex(‘import re’) ip.ex(‘’’ def funcci(a,b):

print a+b

print funcci(3,4) ‘’‘) ip.ex(‘funcci(348,9)’)

def jed_editor(self,filename, linenum=None):
print ‘Calling my own editor, jed ... via hook!’ import os if linenum is None: linenum = 0 os.system(‘jed +%d %s’ % (linenum, filename)) print ‘exiting jed’

ip.set_hook(‘editor’,jed_editor)

o = ip.options o.autocall = 2 # FULL autocall mode

print ‘done!’

Classes

DebugTools

class IPython.ipapi.DebugTools(ip)

Used for debugging mishaps in api usage

So far, tracing redefinitions is supported.

__init__(ip)
check_hotname(name)
debug_stack(msg=None)
hotname(name_to_catch)

IPApi

class IPython.ipapi.IPApi(ip)

Bases: object

The actual API class for configuring IPython

You should do all of the IPython configuration by getting an IPApi object with IPython.ipapi.get() and using the attributes and methods of the returned object.

__init__(ip)
db
A handle to persistent dict-like database (a PickleShareDB object)
defalias(name, cmd)

Define a new alias

_ip.defalias(‘bb’,’bldmake bldfiles’)

Creates a new alias named ‘bb’ in ipython user namespace

defmacro(*args)

Define a new macro

2 forms of calling:

mac = _ip.defmacro(‘print “hello”

print “world”’)

(doesn’t put the created macro on user namespace)

_ip.defmacro(‘build’, ‘bldmake bldfiles

abld build winscw udeb’)

(creates a macro named ‘build’ in user namespace)
ev(expr)

Evaluate python expression expr in user namespace

Returns the result of evaluation

ex(cmd)
Execute a normal python statement in user namespace
expand_alias(line)

Expand an alias in the command line

Returns the provided command line, possibly with the first word (command) translated according to alias expansion rules.

[ipython]|16> _ip.expand_aliases(“np myfile.txt”)
<16> ‘q:/opt/np/notepad++.exe myfile.txt’
expose_magic(magicname, func)

Expose own function as magic function for ipython

def foo_impl(self,parameter_s=’‘):
‘My very own magic!. (Use docstrings, IPython reads them).’ print ‘Magic function. Passed parameter is between < >:’ print ‘<%s>’ % parameter_s print ‘The self object is:’,self

ipapi.expose_magic(‘foo’,foo_impl)

get_db()
A handle to persistent dict-like database (a PickleShareDB object)
get_options()
All configurable variables.
itpl(s, depth=1)

Expand Itpl format string s.

Only callable from command line (i.e. prefilter results); If you use in your scripts, you need to use a bigger depth!

load(mod)

Load an extension.

Some modules should (or must) be ‘load()’:ed, rather than just imported.

Loading will do:

  • run init_ipython(ip)
  • run ipython_firstrun(ip)
options
All configurable variables.
runlines(lines)

Run the specified lines in interpreter, honoring ipython directives.

This allows %magic and !shell escape notations.

Takes either all lines in one string or list of lines.

set_next_input(s)

Sets the ‘default’ input string for the next command line.

Requires readline.

Example:

[D:ipython]|1> _ip.set_next_input(“Hello Word”) [D:ipython]|2> Hello Word_ # cursor is here

to_user_ns(vars, interactive=True)

Inject a group of variables into the IPython user namespace.

Inputs:

  • vars: string with variable names separated by whitespace, or a

dict with name/value pairs.

  • interactive: if True (default), the var will be listed with

%whos et. al.

This utility routine is meant to ease interactive debugging work, where you want to easily propagate some internal variable in your code up to the interactive namespace for further exploration.

When you run code via %run, globals in your script become visible at the interactive prompt, but this doesn’t happen for locals inside your own functions and methods. Yet when debugging, it is common to want to explore some internal variables further at the interactive propmt.

Examples:

To use this, you first must obtain a handle on the ipython object as indicated above, via:

import IPython.ipapi ip = IPython.ipapi.get()

Once this is done, inside a routine foo() where you want to expose variables x and y, you do the following:

def foo():

... x = your_computation() y = something_else()

# This pushes x and y to the interactive prompt immediately, even # if this routine crashes on the next line after: ip.to_user_ns(‘x y’) ...

# To expose ALL the local variables from the function, use: ip.to_user_ns(locals())

... # return

If you need to rename variables, the dict input makes it easy. For example, this call exposes variables ‘foo’ as ‘x’ and ‘bar’ as ‘y’ in IPython user namespace:

ip.to_user_ns(dict(x=foo,y=bar))

IPyAutocall

class IPython.ipapi.IPyAutocall

Instances of this class are always autocalled

This happens regardless of ‘autocall’ variable state. Use this to develop macro-like mechanisms.

set_ip(ip)

Will be used to set _ip point to current ipython instance b/f call

Override this method if you don’t want this to happen.

IPythonNotRunning

class IPython.ipapi.IPythonNotRunning(warn=True)

Dummy do-nothing class.

Instances of this class return a dummy attribute on all accesses, which can be called and warns. This makes it easier to write scripts which use the ipapi.get() object for informational purposes to operate both with and without ipython. Obviously code which uses the ipython object for computations will not work, but this allows a wider range of code to transparently work whether ipython is being used or not.

__init__(warn=True)

TryNext

class IPython.ipapi.TryNext(*args, **kwargs)

Bases: exceptions.Exception

Try next hook exception.

Raise this in your hook function to indicate that the next hook handler should be used to handle the operation. If you pass arguments to the constructor those arguments will be used by the next hook instead of the original ones.

__init__(*args, **kwargs)

UsageError

class IPython.ipapi.UsageError

Bases: exceptions.Exception

Error in magic function arguments, etc.

Something that probably won’t warrant a full traceback, but should nevertheless interrupt a macro / batch file.

__init__()
x.__init__(...) initializes x; see x.__class__.__doc__ for signature

Functions

IPython.ipapi.get(allow_dummy=False, dummy_warn=True)

Get an IPApi object.

If allow_dummy is true, returns an instance of IPythonNotRunning instead of None if not running under IPython.

If dummy_warn is false, the dummy instance will be completely silent.

Running this should be the first thing you do when writing extensions that can be imported as normal modules. You can then direct all the configuration operations against the returned object.

IPython.ipapi.launch_new_instance(user_ns=None, shellclass=None)

Make and start a new ipython instance.

This can be called even without having an already initialized ipython session running.

This is also used as the egg entry point for the ‘ipython’ script.

IPython.ipapi.make_session(user_ns=None, shellclass=None)

Makes, but does not launch an IPython session.

Later on you can call obj.mainloop() on the returned object.

Inputs:

  • user_ns(None): a dict to be used as the user’s namespace with initial

data.

WARNING: This should not be run when a session exists already.

IPython.ipapi.make_user_global_ns(ns=None)

Return a valid user global namespace.

Similar to make_user_ns(), but global namespaces are really only needed in embedded applications, where there is a distinction between the user’s interactive namespace and the global one where ipython is running.

This API is currently deprecated. Use ipapi.make_user_namespaces() instead to make both the local and global namespace objects simultaneously.

Parameters:
ns : dict, optional

The current user global namespace. The items in this namespace should be included in the output. If None, an appropriate blank namespace should be created.

Returns:

A true dict to be used as the global namespace of the interpreter.

IPython.ipapi.make_user_namespaces(user_ns=None, user_global_ns=None)

Return a valid local and global user interactive namespaces.

This builds a dict with the minimal information needed to operate as a valid IPython user namespace, which you can pass to the various embedding classes in ipython. The default implementation returns the same dict for both the locals and the globals to allow functions to refer to variables in the namespace. Customized implementations can return different dicts. The locals dictionary can actually be anything following the basic mapping protocol of a dict, but the globals dict must be a true dict, not even a subclass. It is recommended that any custom object for the locals namespace synchronize with the globals dict somehow.

Raises TypeError if the provided globals namespace is not a true dict.

Parameters:
user_ns : dict-like, optional

The current user namespace. The items in this namespace should be included in the output. If None, an appropriate blank namespace should be created.

user_global_ns : dict, optional

The current user global namespace. The items in this namespace should be included in the output. If None, an appropriate blank namespace should be created.

Returns:

A tuple pair of dictionary-like object to be used as the local namespace of the interpreter and a dict to be used as the global namespace.

IPython.ipapi.make_user_ns(user_ns=None)

Return a valid user interactive namespace.

This builds a dict with the minimal information needed to operate as a valid IPython user namespace, which you can pass to the various embedding classes in ipython.

This API is currently deprecated. Use ipapi.make_user_namespaces() instead to make both the local and global namespace objects simultaneously.

Parameters:
user_ns : dict-like, optional

The current user namespace. The items in this namespace should be included in the output. If None, an appropriate blank namespace should be created.

Returns:

A dictionary-like object to be used as the local namespace of the interpreter.