8000 deprecate IPython.utils.text.dedent in favor of inspect.cleandoc by 12somyasahu · Pull Request #15151 · ipython/ipython · GitHub
[go: up one dir, main page]

Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions IPython/core/magic.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from .inputtransformer2 import ESC_MAGIC, ESC_MAGIC2
from ..utils.ipstruct import Struct
from ..utils.process import arg_split
from ..utils.text import dedent
import inspect
from traitlets import Bool, Dict, Instance, observe
from logging import error

Expand Down Expand Up @@ -272,7 +272,7 @@ def mark(func: _F, *a: Any, **kw: Any) -> _F:
# Ensure the resulting decorator has a usable docstring
ds = _docstring_template.format("function", magic_kind)

ds += dedent(
ds += inspect.cleandoc(
"""
Note: this decorator can only be used in a context where IPython is already
active, so that the `get_ipython()` call succeeds. You can therefore use
Expand Down
146 changes: 77 additions & 69 deletions IPython/core/magic_arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,36 +75,51 @@ def my_cell_magic(line, cell):
:parts: 3

'''
#-----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# Copyright (C) 2010-2011, IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# 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
import textwrap


NAME_RE = re.compile(r"[a-zA-Z][a-zA-Z0-9_-]*$")


@undoc
class MagicHelpFormatter(argparse.RawDescriptionHelpFormatter):
"""A HelpFormatter with a couple of changes to meet our needs.
"""
"""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)
# Dedent ignoring unindented first line (preserves original IPython behavior)
if not text.startswith("\n"):
splits = text.split("\n", 1)
if len(splits) == 2:
first, rest = splits
text = "\n".join([first, textwrap.dedent(rest)])
else:
text = textwrap.dedent(text)
else:
text = textwrap.dedent(text)
return argparse.RawDescriptionHelpFormatter._fill_text(
self, 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)
(metavar,) = self._metavar_formatter(action, action.dest)(1)
return metavar

else:
Expand All @@ -125,127 +140,123 @@ def _format_action_invocation(self, action):
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))
parts.append("%s %s" % (option_string, args_string))

return ', '.join(parts)
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.
"""
def __init__(self,
prog=None,
usage=None,
description=None,
epilog=None,
parents=None,
formatter_class=MagicHelpFormatter,
prefix_chars='-',
argument_default=None,
conflict_handler='error',
add_help=False):
"""An ArgumentParser tweaked for use by IPython magics."""

def __init__(
self,
prog=None,
usage=None,
description=None,
epilog=None,
parents=None,
formatter_class=MagicHelpFormatter,
prefix_chars="-",
argument_default=None,
conflict_handler="error",
add_help=False,
):
if parents is None:
parents = []
super(MagicArgumentParser, self).__init__(prog=prog, usage=usage,
description=description, epilog=epilog,
parents=parents, formatter_class=formatter_class,
prefix_chars=prefix_chars, argument_default=argument_default,
conflict_handler=conflict_handler, add_help=add_help)
super(MagicArgumentParser, self).__init__(
prog=prog,
usage=usage,
description=description,
epilog=epilog,
parents=parents,
formatter_class=formatter_class,
prefix_chars=prefix_chars,
argument_default=argument_default,
conflict_handler=conflict_handler,
add_help=add_help,
)

def error(self, message):
""" Raise a catchable error instead of exiting.
"""
"""Raise a catchable error instead of exiting."""
raise UsageError(message)

def parse_argstring(self, argstring, *, partial=False):
""" Split a string into an argument list and parse that argument list.
"""
"""Split a string into an argument list and parse that argument list."""
argv = arg_split(argstring, strict=not partial)
if partial:
return self.parse_known_args(argv)
return self.parse_args(argv)


def construct_parser(magic_func):
""" Construct an argument parser using the function decorations.
"""
kwds = getattr(magic_func, 'argcmd_kwds', {})
if 'description' not in kwds:
kwds['description'] = getattr(magic_func, '__doc__', None)
"""Construct an argument parser using the function decorations."""
kwds = getattr(magic_func, "argcmd_kwds", {})
if "description" not in kwds:
kwds["description"] = getattr(magic_func, "__doc__", None)
arg_name = real_name(magic_func)
parser = MagicArgumentParser(arg_name, **kwds)
# Reverse the list of decorators in order to apply them in the
# order in which they appear in the source.
group = None
for deco in magic_func.decorators[::-1]:
result = deco.add_to_parser(parser, group)
if result is not None:
group = result

# Replace the magic function's docstring with the full help text.
magic_func.__doc__ = parser.format_help()

return parser


def parse_argstring(magic_func, argstring, *, partial=False):
""" Parse the string of arguments for the given magic function.
"""
"""Parse the string of arguments for the given magic function."""
return magic_func.parser.parse_argstring(argstring, partial=partial)


def real_name(magic_func):
""" Find the real name of the magic.
"""
"""Find the real name of the magic."""
magic_name = magic_func.__name__
if magic_name.startswith('magic_'):
magic_name = magic_name[len('magic_'):]
return getattr(magic_func, 'argcmd_name', magic_name)
if magic_name.startswith("magic_"):
magic_name = magic_name[len("magic_") :]
return getattr(magic_func, "argcmd_name", magic_name)


class ArgDecorator:
""" Base class for decorators to add ArgumentParser information to a method.
"""
"""Base class for decorators to add ArgumentParser information to a method."""

def __call__(self, func):
if not getattr(func, 'has_arguments', False):
if not getattr(func, "has_arguments", False):
func.has_arguments = True
func.decorators = []
func.decorators.append(self)
return func

def add_to_parser(self, parser, group):
""" Add this object's information to the parser, if necessary.
"""
pass


class magic_arguments(ArgDecorator):
""" Mark the magic as having argparse arguments and possibly adjust the
"""Mark the magic as having argparse arguments and possibly adjust the
name.
"""

def __init__(self, name=None):
self.name = name

def __call__(self, func):
if not getattr(func, 'has_arguments', False):
if not getattr(func, "has_arguments", False):
func.has_arguments = True
func.decorators = []
if self.name is not None:
func.argcmd_name = self.name
# This should be the first decorator in the list of decorators, thus the
# last to execute. Build the parser.
func.parser = construct_parser(func)
return func


class ArgMethodWrapper(ArgDecorator):

"""
Base class to define a wrapper for ArgumentParser method.

Expand All @@ -260,45 +271,43 @@ def __init__(self, *args, **kwds):
self.kwds = kwds

def add_to_parser(self, parser, group):
""" Add this object's information to the parser.
"""
if group is not None:
parser = group
getattr(parser, self._method_name)(*self.args, **self.kwds)
return None


class argument(ArgMethodWrapper):
""" Store arguments and keywords to pass to add_argument().
"""Store arguments and keywords to pass to add_argument().

Instances also serve to decorate command methods.
"""
_method_name = 'add_argument'

_method_name = "add_argument"


class defaults(ArgMethodWrapper):
""" Store arguments and keywords to pass to set_defaults().
"""Store arguments and keywords to pass to set_defaults().

Instances also serve to decorate command methods.
"""
_method_name = 'set_defaults'

_method_name = "set_defaults"


class argument_group(ArgMethodWrapper):
""" Store arguments and keywords to pass to add_argument_group().
"""Store arguments and keywords to pass to add_argument_group().

Instances also serve to decorate command methods.
"""

def add_to_parser(self, parser, group):
""" Add this object's information to the parser.
"""
return parser.add_argument_group(*self.args, **self.kwds)


class kwds(ArgDecorator):
""" Provide other keywords to the sub-parser constructor.
"""
"""Provide other keywords to the sub-parser constructor."""

def __init__(self, **kwds):
self.kwds = kwds

Expand All @@ -308,5 +317,4 @@ def __call__(self, func):
return func


__all__ = ['magic_arguments', 'argument', 'argument_group', 'kwds',
'parse_argstring']
__all__ = ["magic_arguments", "argument", "argument_group", "kwds", "parse_argstring"]
7 changes: 4 additions & 3 deletions IPython/core/magics/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
from IPython.core import magic_arguments, page
from IPython.core.error import UsageError
from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
from IPython.utils.text import format_screen, dedent, indent
import inspect
from IPython.utils.text import format_screen, indent
from IPython.testing.skipdoctest import skip_doctest
from IPython.utils.ipstruct import Struct

Expand Down Expand Up @@ -197,11 +198,11 @@ def _magic_docs(self, brief=False, rest=False):

return ''.join(
[format_string % (magic_escapes['line'], fname,
indent(dedent(fndoc)))
indent(inspect.cleandoc(fndoc)))
for fname, fndoc in sorted(docs['line'].items())]
+
[format_string % (magic_escapes['cell'], fname,
indent(dedent(fndoc)))
indent(inspect.cleandoc(fndoc)))
for fname, fndoc in sorted(docs['cell'].items())]
)

Expand Down
Loading
Loading
0