From 1934e25cb2fbaace740d97bc33ab45f01d1be962 2013-11-18 17:53:25 From: Thomas Kluyver Date: 2013-11-18 17:53:25 Subject: [PATCH] Merge pull request #4540 from takluyver/apidocs3 Apidocs3 --- diff --git a/IPython/core/inputsplitter.py b/IPython/core/inputsplitter.py index 97c199d..315a7a9 100644 --- a/IPython/core/inputsplitter.py +++ b/IPython/core/inputsplitter.py @@ -212,13 +212,13 @@ def get_input_encoding(): #----------------------------------------------------------------------------- class InputSplitter(object): - """An object that can accumulate lines of Python source before execution. + r"""An object that can accumulate lines of Python source before execution. This object is designed to be fed python source line-by-line, using - :meth:`push`. It will return on each push whether the currently pushed - code could be executed already. In addition, it provides a method called - :meth:`push_accepts_more` that can be used to query whether more input - can be pushed into a single interactive block. + :meth:`push`. It will return on each push whether the currently pushed + code could be executed already. In addition, it provides a method called + :meth:`push_accepts_more` that can be used to query whether more input + can be pushed into a single interactive block. This is a simple example of how an interactive terminal-based client can use this tool:: diff --git a/IPython/core/interactiveshell.py b/IPython/core/interactiveshell.py index 12b5d31..2fb060d 100644 --- a/IPython/core/interactiveshell.py +++ b/IPython/core/interactiveshell.py @@ -131,9 +131,9 @@ def get_default_colors(): class SeparateUnicode(Unicode): - """A Unicode subclass to validate separate_in, separate_out, etc. + r"""A Unicode subclass to validate separate_in, separate_out, etc. - This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'. + This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``. """ def validate(self, obj, value): @@ -3035,15 +3035,17 @@ class InteractiveShell(SingletonConfigurable): arguments as strings. The number before the / is the session number: ~n goes n back from the current session. - Optional Parameters: - - raw(False): by default, the processed input is used. If this is - true, the raw input history is used instead. + raw : bool, optional + By default, the processed input is used. If this is true, the raw + input history is used instead. - Note that slices can be called with two notations: + Notes + ----- - N:M -> standard python form, means including items N...(M-1). + Slices can be described with two notations: - N-M -> include items N..M (closed endpoint). + * ``N:M`` -> standard python form, means including items N...(M-1). + * ``N-M`` -> include items N..M (closed endpoint). """ lines = self.history_manager.get_range_by_str(range_str, raw=raw) return "\n".join(x for _, _, x in lines) diff --git a/IPython/core/magic.py b/IPython/core/magic.py index a66daf5..f085717 100644 --- a/IPython/core/magic.py +++ b/IPython/core/magic.py @@ -579,24 +579,36 @@ class Magics(Configurable): def parse_options(self, arg_str, opt_str, *long_opts, **kw): """Parse options passed to an argument string. - The interface is similar to that of getopt(), but it returns back a - Struct with the options as keys and the stripped argument string still - as a string. + The interface is similar to that of :func:`getopt.getopt`, but it + returns a :class:`~IPython.utils.struct.Struct` with the options as keys + and the stripped argument string still as a string. arg_str is quoted as a true sys.argv vector by using shlex.split. This allows us to easily expand variables, glob files, quote arguments, etc. - Options: - -mode: default 'string'. If given as 'list', the argument string is - returned as a list (split on whitespace) instead of a string. + Parameters + ---------- + + arg_str : str + The arguments to parse. - -list_all: put all option values in lists. Normally only options + opt_str : str + The options specification. + + mode : str, default 'string' + If given as 'list', the argument string is returned as a list (split + on whitespace) instead of a string. + + list_all : bool, default False + Put all option values in lists. Normally only options appearing more than once are put in a list. - -posix (True): whether to split the input line in POSIX mode or not, - as per the conventions outlined in the shlex module from the - standard library.""" + posix : bool, default True + Whether to split the input line in POSIX mode or not, as per the + conventions outlined in the :mod:`shlex` module from the standard + library. + """ # inject default options at the beginning of the input line caller = sys._getframe(1).f_code.co_name diff --git a/IPython/core/magic_arguments.py b/IPython/core/magic_arguments.py index e83b521..9231609 100644 --- a/IPython/core/magic_arguments.py +++ b/IPython/core/magic_arguments.py @@ -51,18 +51,57 @@ Inheritance diagram: # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- import argparse +import re # Our own imports from IPython.core.error import UsageError +from IPython.utils.decorators import undoc from IPython.utils.process import arg_split from IPython.utils.text import dedent +NAME_RE = re.compile(r"[a-zA-Z][a-zA-Z0-9_-]*$") + +@undoc class MagicHelpFormatter(argparse.RawDescriptionHelpFormatter): - """ A HelpFormatter which dedents but otherwise preserves indentation. + """A HelpFormatter with a couple of changes to meet our needs. """ + # Modified to dedent text. def _fill_text(self, text, width, indent): return argparse.RawDescriptionHelpFormatter._fill_text(self, dedent(text), width, indent) + # Modified to wrap argument placeholders in <> where necessary. + def _format_action_invocation(self, action): + if not action.option_strings: + metavar, = self._metavar_formatter(action, action.dest)(1) + return metavar + + else: + parts = [] + + # if the Optional doesn't take a value, format is: + # -s, --long + if action.nargs == 0: + parts.extend(action.option_strings) + + # if the Optional takes a value, format is: + # -s ARGS, --long ARGS + else: + default = action.dest.upper() + args_string = self._format_args(action, default) + # IPYTHON MODIFICATION: If args_string is not a plain name, wrap + # it in <> so it's valid RST. + if not NAME_RE.match(args_string): + args_string = "<%s>" % args_string + for option_string in action.option_strings: + parts.append('%s %s' % (option_string, args_string)) + + return ', '.join(parts) + + # Override the default prefix ('usage') to our % magic escape, + # in a code block. + def add_usage(self, usage, actions, groups, prefix="::\n\n %"): + super(MagicHelpFormatter, self).add_usage(usage, actions, groups, prefix) + class MagicArgumentParser(argparse.ArgumentParser): """ An ArgumentParser tweaked for use by IPython magics. """ @@ -113,15 +152,8 @@ def construct_parser(magic_func): if result is not None: group = result - # Replace the starting 'usage: ' with IPython's %. - help_text = parser.format_help() - if help_text.startswith('usage: '): - help_text = help_text.replace('usage: ', '%', 1) - else: - help_text = '%' + help_text - # Replace the magic function's docstring with the full help text. - magic_func.__doc__ = help_text + magic_func.__doc__ = parser.format_help() return parser diff --git a/IPython/core/magics/basic.py b/IPython/core/magics/basic.py index c3dbbb4..dcec6be 100644 --- a/IPython/core/magics/basic.py +++ b/IPython/core/magics/basic.py @@ -114,6 +114,7 @@ class BasicMagics(Magics): Examples -------- :: + In [1]: %alias_magic t timeit Created `%t` as an alias for `%timeit`. Created `%%t` as an alias for `%%timeit`. diff --git a/IPython/core/magics/code.py b/IPython/core/magics/code.py index c49149b..35c16de 100644 --- a/IPython/core/magics/code.py +++ b/IPython/core/magics/code.py @@ -275,7 +275,7 @@ class CodeMagics(Magics): where source can be a filename, URL, input history range or macro Options: - -------- + -r : 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 diff --git a/IPython/core/tests/test_magic_arguments.py b/IPython/core/tests/test_magic_arguments.py index 92ae04a..5dea32d 100644 --- a/IPython/core/tests/test_magic_arguments.py +++ b/IPython/core/tests/test_magic_arguments.py @@ -74,44 +74,44 @@ def foo(self, args): def test_magic_arguments(): - assert_equal(magic_foo1.__doc__, '%foo1 [-f FOO]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n') + assert_equal(magic_foo1.__doc__, '::\n\n %foo1 [-f FOO]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n') assert_equal(getattr(magic_foo1, 'argcmd_name', None), None) assert_equal(real_name(magic_foo1), 'foo1') assert_equal(magic_foo1(None, ''), argparse.Namespace(foo=None)) assert hasattr(magic_foo1, 'has_arguments') - assert_equal(magic_foo2.__doc__, '%foo2\n\n A docstring.\n') + assert_equal(magic_foo2.__doc__, '::\n\n %foo2\n\n A docstring.\n') assert_equal(getattr(magic_foo2, 'argcmd_name', None), None) assert_equal(real_name(magic_foo2), 'foo2') assert_equal(magic_foo2(None, ''), argparse.Namespace()) assert hasattr(magic_foo2, 'has_arguments') - assert_equal(magic_foo3.__doc__, '%foo3 [-f FOO] [-b BAR] [-z BAZ]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n\nGroup:\n -b BAR, --bar BAR a grouped argument\n\nSecond Group:\n -z BAZ, --baz BAZ another grouped argument\n') + assert_equal(magic_foo3.__doc__, '::\n\n %foo3 [-f FOO] [-b BAR] [-z BAZ]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n\nGroup:\n -b BAR, --bar BAR a grouped argument\n\nSecond Group:\n -z BAZ, --baz BAZ another grouped argument\n') assert_equal(getattr(magic_foo3, 'argcmd_name', None), None) assert_equal(real_name(magic_foo3), 'foo3') assert_equal(magic_foo3(None, ''), argparse.Namespace(bar=None, baz=None, foo=None)) assert hasattr(magic_foo3, 'has_arguments') - assert_equal(magic_foo4.__doc__, '%foo4 [-f FOO]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n') + assert_equal(magic_foo4.__doc__, '::\n\n %foo4 [-f FOO]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n') assert_equal(getattr(magic_foo4, 'argcmd_name', None), None) assert_equal(real_name(magic_foo4), 'foo4') assert_equal(magic_foo4(None, ''), argparse.Namespace()) assert hasattr(magic_foo4, 'has_arguments') - assert_equal(magic_foo5.__doc__, '%frobnicate [-f FOO]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n') + assert_equal(magic_foo5.__doc__, '::\n\n %frobnicate [-f FOO]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n') assert_equal(getattr(magic_foo5, 'argcmd_name', None), 'frobnicate') assert_equal(real_name(magic_foo5), 'frobnicate') assert_equal(magic_foo5(None, ''), argparse.Namespace(foo=None)) assert hasattr(magic_foo5, 'has_arguments') - assert_equal(magic_magic_foo.__doc__, '%magic_foo [-f FOO]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n') + assert_equal(magic_magic_foo.__doc__, '::\n\n %magic_foo [-f FOO]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n') assert_equal(getattr(magic_magic_foo, 'argcmd_name', None), None) assert_equal(real_name(magic_magic_foo), 'magic_foo') assert_equal(magic_magic_foo(None, ''), argparse.Namespace(foo=None)) assert hasattr(magic_magic_foo, 'has_arguments') - assert_equal(foo.__doc__, '%foo [-f FOO]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n') + assert_equal(foo.__doc__, '::\n\n %foo [-f FOO]\n\n A docstring.\n\noptional arguments:\n -f FOO, --foo FOO an argument\n') assert_equal(getattr(foo, 'argcmd_name', None), None) assert_equal(real_name(foo), 'foo') assert_equal(foo(None, ''), argparse.Namespace(foo=None)) diff --git a/IPython/core/ultratb.py b/IPython/core/ultratb.py index 8ea0874..a932ec9 100644 --- a/IPython/core/ultratb.py +++ b/IPython/core/ultratb.py @@ -2,7 +2,8 @@ """ ultratb.py -- Spice up your tracebacks! -* ColorTB +**ColorTB** + I've always found it a bit hard to visually parse tracebacks in Python. The ColorTB class is a solution to that problem. It colors the different parts of a traceback in a manner similar to what you would expect from a syntax-highlighting @@ -13,7 +14,8 @@ Installation instructions for ColorTB:: import sys,ultratb sys.excepthook = ultratb.ColorTB() -* VerboseTB +**VerboseTB** + I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds of useful info when a traceback occurs. Ping originally had it spit out HTML and intended it for CGI programmers, but why should they have all the fun? I diff --git a/IPython/extensions/cythonmagic.py b/IPython/extensions/cythonmagic.py index bf866f9..2773afd 100644 --- a/IPython/extensions/cythonmagic.py +++ b/IPython/extensions/cythonmagic.py @@ -68,6 +68,7 @@ from IPython.core import magic_arguments from IPython.core.magic import Magics, magics_class, cell_magic from IPython.utils import py3compat from IPython.utils.path import get_ipython_cache_dir +from IPython.utils.text import dedent import Cython from Cython.Compiler.Errors import CompileError @@ -331,9 +332,12 @@ class CythonMagics(Magics): return html __doc__ = __doc__.format( - CYTHON_DOC = ' '*8 + CythonMagics.cython.__doc__, - CYTHON_INLINE_DOC = ' '*8 + CythonMagics.cython_inline.__doc__, - CYTHON_PYXIMPORT_DOC = ' '*8 + CythonMagics.cython_pyximport.__doc__, + # rST doesn't see the -+ flag as part of an option list, so we + # hide it from the module-level docstring. + CYTHON_DOC = dedent(CythonMagics.cython.__doc__\ + .replace('-+, --cplus','--cplus ')), + CYTHON_INLINE_DOC = dedent(CythonMagics.cython_inline.__doc__), + CYTHON_PYXIMPORT_DOC = dedent(CythonMagics.cython_pyximport.__doc__), ) def load_ipython_extension(ip): diff --git a/IPython/extensions/octavemagic.py b/IPython/extensions/octavemagic.py index 1725a34..99b239f 100644 --- a/IPython/extensions/octavemagic.py +++ b/IPython/extensions/octavemagic.py @@ -55,6 +55,7 @@ from IPython.core.magic_arguments import ( argument, magic_arguments, parse_argstring ) from IPython.utils.py3compat import unicode_to_str +from IPython.utils.text import dedent class OctaveMagicError(oct2py.Oct2PyError): pass @@ -145,6 +146,8 @@ class OctaveMagics(Magics): ''' Line-level magic that pulls a variable from Octave. + :: + In [18]: _ = %octave x = [1 2; 3 4]; y = 'hello' In [19]: %octave_pull x y @@ -195,7 +198,7 @@ class OctaveMagics(Magics): def octave(self, line, cell=None, local_ns=None): ''' Execute code in Octave, and pull some of the results back into the - Python namespace. + Python namespace:: In [9]: %octave X = [1 2; 3 4]; mean(X) Out[9]: array([[ 2., 3.]]) @@ -209,9 +212,9 @@ class OctaveMagics(Magics): -2*x^4 - 1*x^3 + 0*x^2 + 1*x^1 + 2 - In the notebook, plots are published as the output of the cell, e.g. + In the notebook, plots are published as the output of the cell, e.g.:: - %octave plot([1 2 3], [4 5 6]) + %octave plot([1 2 3], [4 5 6]) will create a line plot. @@ -360,9 +363,9 @@ class OctaveMagics(Magics): __doc__ = __doc__.format( - OCTAVE_DOC = ' '*8 + OctaveMagics.octave.__doc__, - OCTAVE_PUSH_DOC = ' '*8 + OctaveMagics.octave_push.__doc__, - OCTAVE_PULL_DOC = ' '*8 + OctaveMagics.octave_pull.__doc__ + OCTAVE_DOC = dedent(OctaveMagics.octave.__doc__), + OCTAVE_PUSH_DOC = dedent(OctaveMagics.octave_push.__doc__), + OCTAVE_PULL_DOC = dedent(OctaveMagics.octave_pull.__doc__) ) diff --git a/IPython/extensions/rmagic.py b/IPython/extensions/rmagic.py index 0b27a19..a5210e1 100644 --- a/IPython/extensions/rmagic.py +++ b/IPython/extensions/rmagic.py @@ -75,6 +75,7 @@ from IPython.core.magic_arguments import ( from IPython.external.simplegeneric import generic from IPython.utils.py3compat import (str_to_unicode, unicode_to_str, PY3, unicode_type) +from IPython.utils.text import dedent class RInterpreterError(ri.RRuntimeError): """An error when running R code in a %%R magic cell.""" @@ -679,10 +680,10 @@ class RMagics(Magics): return self.Rconverter(result, dataframe=False) __doc__ = __doc__.format( - R_DOC = ' '*8 + RMagics.R.__doc__, - RPUSH_DOC = ' '*8 + RMagics.Rpush.__doc__, - RPULL_DOC = ' '*8 + RMagics.Rpull.__doc__, - RGET_DOC = ' '*8 + RMagics.Rget.__doc__ + R_DOC = dedent(RMagics.R.__doc__), + RPUSH_DOC = dedent(RMagics.Rpush.__doc__), + RPULL_DOC = dedent(RMagics.Rpull.__doc__), + RGET_DOC = dedent(RMagics.Rget.__doc__) ) diff --git a/IPython/html/services/notebooks/handlers.py b/IPython/html/services/notebooks/handlers.py index e52e559..69d0ac4 100644 --- a/IPython/html/services/notebooks/handlers.py +++ b/IPython/html/services/notebooks/handlers.py @@ -145,9 +145,11 @@ class NotebookHandler(IPythonHandler): POST creates new notebooks. The server always decides on the notebook name. - POST /api/notebooks/path : new untitled notebook in path - If content specified, upload a notebook, otherwise start empty. - POST /api/notebooks/path?copy=OtherNotebook.ipynb : new copy of OtherNotebook in path + POST /api/notebooks/path + New untitled notebook in path. If content specified, upload a + notebook, otherwise start empty. + POST /api/notebooks/path?copy=OtherNotebook.ipynb + New copy of OtherNotebook in path """ if name is not None: @@ -171,14 +173,15 @@ class NotebookHandler(IPythonHandler): def put(self, path='', name=None): """Saves the notebook in the location specified by name and path. - PUT /api/notebooks/path/Name.ipynb : Save notebook at path/Name.ipynb - Notebook structure is specified in `content` key of JSON request body. - If content is not specified, create a new empty notebook. - PUT /api/notebooks/path/Name.ipynb?copy=OtherNotebook.ipynb : copy OtherNotebook to Name + PUT is very similar to POST, but the requester specifies the name, + whereas with POST, the server picks the name. - POST and PUT are basically the same. The only difference: - - - with POST, server always picks the name, with PUT the requester does + PUT /api/notebooks/path/Name.ipynb + Save notebook at ``path/Name.ipynb``. Notebook structure is specified + in `content` key of JSON request body. If content is not specified, + create a new empty notebook. + PUT /api/notebooks/path/Name.ipynb?copy=OtherNotebook.ipynb + Copy OtherNotebook to Name """ if name is None: raise web.HTTPError(400, "Only PUT to full names. Use POST for directories.") diff --git a/IPython/kernel/channels.py b/IPython/kernel/channels.py index d514ece..49845bb 100644 --- a/IPython/kernel/channels.py +++ b/IPython/kernel/channels.py @@ -133,9 +133,9 @@ class ZMQSocketChannel(Thread): def stop(self): """Stop the channel's event loop and join its thread. - This calls :method:`Thread.join` and returns when the thread + This calls :meth:`~threading.Thread.join` and returns when the thread terminates. :class:`RuntimeError` will be raised if - :method:`self.start` is called again. + :meth:`~threading.Thread.start` is called again. """ self.join() @@ -430,7 +430,7 @@ class IOPubChannel(ZMQSocketChannel): def flush(self, timeout=1.0): """Immediately processes all pending messages on the iopub channel. - Callers should use this method to ensure that :method:`call_handlers` + Callers should use this method to ensure that :meth:`call_handlers` has been called for all messages that have been received on the 0MQ SUB socket of this channel. diff --git a/IPython/kernel/client.py b/IPython/kernel/client.py index a0c6a3e..128eead 100644 --- a/IPython/kernel/client.py +++ b/IPython/kernel/client.py @@ -102,7 +102,7 @@ class KernelClient(LoggingConfigurable, ConnectionFileMixin): This will create the channels if they do not exist and then start them (their activity runs in a thread). If port numbers of 0 are being used (random ports) then you must first call - :method:`start_kernel`. If the channels have been stopped and you + :meth:`start_kernel`. If the channels have been stopped and you call this, :class:`RuntimeError` will be raised. """ if shell: diff --git a/IPython/kernel/manager.py b/IPython/kernel/manager.py index 0c9f0bd..c1beefd 100644 --- a/IPython/kernel/manager.py +++ b/IPython/kernel/manager.py @@ -185,8 +185,8 @@ class KernelManager(LoggingConfigurable, ConnectionFileMixin): If random ports (port=0) are being used, this method must be called before the channels are created. - Parameters: - ----------- + Parameters + ---------- **kw : optional keyword arguments that are passed down to build the kernel_cmd and launching the kernel (e.g. Popen kwargs). @@ -227,8 +227,8 @@ class KernelManager(LoggingConfigurable, ConnectionFileMixin): 2. If that fails, the kernel is shutdown forcibly by sending it a signal. - Parameters: - ----------- + Parameters + ---------- now : bool Should the kernel be forcible killed *now*. This skips the first, nice shutdown attempt. diff --git a/IPython/kernel/zmq/parentpoller.py b/IPython/kernel/zmq/parentpoller.py index 7e38c34..b745b02 100644 --- a/IPython/kernel/zmq/parentpoller.py +++ b/IPython/kernel/zmq/parentpoller.py @@ -48,8 +48,8 @@ class ParentPollerWindows(Thread): """ Create the poller. At least one of the optional parameters must be provided. - Parameters: - ----------- + Parameters + ---------- interrupt_handle : HANDLE (int), optional If provided, the program will generate a Ctrl+C event when this handle is signaled. diff --git a/IPython/kernel/zmq/session.py b/IPython/kernel/zmq/session.py index 50d29a4..eddf968 100644 --- a/IPython/kernel/zmq/session.py +++ b/IPython/kernel/zmq/session.py @@ -527,11 +527,13 @@ class Session(Configurable): Returns ------- msg_list : list - The list of bytes objects to be sent with the format: - [ident1,ident2,...,DELIM,HMAC,p_header,p_parent,p_metadata,p_content, - buffer1,buffer2,...]. In this list, the p_* entities are - the packed or serialized versions, so if JSON is used, these - are utf8 encoded JSON strings. + The list of bytes objects to be sent with the format:: + + [ident1, ident2, ..., DELIM, HMAC, p_header, p_parent, + p_metadata, p_content, buffer1, buffer2, ...] + + In this list, the ``p_*`` entities are the packed or serialized + versions, so if JSON is used, these are utf8 encoded JSON strings. """ content = msg.get('content', {}) if content is None: @@ -781,8 +783,8 @@ class Session(Configurable): methods work with full message lists, whereas pack/unpack work with the individual message parts in the message list. - Parameters: - ----------- + Parameters + ---------- msg_list : list of bytes or Message objects The list of message parts of the form [HMAC,p_header,p_parent, p_metadata,p_content,buffer1,buffer2,...]. diff --git a/IPython/kernel/zmq/zmqshell.py b/IPython/kernel/zmq/zmqshell.py index 9fb2e87..9a5f38c 100644 --- a/IPython/kernel/zmq/zmqshell.py +++ b/IPython/kernel/zmq/zmqshell.py @@ -197,116 +197,64 @@ class KernelMagics(Magics): temporary file and will execute the contents of this file when you close it (don't forget to save it!). - Options: - -n : 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. + -n + 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. - -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. + -p + 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. Arguments: If arguments are given, the following possibilites exist: - The arguments are numbers or pairs of colon-separated numbers (like - 1 4:8 9). These are interpreted as lines of previous input to be - loaded into the editor. The syntax is the same of the %macro command. + 1 4:8 9). These are interpreted as lines of previous input to be + loaded into the editor. The syntax is the same of the %macro command. - If the argument doesn't start with a number, it is evaluated as a - variable and its contents loaded into the editor. You can thus edit - any string which contains python code (including the result of - previous edits). + variable and its contents 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. + 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. + 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. + 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. - If the argument is not found as a variable, IPython will look for a - file with that name (adding .py if necessary) and load it into the - editor. It will execute its contents with execfile() when you exit, - loading any code in the file into your interactive namespace. + file with that name (adding .py if necessary) and load it into the + editor. It will execute its contents with execfile() when you exit, + loading any code in the file into your interactive namespace. - 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 _ or Out[], where is the prompt number of - the output. + Unlike in the terminal, this is designed to use a GUI editor, and we do + not know when it has closed. So the file you edit will not be + automatically executed or printed. 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]: ed - 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]: ed 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]: ed - Editing... done. Executing edited code... - hello - Out[5]: "print 'hello'n" - - Now we call it again with the previous output (stored in _): - - In [6]: ed _ - 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]: ed _8 - Editing... done. Executing edited code... - hello again - Out[7]: "print 'hello again'n" """ opts,args = self.parse_options(parameter_s,'prn:') diff --git a/IPython/lib/backgroundjobs.py b/IPython/lib/backgroundjobs.py index e84e52a..b843dcb 100644 --- a/IPython/lib/backgroundjobs.py +++ b/IPython/lib/backgroundjobs.py @@ -360,13 +360,14 @@ class BackgroundJobBase(threading.Thread): The derived classes must implement: - Their own __init__, since the one here raises NotImplementedError. The - derived constructor must call self._init() at the end, to provide common - initialization. + derived constructor must call self._init() at the end, to provide common + initialization. - A strform attribute used in calls to __str__. - A call() method, which will make the actual execution call and must - return a value to be held in the 'result' field of the job object.""" + return a value to be held in the 'result' field of the job object. + """ # Class constants for status, in string and as numerical codes (when # updating jobs lists, we don't want to do string comparisons). This will @@ -378,6 +379,10 @@ class BackgroundJobBase(threading.Thread): stat_dead_c = -1 def __init__(self): + """Must be implemented in subclasses. + + Subclasses must call :meth:`_init` for standard initialisation. + """ raise NotImplementedError("This class can not be instantiated directly.") def _init(self): diff --git a/IPython/lib/display.py b/IPython/lib/display.py index c87e3d7..9d3c949 100644 --- a/IPython/lib/display.py +++ b/IPython/lib/display.py @@ -49,22 +49,23 @@ class Audio(DisplayObject): Examples -------- - - # Generate a sound - import numpy as np - framerate = 44100 - t = np.linspace(0,5,framerate*5) - data = np.sin(2*np.pi*220*t) + np.sin(2*np.pi*224*t)) - Audio(data,rate=framerate) - - Audio("http://www.nch.com.au/acm/8k16bitpcm.wav") - Audio(url="http://www.w3schools.com/html/horse.ogg") - - Audio('/path/to/sound.wav') - Audio(filename='/path/to/sound.ogg') - - Audio(b'RAW_WAV_DATA..) - Audio(data=b'RAW_WAV_DATA..) + :: + + # Generate a sound + import numpy as np + framerate = 44100 + t = np.linspace(0,5,framerate*5) + data = np.sin(2*np.pi*220*t) + np.sin(2*np.pi*224*t)) + Audio(data,rate=framerate) + + Audio("http://www.nch.com.au/acm/8k16bitpcm.wav") # From URL + Audio(url="http://www.w3schools.com/html/horse.ogg") + + Audio('/path/to/sound.wav') # From file + Audio(filename='/path/to/sound.ogg') + + Audio(b'RAW_WAV_DATA..) # From bytes + Audio(data=b'RAW_WAV_DATA..) """ _read_flags = 'rb' @@ -198,22 +199,21 @@ class IFrame(object): class YouTubeVideo(IFrame): """Class for embedding a YouTube Video in an IPython session, based on its video id. - e.g. to embed the video on this page: - - http://www.youtube.com/watch?v=foo + e.g. to embed the video from http://www.youtube.com/watch?v=foo , you would + do:: - you would do: + vid = YouTubeVideo("foo") + display(vid) - vid = YouTubeVideo("foo") - display(vid) + To start from 30 seconds:: - To start from 30 seconds: + vid = YouTubeVideo("abc", start=30) + display(vid) - vid = YouTubeVideo("abc", start=30) - display(vid) + To calculate seconds from time as hours, minutes, seconds use + :class:`datetime.timedelta`:: - To calculate seconds from time as hours, minutes, seconds use: - start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds()) + start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds()) Other parameters can be provided as documented at https://developers.google.com/youtube/player_parameters#parameter-subheader @@ -316,17 +316,15 @@ class FileLink(object): class FileLinks(FileLink): """Class for embedding local file links in an IPython session, based on path - e.g. to embed links to files that were generated in the IPython notebook under my/data - - you would do: + e.g. to embed links to files that were generated in the IPython notebook + under ``my/data``, you would do:: - local_files = FileLinks("my/data") - display(local_files) + local_files = FileLinks("my/data") + display(local_files) - or in the HTML notebook, just - - FileLinks("my/data") + or in the HTML notebook, just:: + FileLinks("my/data") """ def __init__(self, path, @@ -337,35 +335,38 @@ class FileLinks(FileLink): notebook_display_formatter=None, terminal_display_formatter=None): """ - included_suffixes : list of filename suffixes to include when - formatting output [default: include all files] - - See the FileLink (baseclass of LocalDirectory) docstring for - information on additional parameters. - - notebook_display_formatter : func used to format links for display - in the notebook. See discussion of formatter function below. - - terminal_display_formatter : func used to format links for display - in the terminal. See discussion of formatter function below. - - - Passing custom formatter functions - ---------------------------------- - Formatter functions must be of the form: - f(dirname, fnames, included_suffixes) - dirname : the name of a directory (a string), - fnames : a list of the files in that directory - included_suffixes : a list of the file suffixes that should be - included in the output (passing None means - to include all suffixes in the output in - the built-in formatters) - - returns a list of lines that should will be print in the - notebook (if passing notebook_display_formatter) or the terminal - (if passing terminal_display_formatter). This function is iterated - over for each directory in self.path. Default formatters are in - place, can be passed here to support alternative formatting. + See :class:`FileLink` for the ``path``, ``url_prefix``, + ``result_html_prefix`` and ``result_html_suffix`` parameters. + + included_suffixes : list + Filename suffixes to include when formatting output [default: include + all files] + + notebook_display_formatter : function + Used to format links for display in the notebook. See discussion of + formatter functions below. + + terminal_display_formatter : function + Used to format links for display in the terminal. See discussion of + formatter functions below. + + Formatter functions must be of the form:: + + f(dirname, fnames, included_suffixes) + + dirname : str + The name of a directory + fnames : list + The files in that directory + included_suffixes : list + The file suffixes that should be included in the output (passing None + meansto include all suffixes in the output in the built-in formatters) + + The function should return a list of lines that will be printed in the + notebook (if passing notebook_display_formatter) or the terminal (if + passing terminal_display_formatter). This function is iterated over for + each directory in self.path. Default formatters are in place, can be + passed here to support alternative formatting. """ if isfile(path): diff --git a/IPython/lib/security.py b/IPython/lib/security.py index d5c61cb..eab67bb 100644 --- a/IPython/lib/security.py +++ b/IPython/lib/security.py @@ -49,8 +49,8 @@ def passwd(passphrase=None, algorithm='sha1'): Examples -------- - In [1]: passwd('mypassword') - Out[1]: 'sha1:7cf3:b7d6da294ea9592a9480c8f52e63cd42cfb9dd12' + >>> passwd('mypassword') + 'sha1:7cf3:b7d6da294ea9592a9480c8f52e63cd42cfb9dd12' """ if passphrase is None: @@ -89,16 +89,14 @@ def passwd_check(hashed_passphrase, passphrase): Examples -------- - In [1]: from IPython.lib.security import passwd_check - - In [2]: passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', - ...: 'mypassword') - Out[2]: True - - In [3]: passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', - ...: 'anotherpassword') - Out[3]: False - + >>> from IPython.lib.security import passwd_check + >>> passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', + ... 'mypassword') + True + + >>> passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', + ... 'anotherpassword') + False """ try: algorithm, salt, pw_digest = hashed_passphrase.split(':', 2) diff --git a/IPython/nbconvert/exporters/export.py b/IPython/nbconvert/exporters/export.py index 21aeeee..e9fff80 100644 --- a/IPython/nbconvert/exporters/export.py +++ b/IPython/nbconvert/exporters/export.py @@ -16,7 +16,7 @@ Module containing single call export functions. from functools import wraps from IPython.nbformat.v3.nbbase import NotebookNode -from IPython.config import Config +from IPython.utils.decorators import undoc from IPython.utils.py3compat import string_types from .exporter import Exporter @@ -32,18 +32,20 @@ from .rst import RSTExporter # Classes #----------------------------------------------------------------------------- +@undoc def DocDecorator(f): #Set docstring of function f.__doc__ = f.__doc__ + """ - nb : Notebook node + nb : :class:`~{nbnode_mod}.NotebookNode` + The notebook to export. config : config (optional, keyword arg) User configuration instance. resources : dict (optional, keyword arg) Resources used in the conversion process. Returns - ---------- + ------- tuple- output, resources, exporter_instance output : str Jinja 2 output. This is the resulting converted notebook. @@ -55,8 +57,10 @@ def DocDecorator(f): to caller because it provides a 'file_extension' property which specifies what extension the output should be saved as. + Notes + ----- WARNING: API WILL CHANGE IN FUTURE RELEASES OF NBCONVERT - """ + """.format(nbnode_mod=NotebookNode.__module__) @wraps(f) def decorator(*args, **kwargs): @@ -92,11 +96,13 @@ def export(exporter, nb, **kw): """ Export a notebook object using specific exporter class. - exporter : Exporter class type or instance - Class type or instance of the exporter that should be used. If the - method initializes it's own instance of the class, it is ASSUMED that - the class type provided exposes a constructor (__init__) with the same - signature as the base Exporter class. + Parameters + ---------- + exporter : class:`~IPython.nbconvert.exporters.exporter.Exporter` class or instance + Class type or instance of the exporter that should be used. If the + method initializes it's own instance of the class, it is ASSUMED that + the class type provided exposes a constructor (``__init__``) with the same + signature as the base Exporter class. """ #Check arguments @@ -152,6 +158,8 @@ def export_by_name(format_name, nb, **kw): (Inspect) is used to find the template's corresponding explicit export method defined in this module. That method is then called directly. + Parameters + ---------- format_name : str Name of the template style to export to. """ diff --git a/IPython/nbconvert/exporters/exporter.py b/IPython/nbconvert/exporters/exporter.py index 3ac0712..08a0918 100644 --- a/IPython/nbconvert/exporters/exporter.py +++ b/IPython/nbconvert/exporters/exporter.py @@ -32,9 +32,6 @@ from IPython.utils.traitlets import MetaHasTraits, Unicode, List from IPython.utils.importstring import import_item from IPython.utils import text, py3compat -from IPython.nbconvert import preprocessors as nbpreprocessors - - #----------------------------------------------------------------------------- # Class #----------------------------------------------------------------------------- @@ -96,17 +93,20 @@ class Exporter(LoggingConfigurable): def default_config(self): return Config() - + @nbformat.docstring_nbformat_mod def from_notebook_node(self, nb, resources=None, **kw): """ Convert a notebook from a notebook node instance. Parameters ---------- - nb : Notebook node - resources : dict (**kw) - of additional resources that can be accessed read/write by - preprocessors. + nb : :class:`~{nbformat_mod}.nbbase.NotebookNode` + Notebook node + resources : dict + Additional resources that can be accessed read/write by + preprocessors and filters. + **kw + Ignored (?) """ nb_copy = copy.deepcopy(nb) resources = self._init_resources(resources) diff --git a/IPython/nbconvert/exporters/templateexporter.py b/IPython/nbconvert/exporters/templateexporter.py index e50bd36..cbc80e9 100644 --- a/IPython/nbconvert/exporters/templateexporter.py +++ b/IPython/nbconvert/exporters/templateexporter.py @@ -27,6 +27,7 @@ from IPython.utils.traitlets import MetaHasTraits, Unicode, List, Dict, Any from IPython.utils.importstring import import_item from IPython.utils import py3compat, text +from IPython.nbformat.current import docstring_nbformat_mod from IPython.nbconvert import filters from .exporter import Exporter @@ -186,17 +187,19 @@ class TemplateExporter(Exporter): else: self.log.info("Loaded template %s", try_name) break - + + @docstring_nbformat_mod def from_notebook_node(self, nb, resources=None, **kw): """ Convert a notebook from a notebook node instance. Parameters ---------- - nb : Notebook node - resources : dict (**kw) - of additional resources that can be accessed read/write by - preprocessors and filters. + nb : :class:`~{nbformat_mod}.nbbase.NotebookNode` + Notebook node + resources : dict + Additional resources that can be accessed read/write by + preprocessors and filters. """ nb_copy, resources = super(TemplateExporter, self).from_notebook_node(nb, resources, **kw) diff --git a/IPython/nbconvert/nbconvertapp.py b/IPython/nbconvert/nbconvertapp.py index 85ab4a4..1c8a62c 100755 --- a/IPython/nbconvert/nbconvertapp.py +++ b/IPython/nbconvert/nbconvertapp.py @@ -77,7 +77,7 @@ nbconvert_flags.update({ class NbConvertApp(BaseIPythonApplication): - """Application used to convert to and from notebook file type (*.ipynb)""" + """Application used to convert from notebook file type (``*.ipynb``)""" name = 'ipython-nbconvert' aliases = nbconvert_aliases diff --git a/IPython/nbconvert/preprocessors/coalescestreams.py b/IPython/nbconvert/preprocessors/coalescestreams.py index 873c559..3fa4379 100644 --- a/IPython/nbconvert/preprocessors/coalescestreams.py +++ b/IPython/nbconvert/preprocessors/coalescestreams.py @@ -18,8 +18,7 @@ def cell_preprocessor(function): """ Wrap a function to be executed on all cells of a notebook - Wrapped Parameters - ------------------ + The wrapped function should have these parameters: cell : NotebookNode cell Notebook cell being processed diff --git a/IPython/nbconvert/tests/base.py b/IPython/nbconvert/tests/base.py index c84cde8..a19372c 100644 --- a/IPython/nbconvert/tests/base.py +++ b/IPython/nbconvert/tests/base.py @@ -88,8 +88,8 @@ class TestsBase(unittest.TestCase): Replace "ii" with "i" in the string "Hiiii" yields "Hii" Another replacement cds "Hi" (the desired output) - Parameters: - ----------- + Parameters + ---------- text : string Text to replace in. search : string @@ -141,8 +141,8 @@ class TestsBase(unittest.TestCase): Execute a, IPython shell command, listening for both Errors and non-zero return codes. - PARAMETERS: - ----------- + Parameters + ---------- parameters : str List of parameters to pass to IPython. ignore_return_code : optional bool (default False) diff --git a/IPython/nbformat/convert.py b/IPython/nbformat/convert.py index b4c5488..0f0d214 100644 --- a/IPython/nbformat/convert.py +++ b/IPython/nbformat/convert.py @@ -31,8 +31,8 @@ def convert(nb, to_version): a v4. Also assumes that all conversions can be made in one step increments between major versions and ignores minor revisions. - PARAMETERS: - ----------- + Parameters + ---------- nb : NotebookNode to_version : int Major revision to convert the notebook to. Can either be an upgrade or diff --git a/IPython/nbformat/current.py b/IPython/nbformat/current.py index 8067c73..5223c4e 100644 --- a/IPython/nbformat/current.py +++ b/IPython/nbformat/current.py @@ -30,6 +30,7 @@ from IPython.nbformat.v3 import ( parse_filename, new_metadata, new_author, new_heading_cell, nbformat, nbformat_minor, to_notebook_json ) +from IPython.nbformat import v3 as _v_latest from .reader import reads as reader_reads from .reader import versions @@ -41,6 +42,16 @@ from .convert import convert current_nbformat = nbformat current_nbformat_minor = nbformat_minor +current_nbformat_module = _v_latest.__name__ + +def docstring_nbformat_mod(func): + """Decorator for docstrings referring to classes/functions accessed through + nbformat.current. + + Put {nbformat_mod} in the docstring in place of 'IPython.nbformat.v3'. + """ + func.__doc__ = func.__doc__.format(nbformat_mod=current_nbformat_module) + return func class NBFormatError(ValueError): diff --git a/IPython/parallel/apps/launcher.py b/IPython/parallel/apps/launcher.py index c5582aa..17b3fea 100644 --- a/IPython/parallel/apps/launcher.py +++ b/IPython/parallel/apps/launcher.py @@ -1308,9 +1308,10 @@ class HTCondorLauncher(BatchSystemLauncher): this - the mechanism of shebanged scripts means that the python binary will be launched with argv[0] set to the *location of the ip{cluster, engine, controller} scripts on the remote node*. This means you need to take care that: - a. Your remote nodes have their paths configured correctly, with the ipengine and ipcontroller - of the python environment you wish to execute code in having top precedence. - b. This functionality is untested on Windows. + + a. Your remote nodes have their paths configured correctly, with the ipengine and ipcontroller + of the python environment you wish to execute code in having top precedence. + b. This functionality is untested on Windows. If you need different behavior, consider making you own template. """ diff --git a/IPython/parallel/client/magics.py b/IPython/parallel/client/magics.py index b74403b..b73c7a7 100644 --- a/IPython/parallel/client/magics.py +++ b/IPython/parallel/client/magics.py @@ -46,6 +46,7 @@ from IPython.core.error import UsageError from IPython.core.magic import Magics from IPython.core import magic_arguments from IPython.testing.skipdoctest import skip_doctest +from IPython.utils.text import dedent #----------------------------------------------------------------------------- # Definitions of magic functions for use with IPython @@ -108,13 +109,11 @@ def output_args(f): Choices are: - type: group outputs of all engines by type (stdout, stderr, displaypub, etc.). - - engine: display all output for each engine together. - - order: like type, but individual displaypub output from each engine is collated. - For example, if multiple plots are generated by each engine, the first - figure of each engine will be displayed, then the second of each, etc. + **type**: group outputs of all engines by type (stdout, stderr, displaypub, etc.). + **engine**: display all output for each engine together. + **order**: like type, but individual displaypub output from each engine is collated. + For example, if multiple plots are generated by each engine, the first + figure of each engine will be displayed, then the second of each, etc. """ ), magic_arguments.argument('-o', '--out', dest='save_name', type=str, @@ -435,8 +434,8 @@ class ParallelMagics(Magics): __doc__ = __doc__.format( - AUTOPX_DOC = ' '*8 + ParallelMagics.autopx.__doc__, - PX_DOC = ' '*8 + ParallelMagics.px.__doc__, - RESULT_DOC = ' '*8 + ParallelMagics.result.__doc__, - CONFIG_DOC = ' '*8 + ParallelMagics.pxconfig.__doc__, + AUTOPX_DOC = dedent(ParallelMagics.autopx.__doc__), + PX_DOC = dedent(ParallelMagics.px.__doc__), + RESULT_DOC = dedent(ParallelMagics.result.__doc__), + CONFIG_DOC = dedent(ParallelMagics.pxconfig.__doc__), ) diff --git a/IPython/parallel/client/remotefunction.py b/IPython/parallel/client/remotefunction.py index 026c0d0..45c6264 100644 --- a/IPython/parallel/client/remotefunction.py +++ b/IPython/parallel/client/remotefunction.py @@ -152,8 +152,10 @@ class ParallelFunction(RemoteFunction): dist : str [default: 'b'] The key for which mapObject to use to distribute sequences options are: - * 'b' : use contiguous chunks in order - * 'r' : use round-robin striping + + * 'b' : use contiguous chunks in order + * 'r' : use round-robin striping + block : bool [default: None] Whether to wait for results or not. The default behavior is to use the current `block` attribute of `view` @@ -162,7 +164,8 @@ class ParallelFunction(RemoteFunction): ordered : bool [default: True] Whether the result should be kept in order. If False, results become available as they arrive, regardless of submission order. - **flags : remaining kwargs are passed to View.temp_flags + **flags + remaining kwargs are passed to View.temp_flags """ chunksize = None diff --git a/IPython/parallel/client/view.py b/IPython/parallel/client/view.py index d08f03c..57a7154 100644 --- a/IPython/parallel/client/view.py +++ b/IPython/parallel/client/view.py @@ -221,30 +221,27 @@ class View(HasTraits): raise NotImplementedError("Implement in subclasses") def apply(self, f, *args, **kwargs): - """calls f(*args, **kwargs) on remote engines, returning the result. + """calls ``f(*args, **kwargs)`` on remote engines, returning the result. This method sets all apply flags via this View's attributes. - if self.block is False: - returns AsyncResult - else: - returns actual result of f(*args, **kwargs) + Returns :class:`~IPython.parallel.client.asyncresult.AsyncResult` + instance if ``self.block`` is False, otherwise the return value of + ``f(*args, **kwargs)``. """ return self._really_apply(f, args, kwargs) def apply_async(self, f, *args, **kwargs): - """calls f(*args, **kwargs) on remote engines in a nonblocking manner. + """calls ``f(*args, **kwargs)`` on remote engines in a nonblocking manner. - returns AsyncResult + Returns :class:`~IPython.parallel.client.asyncresult.AsyncResult` instance. """ return self._really_apply(f, args, kwargs, block=False) @spin_after def apply_sync(self, f, *args, **kwargs): - """calls f(*args, **kwargs) on remote engines in a blocking manner, + """calls ``f(*args, **kwargs)`` on remote engines in a blocking manner, returning the result. - - returns: actual result of f(*args, **kwargs) """ return self._really_apply(f, args, kwargs, block=True) @@ -320,8 +317,7 @@ class View(HasTraits): def get_result(self, indices_or_msg_ids=None): """return one or more results, specified by history index or msg_id. - See client.get_result for details. - + See :meth:`IPython.parallel.client.client.Client.get_result` for details. """ if indices_or_msg_ids is None: @@ -345,9 +341,9 @@ class View(HasTraits): raise NotImplementedError def map_async(self, f, *sequences, **kwargs): - """Parallel version of builtin `map`, using this view's engines. + """Parallel version of builtin :func:`python:map`, using this view's engines. - This is equivalent to map(...block=False) + This is equivalent to ``map(...block=False)``. See `self.map` for details. """ @@ -357,9 +353,9 @@ class View(HasTraits): return self.map(f,*sequences,**kwargs) def map_sync(self, f, *sequences, **kwargs): - """Parallel version of builtin `map`, using this view's engines. + """Parallel version of builtin :func:`python:map`, using this view's engines. - This is equivalent to map(...block=True) + This is equivalent to ``map(...block=True)``. See `self.map` for details. """ @@ -369,7 +365,7 @@ class View(HasTraits): return self.map(f,*sequences,**kwargs) def imap(self, f, *sequences, **kwargs): - """Parallel version of `itertools.imap`. + """Parallel version of :func:`itertools.imap`. See `self.map` for details. @@ -575,7 +571,7 @@ class DirectView(View): @sync_results def map(self, f, *sequences, **kwargs): - """view.map(f, *sequences, block=self.block) => list|AsyncMapResult + """``view.map(f, *sequences, block=self.block)`` => list|AsyncMapResult Parallel version of builtin `map`, using this View's `targets`. @@ -597,14 +593,14 @@ class DirectView(View): Returns ------- - if block=False: - AsyncMapResult - An object like AsyncResult, but which reassembles the sequence of results - into a single list. AsyncMapResults can be iterated through before all - results are complete. - else: - list - the result of map(f,*sequences) + + If block=False + An :class:`~IPython.parallel.client.asyncresult.AsyncMapResult` instance. + An object like AsyncResult, but which reassembles the sequence of results + into a single list. AsyncMapResults can be iterated through before all + results are complete. + else + A list, the result of ``map(f,*sequences)`` """ block = kwargs.pop('block', self.block) @@ -1056,7 +1052,7 @@ class LoadBalancedView(View): @sync_results @save_ids def map(self, f, *sequences, **kwargs): - """view.map(f, *sequences, block=self.block, chunksize=1, ordered=True) => list|AsyncMapResult + """``view.map(f, *sequences, block=self.block, chunksize=1, ordered=True)`` => list|AsyncMapResult Parallel version of builtin `map`, load-balanced by this View. @@ -1091,14 +1087,13 @@ class LoadBalancedView(View): Returns ------- - if block=False: - AsyncMapResult - An object like AsyncResult, but which reassembles the sequence of results - into a single list. AsyncMapResults can be iterated through before all - results are complete. - else: - the result of map(f,*sequences) - + if block=False + An :class:`~IPython.parallel.client.asyncresult.AsyncMapResult` instance. + An object like AsyncResult, but which reassembles the sequence of results + into a single list. AsyncMapResults can be iterated through before all + results are complete. + else + A list, the result of ``map(f,*sequences)`` """ # default diff --git a/IPython/parallel/controller/dependency.py b/IPython/parallel/controller/dependency.py index 853a0b7..93af379 100644 --- a/IPython/parallel/controller/dependency.py +++ b/IPython/parallel/controller/dependency.py @@ -105,17 +105,16 @@ def require(*objects, **mapping): and will be pushed to the engine with their __name__. Other objects can be passed by keyword arg. - Examples - -------- + Examples:: - In [1]: @require('numpy') - ...: def norm(a): - ...: return numpy.linalg.norm(a,2) + In [1]: @require('numpy') + ...: def norm(a): + ...: return numpy.linalg.norm(a,2) - In [2]: foo = lambda x: x*x - In [3]: @require(foo) - ...: def bar(a): - ...: return foo(1-a) + In [2]: foo = lambda x: x*x + In [3]: @require(foo) + ...: def bar(a): + ...: return foo(1-a) """ names = [] for obj in objects: diff --git a/IPython/parallel/controller/dictdb.py b/IPython/parallel/controller/dictdb.py index e3ad9e0..bffcc2a 100644 --- a/IPython/parallel/controller/dictdb.py +++ b/IPython/parallel/controller/dictdb.py @@ -6,37 +6,42 @@ Authors: * Min RK -TaskRecords are dicts of the form: -{ - 'msg_id' : str(uuid), - 'client_uuid' : str(uuid), - 'engine_uuid' : str(uuid) or None, - 'header' : dict(header), - 'content': dict(content), - 'buffers': list(buffers), - 'submitted': datetime, - 'started': datetime or None, - 'completed': datetime or None, - 'resubmitted': datetime or None, - 'result_header' : dict(header) or None, - 'result_content' : dict(content) or None, - 'result_buffers' : list(buffers) or None, -} -With this info, many of the special categories of tasks can be defined by query: - -pending: completed is None -client's outstanding: client_uuid = uuid && completed is None -MIA: arrived is None (and completed is None) -etc. +TaskRecords are dicts of the form:: + + { + 'msg_id' : str(uuid), + 'client_uuid' : str(uuid), + 'engine_uuid' : str(uuid) or None, + 'header' : dict(header), + 'content': dict(content), + 'buffers': list(buffers), + 'submitted': datetime, + 'started': datetime or None, + 'completed': datetime or None, + 'resubmitted': datetime or None, + 'result_header' : dict(header) or None, + 'result_content' : dict(content) or None, + 'result_buffers' : list(buffers) or None, + } + +With this info, many of the special categories of tasks can be defined by query, +e.g.: + +* pending: completed is None +* client's outstanding: client_uuid = uuid && completed is None +* MIA: arrived is None (and completed is None) + +EngineRecords are dicts of the form:: + + { + 'eid' : int(id), + 'uuid': str(uuid) + } -EngineRecords are dicts of the form: -{ - 'eid' : int(id), - 'uuid': str(uuid) -} This may be extended, but is currently. -We support a subset of mongodb operators: +We support a subset of mongodb operators:: + $lt,$gt,$lte,$gte,$ne,$in,$nin,$all,$mod,$exists """ #----------------------------------------------------------------------------- diff --git a/IPython/parallel/controller/hub.py b/IPython/parallel/controller/hub.py index 8bdba12..176edfa 100644 --- a/IPython/parallel/controller/hub.py +++ b/IPython/parallel/controller/hub.py @@ -1149,11 +1149,15 @@ class Hub(SessionFactory): def queue_status(self, client_id, msg): """Return the Queue status of one or more targets. - if verbose: return the msg_ids - else: return len of each type. - keys: queue (pending MUX jobs) - tasks (pending Task jobs) - completed (finished jobs from both queues)""" + + If verbose, return the msg_ids, else return len of each type. + + Keys: + + * queue (pending MUX jobs) + * tasks (pending Task jobs) + * completed (finished jobs from both queues) + """ content = msg['content'] targets = content['targets'] try: diff --git a/IPython/parallel/util.py b/IPython/parallel/util.py index d8344e9..f914953 100644 --- a/IPython/parallel/util.py +++ b/IPython/parallel/util.py @@ -199,7 +199,8 @@ def disambiguate_url(url, location=None): """turn multi-ip interfaces '0.0.0.0' and '*' into connectable ones, based on the location (default interpretation is localhost). - This is for zeromq urls, such as tcp://*:10101.""" + This is for zeromq urls, such as ``tcp://*:10101``. + """ try: proto,ip,port = split_url(url) except AssertionError: diff --git a/IPython/qt/console/console_widget.py b/IPython/qt/console/console_widget.py index b108ff3..ab70ed8 100644 --- a/IPython/qt/console/console_widget.py +++ b/IPython/qt/console/console_widget.py @@ -236,8 +236,8 @@ class ConsoleWidget(MetaQObjectHasTraits('NewBase', (LoggingConfigurable, QtGui. def __init__(self, parent=None, **kw): """ Create a ConsoleWidget. - Parameters: - ----------- + Parameters + ---------- parent : QWidget, optional [default None] The parent for this widget. """ @@ -543,8 +543,8 @@ class ConsoleWidget(MetaQObjectHasTraits('NewBase', (LoggingConfigurable, QtGui. def clear(self, keep_input=True): """ Clear the console. - Parameters: - ----------- + Parameters + ---------- keep_input : bool, optional (default True) If set, restores the old input buffer if a new prompt is written. """ @@ -580,8 +580,8 @@ class ConsoleWidget(MetaQObjectHasTraits('NewBase', (LoggingConfigurable, QtGui. """ Executes source or the input buffer, possibly prompting for more input. - Parameters: - ----------- + Parameters + ---------- source : str, optional The source to execute. If not specified, the input buffer will be @@ -600,14 +600,14 @@ class ConsoleWidget(MetaQObjectHasTraits('NewBase', (LoggingConfigurable, QtGui. entered by the user. The effect of this parameter depends on the subclass implementation. - Raises: - ------- + Raises + ------ RuntimeError If incomplete input is given and 'hidden' is True. In this case, it is not possible to prompt for more input. - Returns: - -------- + Returns + ------- A boolean indicating whether the source was executed. """ # WARNING: The order in which things happen here is very particular, in @@ -746,8 +746,8 @@ class ConsoleWidget(MetaQObjectHasTraits('NewBase', (LoggingConfigurable, QtGui. def paste(self, mode=QtGui.QClipboard.Clipboard): """ Paste the contents of the clipboard into the input region. - Parameters: - ----------- + Parameters + ---------- mode : QClipboard::Mode, optional [default QClipboard::Clipboard] Controls which part of the system clipboard is used. This can be @@ -1060,8 +1060,8 @@ class ConsoleWidget(MetaQObjectHasTraits('NewBase', (LoggingConfigurable, QtGui. """ Given a KeyboardModifiers flags object, return whether the Control key is down. - Parameters: - ----------- + Parameters + ---------- include_command : bool, optional (default True) Whether to treat the Command key as a (mutually exclusive) synonym for Control when in Mac OS. @@ -1868,8 +1868,8 @@ class ConsoleWidget(MetaQObjectHasTraits('NewBase', (LoggingConfigurable, QtGui. """ Displays text using the pager if it exceeds the height of the viewport. - Parameters: - ----------- + Parameters + ---------- html : bool, optional (default False) If set, the text will be interpreted as HTML instead of plain text. """ @@ -1903,11 +1903,8 @@ class ConsoleWidget(MetaQObjectHasTraits('NewBase', (LoggingConfigurable, QtGui. """ Change the pager to `paging` style. - XXX: currently, this is limited to switching between 'hsplit' and - 'vsplit'. - - Parameters: - ----------- + Parameters + ---------- paging : string Either "hsplit", "vsplit", or "inside" """ diff --git a/IPython/qt/console/history_console_widget.py b/IPython/qt/console/history_console_widget.py index 35f6a7f..d2c5354 100644 --- a/IPython/qt/console/history_console_widget.py +++ b/IPython/qt/console/history_console_widget.py @@ -155,15 +155,15 @@ class HistoryConsoleWidget(ConsoleWidget): def history_previous(self, substring='', as_prefix=True): """ If possible, set the input buffer to a previous history item. - Parameters: - ----------- + Parameters + ---------- substring : str, optional If specified, search for an item with this substring. as_prefix : bool, optional If True, the substring must match at the beginning (default). - Returns: - -------- + Returns + ------- Whether the input buffer was changed. """ index = self._history_index @@ -186,15 +186,15 @@ class HistoryConsoleWidget(ConsoleWidget): def history_next(self, substring='', as_prefix=True): """ If possible, set the input buffer to a subsequent history item. - Parameters: - ----------- + Parameters + ---------- substring : str, optional If specified, search for an item with this substring. as_prefix : bool, optional If True, the substring must match at the beginning (default). - Returns: - -------- + Returns + ------- Whether the input buffer was changed. """ index = self._history_index @@ -217,8 +217,8 @@ class HistoryConsoleWidget(ConsoleWidget): def history_tail(self, n=10): """ Get the local history list. - Parameters: - ----------- + Parameters + ---------- n : int The (maximum) number of history items to get. """ diff --git a/IPython/qt/console/ipython_widget.py b/IPython/qt/console/ipython_widget.py index 71a0251..b93d86a 100644 --- a/IPython/qt/console/ipython_widget.py +++ b/IPython/qt/console/ipython_widget.py @@ -438,8 +438,8 @@ class IPythonWidget(FrontendWidget): def set_default_style(self, colors='lightbg'): """ Sets the widget style to the class defaults. - Parameters: - ----------- + Parameters + ---------- colors : str, optional (default lightbg) Whether to use the default IPython light background or dark background or B&W style. @@ -464,8 +464,8 @@ class IPythonWidget(FrontendWidget): def _edit(self, filename, line=None): """ Opens a Python script for editing. - Parameters: - ----------- + Parameters + ---------- filename : str A path to a local system file. diff --git a/IPython/qt/console/kill_ring.py b/IPython/qt/console/kill_ring.py index 98d1d09..7f8cce6 100644 --- a/IPython/qt/console/kill_ring.py +++ b/IPython/qt/console/kill_ring.py @@ -32,8 +32,8 @@ class KillRing(object): def yank(self): """ Yank back the most recently killed text. - Returns: - -------- + Returns + ------- A text string or None. """ self._index = len(self._ring) @@ -42,8 +42,8 @@ class KillRing(object): def rotate(self): """ Rotate the kill ring, then yank back the new top. - Returns: - -------- + Returns + ------- A text string or None. """ self._index -= 1 diff --git a/IPython/qt/console/mainwindow.py b/IPython/qt/console/mainwindow.py index 53a3d95..9660bfc 100644 --- a/IPython/qt/console/mainwindow.py +++ b/IPython/qt/console/mainwindow.py @@ -673,8 +673,8 @@ class MainWindow(QtGui.QMainWindow): def _get_magic_menu(self,menuidentifier, menulabel=None): """return a submagic menu by name, and create it if needed - parameters: - ----------- + Parameters + ---------- menulabel : str Label for the menu diff --git a/IPython/qt/console/qtconsoleapp.py b/IPython/qt/console/qtconsoleapp.py index 5fbefab..4788e64 100644 --- a/IPython/qt/console/qtconsoleapp.py +++ b/IPython/qt/console/qtconsoleapp.py @@ -36,6 +36,10 @@ import sys if os.name == 'nt': old_excepthook = sys.excepthook + # Exclude this from our autogenerated API docs. + undoc = lambda func: func + + @undoc def gui_excepthook(exctype, value, tb): try: import ctypes, traceback diff --git a/IPython/qt/rich_text.py b/IPython/qt/rich_text.py index 342da2d..d94e6ed 100644 --- a/IPython/qt/rich_text.py +++ b/IPython/qt/rich_text.py @@ -126,8 +126,8 @@ class HtmlExporter(object): def export_html(html, filename, image_tag = None, inline = True): """ Export the contents of the ConsoleWidget as HTML. - Parameters: - ----------- + Parameters + ---------- html : unicode, A Python unicode string containing the Qt HTML to export. @@ -162,8 +162,8 @@ def export_html(html, filename, image_tag = None, inline = True): def export_xhtml(html, filename, image_tag=None): """ Export the contents of the ConsoleWidget as XHTML with inline SVGs. - Parameters: - ----------- + Parameters + ---------- html : unicode, A Python unicode string containing the Qt HTML to export. @@ -216,8 +216,8 @@ def default_image_tag(match, path = None, format = "png"): def fix_html(html): """ Transforms a Qt-generated HTML string into a standards-compliant one. - Parameters: - ----------- + Parameters + ---------- html : unicode, A Python unicode string containing the Qt HTML. """ diff --git a/IPython/qt/svg.py b/IPython/qt/svg.py index 9404d94..f2d1321 100644 --- a/IPython/qt/svg.py +++ b/IPython/qt/svg.py @@ -10,16 +10,16 @@ from IPython.utils.py3compat import unicode_type def save_svg(string, parent=None): """ Prompts the user to save an SVG document to disk. - Parameters: - ----------- + Parameters + ---------- string : basestring A Python string containing a SVG document. parent : QWidget, optional The parent to use for the file dialog. - Returns: - -------- + Returns + ------- The name of the file to which the document was saved, or None if the save was cancelled. """ @@ -43,8 +43,8 @@ def save_svg(string, parent=None): def svg_to_clipboard(string): """ Copy a SVG document to the clipboard. - Parameters: - ----------- + Parameters + ---------- string : basestring A Python string containing a SVG document. """ @@ -58,8 +58,8 @@ def svg_to_clipboard(string): def svg_to_image(string, size=None): """ Convert a SVG document to a QImage. - Parameters: - ----------- + Parameters + ---------- string : basestring A Python string containing a SVG document. @@ -67,13 +67,13 @@ def svg_to_image(string, size=None): The size of the image that is produced. If not specified, the SVG document's default size is used. - Raises: - ------- + Raises + ------ ValueError If an invalid SVG string is provided. - Returns: - -------- + Returns + ------- A QImage of format QImage.Format_ARGB32. """ if isinstance(string, unicode_type): diff --git a/IPython/sphinxext/ipython_directive.py b/IPython/sphinxext/ipython_directive.py index 17c3c65..744aa57 100644 --- a/IPython/sphinxext/ipython_directive.py +++ b/IPython/sphinxext/ipython_directive.py @@ -31,7 +31,6 @@ ipython_promptin: The default is 'In [%d]:'. This expects that the line numbers are used in the prompt. ipython_promptout: - The string to represent the IPython prompt in the generated ReST. The default is 'Out [%d]:'. This expects that the line numbers are used in the prompt. diff --git a/IPython/terminal/embed.py b/IPython/terminal/embed.py index 33f9d33..a37d226 100644 --- a/IPython/terminal/embed.py +++ b/IPython/terminal/embed.py @@ -161,30 +161,28 @@ class InteractiveShellEmbed(TerminalInteractiveShell): display_banner=None, global_ns=None, compile_flags=None): """Embeds IPython into a running python program. - Input: - - - header: An optional header message can be specified. - - - local_ns, module: working local namespace (a dict) and module (a - module or similar object). If given as None, they are automatically - taken from the scope where the shell was called, so that - program variables become visible. - - - stack_depth: specifies how many levels in the stack to go to - looking for namespaces (when local_ns or module is None). This - allows an intermediate caller to make sure that this function gets - the namespace from the intended level in the stack. By default (0) - it will get its locals and globals from the immediate caller. - - - compile_flags: A bit field identifying the __future__ features - that are enabled, as passed to the builtin `compile` function. If - given as None, they are automatically taken from the scope where the - shell was called. - - Warning: it's possible to use this in a program which is being run by - IPython itself (via %run), but some funny things will happen (a few - globals get overwritten). In the future this will be cleaned up, as - there is no fundamental reason why it can't work perfectly.""" + Parameters + ---------- + + local_ns, module + Working local namespace (a dict) and module (a module or similar + object). If given as None, they are automatically taken from the scope + where the shell was called, so that program variables become visible. + + stack_depth : int + How many levels in the stack to go to looking for namespaces (when + local_ns or module is None). This allows an intermediate caller to + make sure that this function gets the namespace from the intended + level in the stack. By default (0) it will get its locals and globals + from the immediate caller. + + compile_flags + A bit field identifying the __future__ features + that are enabled, as passed to the builtin :func:`compile` function. + If given as None, they are automatically taken from the scope where + the shell was called. + + """ if (global_ns is not None) and (module is None): warnings.warn("global_ns is deprecated, use module instead.", DeprecationWarning) diff --git a/IPython/terminal/interactiveshell.py b/IPython/terminal/interactiveshell.py index f281dc2..9297c70 100644 --- a/IPython/terminal/interactiveshell.py +++ b/IPython/terminal/interactiveshell.py @@ -191,8 +191,7 @@ class TerminalMagics(Magics): This assigns the pasted block to variable 'foo' as string, without executing it (preceding >>> and + is still stripped). - Options - ------- + Options: -r: re-executes the block previously entered by cpaste. @@ -561,12 +560,11 @@ class TerminalInteractiveShell(InteractiveShell): The returned line does not include the trailing newline. When the user enters the EOF key sequence, EOFError is raised. - Optional inputs: + Parameters + ---------- - - prompt(''): a string to be printed to prompt the user. - - - continue_prompt(False): whether this line is the first one or a - continuation in a sequence of inputs. + prompt : str, optional + A string to be printed to prompt the user. """ # Code run by the user may have modified the readline completer state. # We must ensure that our completer is back in place. diff --git a/IPython/testing/decorators.py b/IPython/testing/decorators.py index 62422ce..04c0dbe 100644 --- a/IPython/testing/decorators.py +++ b/IPython/testing/decorators.py @@ -175,20 +175,21 @@ def skipif(skip_condition, msg=None): Parameters ---------- - skip_condition : bool or callable. - Flag to determine whether to skip test. If the condition is a - callable, it is used at runtime to dynamically make the decision. This - is useful for tests that may require costly imports, to delay the cost - until the test suite is actually executed. + + skip_condition : bool or callable + Flag to determine whether to skip test. If the condition is a + callable, it is used at runtime to dynamically make the decision. This + is useful for tests that may require costly imports, to delay the cost + until the test suite is actually executed. msg : string - Message to give on raising a SkipTest exception - - Returns - ------- - decorator : function - Decorator, which, when applied to a function, causes SkipTest - to be raised when the skip_condition was True, and the function - to be called normally otherwise. + Message to give on raising a SkipTest exception. + + Returns + ------- + decorator : function + Decorator, which, when applied to a function, causes SkipTest + to be raised when the skip_condition was True, and the function + to be called normally otherwise. Notes ----- diff --git a/IPython/testing/tools.py b/IPython/testing/tools.py index d17ce42..b09da9b 100644 --- a/IPython/testing/tools.py +++ b/IPython/testing/tools.py @@ -59,17 +59,17 @@ def full_path(startPath,files): """Make full paths for all the listed files, based on startPath. Only the base part of startPath is kept, since this routine is typically - used with a script's __file__ variable as startPath. The base of startPath + used with a script's ``__file__`` variable as startPath. The base of startPath is then prepended to all the listed files, forming the output list. Parameters ---------- - startPath : string - Initial path to use as the base for the results. This path is split + startPath : string + Initial path to use as the base for the results. This path is split using os.path.split() and only its first component is kept. - files : string or list - One or more files. + files : string or list + One or more files. Examples -------- @@ -80,9 +80,10 @@ def full_path(startPath,files): >>> full_path('/foo',['a.txt','b.txt']) ['/a.txt', '/b.txt'] - If a single file is given, the output is still a list: - >>> full_path('/foo','a.txt') - ['/a.txt'] + If a single file is given, the output is still a list:: + + >>> full_path('/foo','a.txt') + ['/a.txt'] """ files = list_strings(files) @@ -105,7 +106,8 @@ def parse_test_output(txt): Returns ------- - nerr, nfail: number of errors and failures. + nerr, nfail + number of errors and failures. """ err_m = re.search(r'^FAILED \(errors=(\d+)\)', txt, re.MULTILINE) diff --git a/IPython/utils/attic.py b/IPython/utils/attic.py index d8fb5e3..0915ac2 100644 --- a/IPython/utils/attic.py +++ b/IPython/utils/attic.py @@ -81,11 +81,12 @@ def belong(candidates,checklist): def with_obj(object, **args): """Set multiple attributes for an object, similar to Pascal's with. - Example: - with_obj(jim, - born = 1960, - haircolour = 'Brown', - eyecolour = 'Green') + Example:: + + with_obj(jim, + born = 1960, + haircolour = 'Brown', + eyecolour = 'Green') Credit: Greg Ewing, in http://mail.python.org/pipermail/python-list/2001-May/040703.html. diff --git a/IPython/utils/coloransi.py b/IPython/utils/coloransi.py index acac3a3..b879f7c 100644 --- a/IPython/utils/coloransi.py +++ b/IPython/utils/coloransi.py @@ -48,8 +48,9 @@ color_templates = ( def make_color_table(in_class): """Build a set of color attributes in a class. - Helper function for building the *TermColors classes.""" - + Helper function for building the :class:`TermColors` and + :class`InputTermColors`. + """ for name,value in color_templates: setattr(in_class,name,in_class._base % value) diff --git a/IPython/utils/frame.py b/IPython/utils/frame.py index a87d6f9..348cbcc 100644 --- a/IPython/utils/frame.py +++ b/IPython/utils/frame.py @@ -26,17 +26,20 @@ from IPython.utils import py3compat def extract_vars(*names,**kw): """Extract a set of variables by name from another frame. - :Parameters: - - `*names`: strings + Parameters + ---------- + *names : str One or more variable names which will be extracted from the caller's - frame. + frame. - :Keywords: - - `depth`: integer (0) + depth : integer, optional How many frames in the stack to walk when looking for your variables. + The default is 0, which will use the frame where the call was made. - Examples: + Examples + -------- + :: In [2]: def func(x): ...: y = 1 diff --git a/IPython/utils/text.py b/IPython/utils/text.py index 71d5e93..2eb6580 100644 --- a/IPython/utils/text.py +++ b/IPython/utils/text.py @@ -110,10 +110,10 @@ class SList(list): These are normal lists, but with the special attributes: - .l (or .list) : value as list (the list itself). - .n (or .nlstr): value as a string, joined on newlines. - .s (or .spstr): value as a string, joined on spaces. - .p (or .paths): list of path objects + * .l (or .list) : value as list (the list itself). + * .n (or .nlstr): value as a string, joined on newlines. + * .s (or .spstr): value as a string, joined on spaces. + * .p (or .paths): list of path objects Any values which require transformations are computed only once and cached.""" @@ -191,13 +191,14 @@ class SList(list): Allows quick awk-like usage of string lists. Example data (in var a, created by 'a = !ls -l'):: + -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython - a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+'] - a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+'] - (note the joining by space). - a.fields(-1) is ['ChangeLog', 'IPython'] + * ``a.fields(0)`` is ``['-rwxrwxrwx', 'drwxrwxrwx+']`` + * ``a.fields(1,0)`` is ``['1 -rwxrwxrwx', '6 drwxrwxrwx+']`` + (note the joining by space). + * ``a.fields(-1)`` is ``['ChangeLog', 'IPython']`` IndexErrors are ignored. diff --git a/IPython/utils/traitlets.py b/IPython/utils/traitlets.py index 30e5bbd..7b33e2f 100644 --- a/IPython/utils/traitlets.py +++ b/IPython/utils/traitlets.py @@ -761,8 +761,8 @@ class Instance(ClassBasedTraitType): allow_none : bool Indicates whether None is allowed as a value. - Default Value - ------------- + Notes + ----- If both ``args`` and ``kw`` are None, then the default value is None. If ``args`` is a tuple and ``kw`` is a dict, then the default is created as ``klass(*args, **kw)``. If either ``args`` or ``kw`` is diff --git a/docs/autogen_api.py b/docs/autogen_api.py index b0d831e..ee2ba66 100755 --- a/docs/autogen_api.py +++ b/docs/autogen_api.py @@ -17,45 +17,29 @@ if __name__ == '__main__': docwriter = ApiDocWriter(package,rst_extension='.rst') # You have to escape the . here because . is a special char for regexps. # You must do make clean if you change this! - docwriter.package_skip_patterns += [r'\.fixes$', - r'\.external$', + docwriter.package_skip_patterns += [r'\.external$', + # Extensions are documented elsewhere. r'\.extensions', - r'\.kernel\.config', - r'\.attic', - r'\.quarantine', - r'\.deathrow', - r'\.config\.default', r'\.config\.profile', - r'\.frontend', - r'\.gui', - r'\.kernel', - # For now, the zmq code has - # unconditional top-level code so it's - # not import safe. This needs fixing - r'\.zmq', ] - docwriter.module_skip_patterns += [ - r'\.testing\.iptest', - # Keeping these disabled is OK - r'\.parallel\.controller\.mongodb', - r'\.lib\.inputhookwx', - r'\.lib\.inputhookgtk', - r'\.cocoa', + # The inputhook* modules often cause problems on import, such as trying to + # load incompatible Qt bindings. It's easiest to leave them all out. The + # main API is in the inputhook module, which is documented. + docwriter.module_skip_patterns += [ r'\.lib\.inputhook.+', r'\.ipdoctest', - r'\.Gnuplot', - r'\.frontend\.process\.winprocess', + r'\.testing\.plugin', + # This just prints a deprecation msg: r'\.frontend', - r'\.Shell', ] - # If we don't have pexpect, we can't load irunner, so skip any code that - # depends on it + # We're rarely working on machines with the Azure SDK installed, so we + # skip the module that needs it in that case. try: - import pexpect + import azure # analysis:ignore except ImportError: - docwriter.module_skip_patterns += [r'\.lib\.irunner', - r'\.testing\.mkdoctests'] + docwriter.module_skip_patterns.append(r'\.html\.services\.notebooks\.azurenbmanager') + # Now, generate the outputs docwriter.write_api_docs(outdir) # Write index with .txt extension - we can include it, but Sphinx won't try diff --git a/docs/source/conf.py b/docs/source/conf.py index 8499d67..d6fc28d 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -44,6 +44,7 @@ extensions = [ 'matplotlib.sphinxext.only_directives', 'matplotlib.sphinxext.plot_directive', 'sphinx.ext.autodoc', + 'sphinx.ext.autosummary', 'sphinx.ext.doctest', 'sphinx.ext.inheritance_diagram', 'sphinx.ext.intersphinx', @@ -179,7 +180,7 @@ html_additional_pages = { # Output file base name for HTML help builder. htmlhelp_basename = 'ipythondoc' -intersphinx_mapping = {'http://docs.python.org/2/': None} +intersphinx_mapping = {'python': ('http://docs.python.org/2/', None)} # Options for LaTeX output # ------------------------ diff --git a/docs/source/development/gitwash/development_workflow.rst b/docs/source/development/gitwash/development_workflow.rst index b66c710..00b8412 100644 --- a/docs/source/development/gitwash/development_workflow.rst +++ b/docs/source/development/gitwash/development_workflow.rst @@ -116,8 +116,7 @@ The generated comparison, is between your feature branch ``my-new-feature``, and the place in ``master`` from which you branched ``my-new-feature``. In other words, you can keep updating ``master`` without interfering with the output from the comparison. More detail? -Note the three dots in the URL above (``master...my-new-feature``) and -see :ref:`dot2-dot3`. +Note the three dots in the URL above (``master...my-new-feature``). Asking for your changes to be merged with the main repo ======================================================= diff --git a/docs/source/development/gitwash/dot2_dot3.rst b/docs/source/development/gitwash/dot2_dot3.rst deleted file mode 100644 index 7759e2e..0000000 --- a/docs/source/development/gitwash/dot2_dot3.rst +++ /dev/null @@ -1,28 +0,0 @@ -.. _dot2-dot3: - -======================================== - Two and three dots in difference specs -======================================== - -Thanks to Yarik Halchenko for this explanation. - -Imagine a series of commits A, B, C, D... Imagine that there are two -branches, *topic* and *master*. You branched *topic* off *master* when -*master* was at commit 'E'. The graph of the commits looks like this:: - - - A---B---C topic - / - D---E---F---G master - -Then:: - - git diff master..topic - -will output the difference from G to C (i.e. with effects of F and G), -while:: - - git diff master...topic - -would output just differences in the topic branch (i.e. only A, B, and -C). diff --git a/docs/source/development/index.rst b/docs/source/development/index.rst index be82d74..c8a7142 100644 --- a/docs/source/development/index.rst +++ b/docs/source/development/index.rst @@ -26,3 +26,4 @@ on the IPython GitHub wiki. parallel_connections pycompat config + inputhook_app diff --git a/docs/source/parallel/winhpc_index.rst b/docs/source/parallel/winhpc_index.rst deleted file mode 100644 index dad2e86..0000000 --- a/docs/source/parallel/winhpc_index.rst +++ /dev/null @@ -1,14 +0,0 @@ -======================================== -Using IPython on Windows HPC Server 2008 -======================================== - - -Contents -======== - -.. toctree:: - :maxdepth: 1 - - parallel_winhpc - parallel_demos - diff --git a/docs/source/whatsnew/github-stats-0.12.rst b/docs/source/whatsnew/github-stats-0.12.rst index 6503f22..05d139a 100644 --- a/docs/source/whatsnew/github-stats-0.12.rst +++ b/docs/source/whatsnew/github-stats-0.12.rst @@ -140,7 +140,7 @@ Pull requests (257): * `1126 `_: Totally remove pager when read only (notebook) * `1091 `_: qtconsole : allow copy with shortcut in pager * `1114 `_: fix magics history in two-process ipython console -* `1113 `_: Fixing #1112 removing failing asserts for test_carriage_return and test_... +* `1113 `_: Fixing #1112 removing failing asserts for test_carriage_return and test_beep * `1089 `_: Support carriage return ('\r') and beep ('\b') characters in the qtconsole * `1108 `_: Completer usability 2 (rebased of pr #1082) * `864 `_: Two-process terminal frontend (ipython core branch) diff --git a/docs/source/whatsnew/github-stats-1.0.rst b/docs/source/whatsnew/github-stats-1.0.rst index f3beb3c..05bdbde 100644 --- a/docs/source/whatsnew/github-stats-1.0.rst +++ b/docs/source/whatsnew/github-stats-1.0.rst @@ -643,7 +643,7 @@ Pull Requests (793): * :ghpull:`3223`: add missing mathjax_url to new settings dict * :ghpull:`3089`: add stdin to the notebook * :ghpull:`3221`: Remove references to HTMLCell (dead code) -* :ghpull:`3205`: add ignored *args to HasTraits constructor +* :ghpull:`3205`: add ignored ``*args`` to HasTraits constructor * :ghpull:`3088`: cleanup IPython handler settings * :ghpull:`3201`: use much faster regexp for ansi coloring * :ghpull:`3220`: avoid race condition in profile creation @@ -1064,7 +1064,7 @@ Pull Requests (793): * :ghpull:`2140`: 2to3: Apply `has_key` fixer. * :ghpull:`2131`: Add option append (-a) to %save * :ghpull:`2117`: use explicit url in notebook example -* :ghpull:`2133`: Tell git that *.py files contain Python code, for use in word-diffs. +* :ghpull:`2133`: Tell git that ``*.py`` files contain Python code, for use in word-diffs. * :ghpull:`2134`: Apply 2to3 `next` fix. * :ghpull:`2126`: ipcluster broken with any batch launcher (PBS/LSF/SGE) * :ghpull:`2104`: Windows make file for Sphinx documentation @@ -1423,7 +1423,7 @@ Issues (691): * :ghissue:`3207`: [Feature] folders for ipython notebook dashboard * :ghissue:`3178`: cell magics do not work with empty lines after #2447 * :ghissue:`3204`: Default plot() colors unsuitable for red-green colorblind users -* :ghissue:`1789`: :\n/*foo turns into :\n*(foo) in triple-quoted strings. +* :ghissue:`1789`: ``:\n/*foo`` turns into ``:\n*(foo)`` in triple-quoted strings. * :ghissue:`3202`: File cell magic fails with blank lines * :ghissue:`3199`: %%cython -a stopped working? * :ghissue:`2688`: obsolete imports in import autocompletion @@ -1649,7 +1649,7 @@ Issues (691): * :ghissue:`1308`: ipython qtconsole --ssh=server --existing ... hangs * :ghissue:`1679`: List command doesn't work in ipdb debugger the first time * :ghissue:`2545`: pypi win32 installer creates 64bit executibles -* :ghissue:`2080`: Event loop issues with IPython 0.12 and PyQt4 (QDialog.exec_ and more) +* :ghissue:`2080`: Event loop issues with IPython 0.12 and PyQt4 (``QDialog.exec_`` and more) * :ghissue:`2541`: Allow `python -m IPython` * :ghissue:`2508`: subplots_adjust() does not work correctly in ipython notebook * :ghissue:`2289`: Incorrect mathjax rendering of certain arrays of equations diff --git a/docs/source/whatsnew/version0.11.rst b/docs/source/whatsnew/version0.11.rst index 697684d..2b7b6fd 100644 --- a/docs/source/whatsnew/version0.11.rst +++ b/docs/source/whatsnew/version0.11.rst @@ -547,7 +547,7 @@ Backwards incompatible changes * Old style configuration files :file:`ipythonrc` and :file:`ipy_user_conf.py` are no longer supported. Users should migrate there configuration files to - the new format described :doc:`here ` and + the new format described :doc:`here ` and :ref:`here `. * The old IPython extension API that relied on :func:`ipapi` has been diff --git a/docs/sphinxext/apigen.py b/docs/sphinxext/apigen.py index a7bbd5b..21f28e2 100644 --- a/docs/sphinxext/apigen.py +++ b/docs/sphinxext/apigen.py @@ -220,7 +220,7 @@ class ApiDocWriter(object): # get the names of all classes and functions functions, classes = self._parse_module(uri) if not len(functions) and not len(classes): - print ('WARNING: Empty -', uri) # dbg + #print ('WARNING: Empty -', uri) # dbg return '' # Make a shorter version of the uri that omits the package name for @@ -415,7 +415,8 @@ class ApiDocWriter(object): idx = open(path,'wt') w = idx.write w('.. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n') - w('.. toctree::\n\n') - for f in self.written_modules: - w(' %s\n' % os.path.join(relpath,f)) + w('.. autosummary::\n' + ' :toctree: %s\n\n' % relpath) + for mod in self.written_modules: + w(' %s\n' % mod) idx.close()