IPython Documentation

Table Of Contents

Previous topic

core.compilerop

Next topic

core.completerlib

This Page

core.completer

Module: core.completer

Inheritance diagram for IPython.core.completer:

Word completion for IPython.

This module is a fork of the rlcompleter module in the Python standard library. The original enhancements made to rlcompleter have been sent upstream and were accepted as of Python 2.3, but we need a lot more functionality specific to IPython, so this module will continue to live as an IPython-specific utility.

Original rlcompleter documentation:

This requires the latest extension to the readline module (the completes keywords, built-ins and globals in __main__; when completing NAME.NAME..., it evaluates (!) the expression up to the last dot and completes its attributes.

It’s very cool to do “import string” type “string.”, hit the completion key (twice), and see the list of names defined by the string module!

Tip: to use the tab key as the completion key, call

readline.parse_and_bind(“tab: complete”)

Notes:

  • Exceptions raised by the completer function are ignored (and

generally cause the completion to fail). This is a feature – since readline sets the tty device in raw (or cbreak) mode, printing a traceback wouldn’t work well without some complicated hoopla to save, reset and restore the tty state.

  • The evaluation of the NAME.NAME... form may cause arbitrary

application defined code to be executed if an object with a __getattr__ hook is found. Since it is the responsibility of the application (or the user) to enable this feature, I consider this an acceptable risk. More complicated expressions (e.g. function calls or indexing operations) are not evaluated.

  • GNU readline is also used by the built-in functions input() and

raw_input(), and thus these also benefit/suffer from the completer features. Clearly an interactive application can benefit by specifying its own completer function and using raw_input() for all its input.

  • When the original stdin is not a tty device, GNU readline is never

used, and this module (and the readline module) are silently inactive.

Classes

Bunch

class IPython.core.completer.Bunch

Bases: object

__init__()

x.__init__(...) initializes x; see help(type(x)) for signature

Completer

class IPython.core.completer.Completer(namespace=None, global_namespace=None, config=None, **kwargs)

Bases: IPython.config.configurable.Configurable

__init__(namespace=None, global_namespace=None, config=None, **kwargs)

Create a new completer for the command line.

Completer(namespace=ns,global_namespace=ns2) -> completer instance.

If unspecified, the default namespace where completions are performed is __main__ (technically, __main__.__dict__). Namespaces should be given as dictionaries.

An optional second namespace can be given. This allows the completer to handle cases where both the local and global scopes need to be distinguished.

Completer instances should be used as the completion mechanism of readline via the set_completer() call:

readline.set_completer(Completer(my_namespace).complete)

attr_matches(text)

Compute matches when text contains a dot.

Assuming the text is of the form NAME.NAME....[NAME], and is evaluatable in self.namespace or self.global_namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class instances, class members are are also considered.)

WARNING: this can still invoke arbitrary C code, if an object with a __getattr__ hook is evaluated.

classmethod class_config_section()

Get the config class config section

classmethod class_get_help(inst=None)

Get the help string for this class in ReST format.

If inst is given, it’s current trait values will be used in place of class defaults.

classmethod class_get_trait_help(trait, inst=None)

Get the help string for a single trait.

If inst is given, it’s current trait values will be used in place of the class default.

classmethod class_print_help(inst=None)

Get the help string for a single trait and print it.

classmethod class_trait_names(**metadata)

Get a list of all the names of this classes traits.

This method is just like the trait_names() method, but is unbound.

classmethod class_traits(**metadata)

Get a list of all the traits of this class.

This method is just like the traits() method, but is unbound.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

This follows the same algorithm as traits does and does not allow for any simple way of specifying merely that a metadata name exists, but has any value. This is because get_metadata returns None if a metadata key doesn’t exist.

complete(text, state)

Return the next possible completion for ‘text’.

This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with ‘text’.

config

A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

global_matches(text)

Compute matches when text is a simple name.

Return a list of all keywords, built-in functions and names currently defined in self.namespace or self.global_namespace that match.

greedy

A casting version of the boolean trait.

on_trait_change(handler, name=None, remove=False)

Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Static handlers can be created by creating methods on a HasTraits subclass with the naming convention ‘_[traitname]_changed’. Thus, to create static handler for the trait ‘a’, create the method _a_changed(self, name, old, new) (fewer arguments can be used, see below).

Parameters :

handler : callable

A callable that is called when a trait changes. Its signature can be handler(), handler(name), handler(name, new) or handler(name, old, new).

name : list, str, None

If None, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

remove : bool

If False (the default), then install the handler. If True then unintall it.

trait_metadata(traitname, key)

Get metadata values for trait by key.

trait_names(**metadata)

Get a list of all the names of this classes traits.

traits(**metadata)

Get a list of all the traits of this class.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

This follows the same algorithm as traits does and does not allow for any simple way of specifying merely that a metadata name exists, but has any value. This is because get_metadata returns None if a metadata key doesn’t exist.

update_config(config)

Fire the traits events when the config is updated.

CompletionSplitter

class IPython.core.completer.CompletionSplitter(delims=None)

Bases: object

An object to split an input line in a manner similar to readline.

By having our own implementation, we can expose readline-like completion in a uniform manner to all frontends. This object only needs to be given the line of text to be split and the cursor position on said line, and it returns the ‘word’ to be completed on at the cursor after splitting the entire line.

What characters are used as splitting delimiters can be controlled by setting the delims attribute (this is a property that internally automatically builds the necessary

__init__(delims=None)
get_delims()

Return the string of delimiter characters.

set_delims(delims)

Set the delimiters for line splitting.

split_line(line, cursor_pos=None)

Split a line of text with a cursor at the given position.

IPCompleter

class IPython.core.completer.IPCompleter(shell=None, namespace=None, global_namespace=None, alias_table=None, use_readline=True, config=None, **kwargs)

Bases: IPython.core.completer.Completer

Extension of the completer class with IPython-specific features

__init__(shell=None, namespace=None, global_namespace=None, alias_table=None, use_readline=True, config=None, **kwargs)

IPCompleter() -> completer

Return a completer object suitable for use by the readline library via readline.set_completer().

Inputs:

  • shell: a pointer to the ipython shell itself. This is needed

because this completer knows about magic functions, and those can only be accessed via the ipython instance.

  • namespace: an optional dict where completions are performed.
  • global_namespace: secondary optional dict for completions, to

handle cases (such as IPython embedded inside functions) where both Python scopes are visible.

  • If alias_table is supplied, it should be a dictionary of aliases

to complete.

use_readline : bool, optional
If true, use the readline library. This completer can still function without readline, though in that case callers must provide some extra information on each call about the current line.
alias_matches(text)

Match internal system aliases

all_completions(text)

Wrapper around the complete method for the benefit of emacs and pydb.

attr_matches(text)

Compute matches when text contains a dot.

Assuming the text is of the form NAME.NAME....[NAME], and is evaluatable in self.namespace or self.global_namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class instances, class members are are also considered.)

WARNING: this can still invoke arbitrary C code, if an object with a __getattr__ hook is evaluated.

classmethod class_config_section()

Get the config class config section

classmethod class_get_help(inst=None)

Get the help string for this class in ReST format.

If inst is given, it’s current trait values will be used in place of class defaults.

classmethod class_get_trait_help(trait, inst=None)

Get the help string for a single trait.

If inst is given, it’s current trait values will be used in place of the class default.

classmethod class_print_help(inst=None)

Get the help string for a single trait and print it.

classmethod class_trait_names(**metadata)

Get a list of all the names of this classes traits.

This method is just like the trait_names() method, but is unbound.

classmethod class_traits(**metadata)

Get a list of all the traits of this class.

This method is just like the traits() method, but is unbound.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

This follows the same algorithm as traits does and does not allow for any simple way of specifying merely that a metadata name exists, but has any value. This is because get_metadata returns None if a metadata key doesn’t exist.

complete(text=None, line_buffer=None, cursor_pos=None)

Find completions for the given text and line context.

This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with ‘text’.

Note that both the text and the line_buffer are optional, but at least one of them must be given.

Parameters :

text : string, optional

Text to perform the completion on. If not given, the line buffer is split using the instance’s CompletionSplitter object.

line_buffer : string, optional

If not given, the completer attempts to obtain the current line buffer via readline. This keyword allows clients which are requesting for text completions in non-readline contexts to inform the completer of the entire text.

cursor_pos : int, optional

Index of the cursor in the full line buffer. Should be provided by remote frontends where kernel has no access to frontend state.

Returns :

text : str

Text that was actually used in the completion.

matches : list

A list of completion matches.

config

A trait whose value must be an instance of a specified class.

The value can also be an instance of a subclass of the specified class.

dispatch_custom_completer(text)
file_matches(text)

Match filenames, expanding ~USER type strings.

Most of the seemingly convoluted logic in this completer is an attempt to handle filenames with spaces in them. And yet it’s not quite perfect, because Python’s readline doesn’t expose all of the GNU readline details needed for this to be done correctly.

For a filename with a space in it, the printed completions will be only the parts after what’s already been typed (instead of the full completions, as is normally done). I don’t think with the current (as of Python 2.3) Python readline it’s possible to do better.

global_matches(text)

Compute matches when text is a simple name.

Return a list of all keywords, built-in functions and names currently defined in self.namespace or self.global_namespace that match.

greedy

A casting version of the boolean trait.

magic_matches(text)

Match magics

merge_completions

A casting version of the boolean trait.

omit__names

An enum that whose value must be in a given sequence.

on_trait_change(handler, name=None, remove=False)

Setup a handler to be called when a trait changes.

This is used to setup dynamic notifications of trait changes.

Static handlers can be created by creating methods on a HasTraits subclass with the naming convention ‘_[traitname]_changed’. Thus, to create static handler for the trait ‘a’, create the method _a_changed(self, name, old, new) (fewer arguments can be used, see below).

Parameters :

handler : callable

A callable that is called when a trait changes. Its signature can be handler(), handler(name), handler(name, new) or handler(name, old, new).

name : list, str, None

If None, the handler will apply to all traits. If a list of str, handler will apply to all names in the list. If a str, the handler will apply just to that name.

remove : bool

If False (the default), then install the handler. If True then unintall it.

python_func_kw_matches(text)

Match named parameters (kwargs) of the last open function

python_matches(text)

Match attributes or global python names

rlcomplete(text, state)

Return the state-th possible completion for ‘text’.

This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with ‘text’.

Parameters :

text : string

Text to perform the completion on.

state : int

Counter used by readline.

trait_metadata(traitname, key)

Get metadata values for trait by key.

trait_names(**metadata)

Get a list of all the names of this classes traits.

traits(**metadata)

Get a list of all the traits of this class.

The TraitTypes returned don’t know anything about the values that the various HasTrait’s instances are holding.

This follows the same algorithm as traits does and does not allow for any simple way of specifying merely that a metadata name exists, but has any value. This is because get_metadata returns None if a metadata key doesn’t exist.

update_config(config)

Fire the traits events when the config is updated.

Functions

IPython.core.completer.compress_user(path, tilde_expand, tilde_val)

Does the opposite of expand_user, with its outputs.

IPython.core.completer.expand_user(path)

Expand ‘~’-style usernames in strings.

This is similar to os.path.expanduser(), but it computes and returns extra information that will be useful if the input was being used in computing completions, and you wish to return the completions with the original ‘~’ instead of its expanded value.

Parameters :

path : str

String to be expanded. If no ~ is present, the output is the same as the input.

Returns :

newpath : str

Result of ~ expansion in the input path.

tilde_expand : bool

Whether any expansion was performed or not.

tilde_val : str

The value that ~ was replaced with.

IPython.core.completer.has_open_quotes(s)

Return whether a string has open quotes.

This simply counts whether the number of quote characters of either type in the string is odd.

Returns :

If there is an open quote, the quote character is returned. Else, return :

False. :

IPython.core.completer.mark_dirs(matches)

Mark directories in input list by appending ‘/’ to their names.

IPython.core.completer.protect_filename(s)

Escape a string to protect certain characters.

IPython.core.completer.single_dir_expand(matches)

Recursively expand match lists containing a single dir.