We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Improvement of  `core.magic_arguments` example
Currently, there is only a [very raw example](https://ipython.readthedocs.io/en/stable/api/generated/IPython.core.magic_arguments.html?highlight=%40magic_arguments.argumen#module-IPython.core.magic_arguments
) of using `magic_arguments` with custom cell magic.
Therefore, I have the idea to add a second, more fleshed out example that might help people to easier understand and use cell magic arguments: 
![image](https://user-images.githubusercontent.com/44469195/148220767-d59ad4ca-e713-434a-8241-c212580fba6b.png)
Here is the code:
```py
from IPython.core import magic_arguments
from IPython.core.magic import register_cell_magic


@magic_arguments.magic_arguments()
@magic_arguments.argument(
    "--option",
    help=("Add an option here"),
)
@magic_arguments.argument(
    "--style",
    default=None,
    help=("Add some style arguments"),
)
@register_cell_magic
def my_cell_magic(line, cell):
    """Cool cell magic"""
    args = magic_arguments.parse_argstring(my_cell_magic, line)
    print(args.style)
    print(args.option)
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `IPython/core/magic_arguments.py`
Content:
```
1 ''' A decorator-based method of constructing IPython magics with `argparse`
2 option handling.
3 
4 New magic functions can be defined like so::
5 
6     from IPython.core.magic_arguments import (argument, magic_arguments,
7         parse_argstring)
8 
9     @magic_arguments()
10     @argument('-o', '--option', help='An optional argument.')
11     @argument('arg', type=int, help='An integer positional argument.')
12     def magic_cool(self, arg):
13         """ A really cool magic command.
14 
15     """
16         args = parse_argstring(magic_cool, arg)
17         ...
18 
19 The `@magic_arguments` decorator marks the function as having argparse arguments.
20 The `@argument` decorator adds an argument using the same syntax as argparse's
21 `add_argument()` method. More sophisticated uses may also require the
22 `@argument_group` or `@kwds` decorator to customize the formatting and the
23 parsing.
24 
25 Help text for the magic is automatically generated from the docstring and the
26 arguments::
27 
28     In[1]: %cool?
29         %cool [-o OPTION] arg
30         
31         A really cool magic command.
32         
33         positional arguments:
34           arg                   An integer positional argument.
35         
36         optional arguments:
37           -o OPTION, --option OPTION
38                                 An optional argument.
39 
40 Inheritance diagram:
41 
42 .. inheritance-diagram:: IPython.core.magic_arguments
43    :parts: 3
44 
45 '''
46 #-----------------------------------------------------------------------------
47 # Copyright (C) 2010-2011, IPython Development Team.
48 #
49 # Distributed under the terms of the Modified BSD License.
50 #
51 # The full license is in the file COPYING.txt, distributed with this software.
52 #-----------------------------------------------------------------------------
53 import argparse
54 import re
55 
56 # Our own imports
57 from IPython.core.error import UsageError
58 from IPython.utils.decorators import undoc
59 from IPython.utils.process import arg_split
60 from IPython.utils.text import dedent
61 
62 NAME_RE = re.compile(r"[a-zA-Z][a-zA-Z0-9_-]*$")
63 
64 @undoc
65 class MagicHelpFormatter(argparse.RawDescriptionHelpFormatter):
66     """A HelpFormatter with a couple of changes to meet our needs.
67     """
68     # Modified to dedent text.
69     def _fill_text(self, text, width, indent):
70         return argparse.RawDescriptionHelpFormatter._fill_text(self, dedent(text), width, indent)
71 
72     # Modified to wrap argument placeholders in <> where necessary.
73     def _format_action_invocation(self, action):
74         if not action.option_strings:
75             metavar, = self._metavar_formatter(action, action.dest)(1)
76             return metavar
77 
78         else:
79             parts = []
80 
81             # if the Optional doesn't take a value, format is:
82             #    -s, --long
83             if action.nargs == 0:
84                 parts.extend(action.option_strings)
85 
86             # if the Optional takes a value, format is:
87             #    -s ARGS, --long ARGS
88             else:
89                 default = action.dest.upper()
90                 args_string = self._format_args(action, default)
91                 # IPYTHON MODIFICATION: If args_string is not a plain name, wrap
92                 # it in <> so it's valid RST.
93                 if not NAME_RE.match(args_string):
94                     args_string = "<%s>" % args_string
95                 for option_string in action.option_strings:
96                     parts.append('%s %s' % (option_string, args_string))
97 
98             return ', '.join(parts)
99 
100     # Override the default prefix ('usage') to our % magic escape,
101     # in a code block.
102     def add_usage(self, usage, actions, groups, prefix="::\n\n  %"):
103         super(MagicHelpFormatter, self).add_usage(usage, actions, groups, prefix)
104 
105 class MagicArgumentParser(argparse.ArgumentParser):
106     """ An ArgumentParser tweaked for use by IPython magics.
107     """
108     def __init__(self,
109                  prog=None,
110                  usage=None,
111                  description=None,
112                  epilog=None,
113                  parents=None,
114                  formatter_class=MagicHelpFormatter,
115                  prefix_chars='-',
116                  argument_default=None,
117                  conflict_handler='error',
118                  add_help=False):
119         if parents is None:
120             parents = []
121         super(MagicArgumentParser, self).__init__(prog=prog, usage=usage,
122             description=description, epilog=epilog,
123             parents=parents, formatter_class=formatter_class,
124             prefix_chars=prefix_chars, argument_default=argument_default,
125             conflict_handler=conflict_handler, add_help=add_help)
126 
127     def error(self, message):
128         """ Raise a catchable error instead of exiting.
129         """
130         raise UsageError(message)
131 
132     def parse_argstring(self, argstring):
133         """ Split a string into an argument list and parse that argument list.
134         """
135         argv = arg_split(argstring)
136         return self.parse_args(argv)
137 
138 
139 def construct_parser(magic_func):
140     """ Construct an argument parser using the function decorations.
141     """
142     kwds = getattr(magic_func, 'argcmd_kwds', {})
143     if 'description' not in kwds:
144         kwds['description'] = getattr(magic_func, '__doc__', None)
145     arg_name = real_name(magic_func)
146     parser = MagicArgumentParser(arg_name, **kwds)
147     # Reverse the list of decorators in order to apply them in the
148     # order in which they appear in the source.
149     group = None
150     for deco in magic_func.decorators[::-1]:
151         result = deco.add_to_parser(parser, group)
152         if result is not None:
153             group = result
154 
155     # Replace the magic function's docstring with the full help text.
156     magic_func.__doc__ = parser.format_help()
157 
158     return parser
159 
160 
161 def parse_argstring(magic_func, argstring):
162     """ Parse the string of arguments for the given magic function.
163     """
164     return magic_func.parser.parse_argstring(argstring)
165 
166 
167 def real_name(magic_func):
168     """ Find the real name of the magic.
169     """
170     magic_name = magic_func.__name__
171     if magic_name.startswith('magic_'):
172         magic_name = magic_name[len('magic_'):]
173     return getattr(magic_func, 'argcmd_name', magic_name)
174 
175 
176 class ArgDecorator(object):
177     """ Base class for decorators to add ArgumentParser information to a method.
178     """
179 
180     def __call__(self, func):
181         if not getattr(func, 'has_arguments', False):
182             func.has_arguments = True
183             func.decorators = []
184         func.decorators.append(self)
185         return func
186 
187     def add_to_parser(self, parser, group):
188         """ Add this object's information to the parser, if necessary.
189         """
190         pass
191 
192 
193 class magic_arguments(ArgDecorator):
194     """ Mark the magic as having argparse arguments and possibly adjust the
195     name.
196     """
197 
198     def __init__(self, name=None):
199         self.name = name
200 
201     def __call__(self, func):
202         if not getattr(func, 'has_arguments', False):
203             func.has_arguments = True
204             func.decorators = []
205         if self.name is not None:
206             func.argcmd_name = self.name
207         # This should be the first decorator in the list of decorators, thus the
208         # last to execute. Build the parser.
209         func.parser = construct_parser(func)
210         return func
211 
212 
213 class ArgMethodWrapper(ArgDecorator):
214 
215     """
216     Base class to define a wrapper for ArgumentParser method.
217 
218     Child class must define either `_method_name` or `add_to_parser`.
219 
220     """
221 
222     _method_name = None
223 
224     def __init__(self, *args, **kwds):
225         self.args = args
226         self.kwds = kwds
227 
228     def add_to_parser(self, parser, group):
229         """ Add this object's information to the parser.
230         """
231         if group is not None:
232             parser = group
233         getattr(parser, self._method_name)(*self.args, **self.kwds)
234         return None
235 
236 
237 class argument(ArgMethodWrapper):
238     """ Store arguments and keywords to pass to add_argument().
239 
240     Instances also serve to decorate command methods.
241     """
242     _method_name = 'add_argument'
243 
244 
245 class defaults(ArgMethodWrapper):
246     """ Store arguments and keywords to pass to set_defaults().
247 
248     Instances also serve to decorate command methods.
249     """
250     _method_name = 'set_defaults'
251 
252 
253 class argument_group(ArgMethodWrapper):
254     """ Store arguments and keywords to pass to add_argument_group().
255 
256     Instances also serve to decorate command methods.
257     """
258 
259     def add_to_parser(self, parser, group):
260         """ Add this object's information to the parser.
261         """
262         return parser.add_argument_group(*self.args, **self.kwds)
263 
264 
265 class kwds(ArgDecorator):
266     """ Provide other keywords to the sub-parser constructor.
267     """
268     def __init__(self, **kwds):
269         self.kwds = kwds
270 
271     def __call__(self, func):
272         func = super(kwds, self).__call__(func)
273         func.argcmd_kwds = self.kwds
274         return func
275 
276 
277 __all__ = ['magic_arguments', 'argument', 'argument_group', 'kwds',
278     'parse_argstring']
279
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/IPython/core/magic_arguments.py b/IPython/core/magic_arguments.py
--- a/IPython/core/magic_arguments.py
+++ b/IPython/core/magic_arguments.py
@@ -37,6 +37,38 @@
           -o OPTION, --option OPTION
                                 An optional argument.
 
+Here is an elaborated example that uses default parameters in `argument` and calls the `args` in the cell magic::
+
+    from IPython.core.magic import register_cell_magic
+    from IPython.core.magic_arguments import (argument, magic_arguments,
+                                            parse_argstring)
+
+
+    @magic_arguments()
+    @argument(
+        "--option",
+        "-o",
+        help=("Add an option here"),
+    )
+    @argument(
+        "--style",
+        "-s",
+        default="foo",
+        help=("Add some style arguments"),
+    )
+    @register_cell_magic
+    def my_cell_magic(line, cell):
+        args = parse_argstring(my_cell_magic, line)
+        print(f"{args.option=}")
+        print(f"{args.style=}")
+        print(f"{cell=}")
+
+In a jupyter notebook, this cell magic can be executed like this::
+
+    %%my_cell_magic -o Hello
+    print("bar")
+    i = 42
+
 Inheritance diagram:
 
 .. inheritance-diagram:: IPython.core.magic_arguments

{"golden_diff": "diff --git a/IPython/core/magic_arguments.py b/IPython/core/magic_arguments.py\n--- a/IPython/core/magic_arguments.py\n+++ b/IPython/core/magic_arguments.py\n@@ -37,6 +37,38 @@\n           -o OPTION, --option OPTION\n                                 An optional argument.\n \n+Here is an elaborated example that uses default parameters in `argument` and calls the `args` in the cell magic::\n+\n+    from IPython.core.magic import register_cell_magic\n+    from IPython.core.magic_arguments import (argument, magic_arguments,\n+                                            parse_argstring)\n+\n+\n+    @magic_arguments()\n+    @argument(\n+        \"--option\",\n+        \"-o\",\n+        help=(\"Add an option here\"),\n+    )\n+    @argument(\n+        \"--style\",\n+        \"-s\",\n+        default=\"foo\",\n+        help=(\"Add some style arguments\"),\n+    )\n+    @register_cell_magic\n+    def my_cell_magic(line, cell):\n+        args = parse_argstring(my_cell_magic, line)\n+        print(f\"{args.option=}\")\n+        print(f\"{args.style=}\")\n+        print(f\"{cell=}\")\n+\n+In a jupyter notebook, this cell magic can be executed like this::\n+\n+    %%my_cell_magic -o Hello\n+    print(\"bar\")\n+    i = 42\n+\n Inheritance diagram:\n \n .. inheritance-diagram:: IPython.core.magic_arguments\n", "issue": "Improvement of  `core.magic_arguments` example\nCurrently, there is only a [very raw example](https://ipython.readthedocs.io/en/stable/api/generated/IPython.core.magic_arguments.html?highlight=%40magic_arguments.argumen#module-IPython.core.magic_arguments\r\n) of using `magic_arguments` with custom cell magic.\r\nTherefore, I have the idea to add a second, more fleshed out example that might help people to easier understand and use cell magic arguments: \r\n![image](https://user-images.githubusercontent.com/44469195/148220767-d59ad4ca-e713-434a-8241-c212580fba6b.png)\r\nHere is the code:\r\n```py\r\nfrom IPython.core import magic_arguments\r\nfrom IPython.core.magic import register_cell_magic\r\n\r\n\r\n@magic_arguments.magic_arguments()\r\n@magic_arguments.argument(\r\n    \"--option\",\r\n    help=(\"Add an option here\"),\r\n)\r\n@magic_arguments.argument(\r\n    \"--style\",\r\n    default=None,\r\n    help=(\"Add some style arguments\"),\r\n)\r\n@register_cell_magic\r\ndef my_cell_magic(line, cell):\r\n    \"\"\"Cool cell magic\"\"\"\r\n    args = magic_arguments.parse_argstring(my_cell_magic, line)\r\n    print(args.style)\r\n    print(args.option)\r\n```\n", "before_files": [{"content": "''' A decorator-based method of constructing IPython magics with `argparse`\noption handling.\n\nNew magic functions can be defined like so::\n\n    from IPython.core.magic_arguments import (argument, magic_arguments,\n        parse_argstring)\n\n    @magic_arguments()\n    @argument('-o', '--option', help='An optional argument.')\n    @argument('arg', type=int, help='An integer positional argument.')\n    def magic_cool(self, arg):\n        \"\"\" A really cool magic command.\n\n    \"\"\"\n        args = parse_argstring(magic_cool, arg)\n        ...\n\nThe `@magic_arguments` decorator marks the function as having argparse arguments.\nThe `@argument` decorator adds an argument using the same syntax as argparse's\n`add_argument()` method. More sophisticated uses may also require the\n`@argument_group` or `@kwds` decorator to customize the formatting and the\nparsing.\n\nHelp text for the magic is automatically generated from the docstring and the\narguments::\n\n    In[1]: %cool?\n        %cool [-o OPTION] arg\n        \n        A really cool magic command.\n        \n        positional arguments:\n          arg                   An integer positional argument.\n        \n        optional arguments:\n          -o OPTION, --option OPTION\n                                An optional argument.\n\nInheritance diagram:\n\n.. inheritance-diagram:: IPython.core.magic_arguments\n   :parts: 3\n\n'''\n#-----------------------------------------------------------------------------\n# Copyright (C) 2010-2011, IPython Development Team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n#-----------------------------------------------------------------------------\nimport argparse\nimport re\n\n# Our own imports\nfrom IPython.core.error import UsageError\nfrom IPython.utils.decorators import undoc\nfrom IPython.utils.process import arg_split\nfrom IPython.utils.text import dedent\n\nNAME_RE = re.compile(r\"[a-zA-Z][a-zA-Z0-9_-]*$\")\n\n@undoc\nclass MagicHelpFormatter(argparse.RawDescriptionHelpFormatter):\n    \"\"\"A HelpFormatter with a couple of changes to meet our needs.\n    \"\"\"\n    # Modified to dedent text.\n    def _fill_text(self, text, width, indent):\n        return argparse.RawDescriptionHelpFormatter._fill_text(self, dedent(text), width, indent)\n\n    # Modified to wrap argument placeholders in <> where necessary.\n    def _format_action_invocation(self, action):\n        if not action.option_strings:\n            metavar, = self._metavar_formatter(action, action.dest)(1)\n            return metavar\n\n        else:\n            parts = []\n\n            # if the Optional doesn't take a value, format is:\n            #    -s, --long\n            if action.nargs == 0:\n                parts.extend(action.option_strings)\n\n            # if the Optional takes a value, format is:\n            #    -s ARGS, --long ARGS\n            else:\n                default = action.dest.upper()\n                args_string = self._format_args(action, default)\n                # IPYTHON MODIFICATION: If args_string is not a plain name, wrap\n                # it in <> so it's valid RST.\n                if not NAME_RE.match(args_string):\n                    args_string = \"<%s>\" % args_string\n                for option_string in action.option_strings:\n                    parts.append('%s %s' % (option_string, args_string))\n\n            return ', '.join(parts)\n\n    # Override the default prefix ('usage') to our % magic escape,\n    # in a code block.\n    def add_usage(self, usage, actions, groups, prefix=\"::\\n\\n  %\"):\n        super(MagicHelpFormatter, self).add_usage(usage, actions, groups, prefix)\n\nclass MagicArgumentParser(argparse.ArgumentParser):\n    \"\"\" An ArgumentParser tweaked for use by IPython magics.\n    \"\"\"\n    def __init__(self,\n                 prog=None,\n                 usage=None,\n                 description=None,\n                 epilog=None,\n                 parents=None,\n                 formatter_class=MagicHelpFormatter,\n                 prefix_chars='-',\n                 argument_default=None,\n                 conflict_handler='error',\n                 add_help=False):\n        if parents is None:\n            parents = []\n        super(MagicArgumentParser, self).__init__(prog=prog, usage=usage,\n            description=description, epilog=epilog,\n            parents=parents, formatter_class=formatter_class,\n            prefix_chars=prefix_chars, argument_default=argument_default,\n            conflict_handler=conflict_handler, add_help=add_help)\n\n    def error(self, message):\n        \"\"\" Raise a catchable error instead of exiting.\n        \"\"\"\n        raise UsageError(message)\n\n    def parse_argstring(self, argstring):\n        \"\"\" Split a string into an argument list and parse that argument list.\n        \"\"\"\n        argv = arg_split(argstring)\n        return self.parse_args(argv)\n\n\ndef construct_parser(magic_func):\n    \"\"\" Construct an argument parser using the function decorations.\n    \"\"\"\n    kwds = getattr(magic_func, 'argcmd_kwds', {})\n    if 'description' not in kwds:\n        kwds['description'] = getattr(magic_func, '__doc__', None)\n    arg_name = real_name(magic_func)\n    parser = MagicArgumentParser(arg_name, **kwds)\n    # Reverse the list of decorators in order to apply them in the\n    # order in which they appear in the source.\n    group = None\n    for deco in magic_func.decorators[::-1]:\n        result = deco.add_to_parser(parser, group)\n        if result is not None:\n            group = result\n\n    # Replace the magic function's docstring with the full help text.\n    magic_func.__doc__ = parser.format_help()\n\n    return parser\n\n\ndef parse_argstring(magic_func, argstring):\n    \"\"\" Parse the string of arguments for the given magic function.\n    \"\"\"\n    return magic_func.parser.parse_argstring(argstring)\n\n\ndef real_name(magic_func):\n    \"\"\" Find the real name of the magic.\n    \"\"\"\n    magic_name = magic_func.__name__\n    if magic_name.startswith('magic_'):\n        magic_name = magic_name[len('magic_'):]\n    return getattr(magic_func, 'argcmd_name', magic_name)\n\n\nclass ArgDecorator(object):\n    \"\"\" Base class for decorators to add ArgumentParser information to a method.\n    \"\"\"\n\n    def __call__(self, func):\n        if not getattr(func, 'has_arguments', False):\n            func.has_arguments = True\n            func.decorators = []\n        func.decorators.append(self)\n        return func\n\n    def add_to_parser(self, parser, group):\n        \"\"\" Add this object's information to the parser, if necessary.\n        \"\"\"\n        pass\n\n\nclass magic_arguments(ArgDecorator):\n    \"\"\" Mark the magic as having argparse arguments and possibly adjust the\n    name.\n    \"\"\"\n\n    def __init__(self, name=None):\n        self.name = name\n\n    def __call__(self, func):\n        if not getattr(func, 'has_arguments', False):\n            func.has_arguments = True\n            func.decorators = []\n        if self.name is not None:\n            func.argcmd_name = self.name\n        # This should be the first decorator in the list of decorators, thus the\n        # last to execute. Build the parser.\n        func.parser = construct_parser(func)\n        return func\n\n\nclass ArgMethodWrapper(ArgDecorator):\n\n    \"\"\"\n    Base class to define a wrapper for ArgumentParser method.\n\n    Child class must define either `_method_name` or `add_to_parser`.\n\n    \"\"\"\n\n    _method_name = None\n\n    def __init__(self, *args, **kwds):\n        self.args = args\n        self.kwds = kwds\n\n    def add_to_parser(self, parser, group):\n        \"\"\" Add this object's information to the parser.\n        \"\"\"\n        if group is not None:\n            parser = group\n        getattr(parser, self._method_name)(*self.args, **self.kwds)\n        return None\n\n\nclass argument(ArgMethodWrapper):\n    \"\"\" Store arguments and keywords to pass to add_argument().\n\n    Instances also serve to decorate command methods.\n    \"\"\"\n    _method_name = 'add_argument'\n\n\nclass defaults(ArgMethodWrapper):\n    \"\"\" Store arguments and keywords to pass to set_defaults().\n\n    Instances also serve to decorate command methods.\n    \"\"\"\n    _method_name = 'set_defaults'\n\n\nclass argument_group(ArgMethodWrapper):\n    \"\"\" Store arguments and keywords to pass to add_argument_group().\n\n    Instances also serve to decorate command methods.\n    \"\"\"\n\n    def add_to_parser(self, parser, group):\n        \"\"\" Add this object's information to the parser.\n        \"\"\"\n        return parser.add_argument_group(*self.args, **self.kwds)\n\n\nclass kwds(ArgDecorator):\n    \"\"\" Provide other keywords to the sub-parser constructor.\n    \"\"\"\n    def __init__(self, **kwds):\n        self.kwds = kwds\n\n    def __call__(self, func):\n        func = super(kwds, self).__call__(func)\n        func.argcmd_kwds = self.kwds\n        return func\n\n\n__all__ = ['magic_arguments', 'argument', 'argument_group', 'kwds',\n    'parse_argstring']\n", "path": "IPython/core/magic_arguments.py"}], "after_files": [{"content": "''' A decorator-based method of constructing IPython magics with `argparse`\noption handling.\n\nNew magic functions can be defined like so::\n\n    from IPython.core.magic_arguments import (argument, magic_arguments,\n        parse_argstring)\n\n    @magic_arguments()\n    @argument('-o', '--option', help='An optional argument.')\n    @argument('arg', type=int, help='An integer positional argument.')\n    def magic_cool(self, arg):\n        \"\"\" A really cool magic command.\n\n    \"\"\"\n        args = parse_argstring(magic_cool, arg)\n        ...\n\nThe `@magic_arguments` decorator marks the function as having argparse arguments.\nThe `@argument` decorator adds an argument using the same syntax as argparse's\n`add_argument()` method. More sophisticated uses may also require the\n`@argument_group` or `@kwds` decorator to customize the formatting and the\nparsing.\n\nHelp text for the magic is automatically generated from the docstring and the\narguments::\n\n    In[1]: %cool?\n        %cool [-o OPTION] arg\n        \n        A really cool magic command.\n        \n        positional arguments:\n          arg                   An integer positional argument.\n        \n        optional arguments:\n          -o OPTION, --option OPTION\n                                An optional argument.\n\nHere is an elaborated example that uses default parameters in `argument` and calls the `args` in the cell magic::\n\n    from IPython.core.magic import register_cell_magic\n    from IPython.core.magic_arguments import (argument, magic_arguments,\n                                            parse_argstring)\n\n\n    @magic_arguments()\n    @argument(\n        \"--option\",\n        \"-o\",\n        help=(\"Add an option here\"),\n    )\n    @argument(\n        \"--style\",\n        \"-s\",\n        default=\"foo\",\n        help=(\"Add some style arguments\"),\n    )\n    @register_cell_magic\n    def my_cell_magic(line, cell):\n        args = parse_argstring(my_cell_magic, line)\n        print(f\"{args.option=}\")\n        print(f\"{args.style=}\")\n        print(f\"{cell=}\")\n\nIn a jupyter notebook, this cell magic can be executed like this::\n\n    %%my_cell_magic -o Hello\n    print(\"bar\")\n    i = 42\n\nInheritance diagram:\n\n.. inheritance-diagram:: IPython.core.magic_arguments\n   :parts: 3\n\n'''\n#-----------------------------------------------------------------------------\n# Copyright (C) 2010-2011, IPython Development Team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n#-----------------------------------------------------------------------------\nimport argparse\nimport re\n\n# Our own imports\nfrom IPython.core.error import UsageError\nfrom IPython.utils.decorators import undoc\nfrom IPython.utils.process import arg_split\nfrom IPython.utils.text import dedent\n\nNAME_RE = re.compile(r\"[a-zA-Z][a-zA-Z0-9_-]*$\")\n\n@undoc\nclass MagicHelpFormatter(argparse.RawDescriptionHelpFormatter):\n    \"\"\"A HelpFormatter with a couple of changes to meet our needs.\n    \"\"\"\n    # Modified to dedent text.\n    def _fill_text(self, text, width, indent):\n        return argparse.RawDescriptionHelpFormatter._fill_text(self, dedent(text), width, indent)\n\n    # Modified to wrap argument placeholders in <> where necessary.\n    def _format_action_invocation(self, action):\n        if not action.option_strings:\n            metavar, = self._metavar_formatter(action, action.dest)(1)\n            return metavar\n\n        else:\n            parts = []\n\n            # if the Optional doesn't take a value, format is:\n            #    -s, --long\n            if action.nargs == 0:\n                parts.extend(action.option_strings)\n\n            # if the Optional takes a value, format is:\n            #    -s ARGS, --long ARGS\n            else:\n                default = action.dest.upper()\n                args_string = self._format_args(action, default)\n                # IPYTHON MODIFICATION: If args_string is not a plain name, wrap\n                # it in <> so it's valid RST.\n                if not NAME_RE.match(args_string):\n                    args_string = \"<%s>\" % args_string\n                for option_string in action.option_strings:\n                    parts.append('%s %s' % (option_string, args_string))\n\n            return ', '.join(parts)\n\n    # Override the default prefix ('usage') to our % magic escape,\n    # in a code block.\n    def add_usage(self, usage, actions, groups, prefix=\"::\\n\\n  %\"):\n        super(MagicHelpFormatter, self).add_usage(usage, actions, groups, prefix)\n\nclass MagicArgumentParser(argparse.ArgumentParser):\n    \"\"\" An ArgumentParser tweaked for use by IPython magics.\n    \"\"\"\n    def __init__(self,\n                 prog=None,\n                 usage=None,\n                 description=None,\n                 epilog=None,\n                 parents=None,\n                 formatter_class=MagicHelpFormatter,\n                 prefix_chars='-',\n                 argument_default=None,\n                 conflict_handler='error',\n                 add_help=False):\n        if parents is None:\n            parents = []\n        super(MagicArgumentParser, self).__init__(prog=prog, usage=usage,\n            description=description, epilog=epilog,\n            parents=parents, formatter_class=formatter_class,\n            prefix_chars=prefix_chars, argument_default=argument_default,\n            conflict_handler=conflict_handler, add_help=add_help)\n\n    def error(self, message):\n        \"\"\" Raise a catchable error instead of exiting.\n        \"\"\"\n        raise UsageError(message)\n\n    def parse_argstring(self, argstring):\n        \"\"\" Split a string into an argument list and parse that argument list.\n        \"\"\"\n        argv = arg_split(argstring)\n        return self.parse_args(argv)\n\n\ndef construct_parser(magic_func):\n    \"\"\" Construct an argument parser using the function decorations.\n    \"\"\"\n    kwds = getattr(magic_func, 'argcmd_kwds', {})\n    if 'description' not in kwds:\n        kwds['description'] = getattr(magic_func, '__doc__', None)\n    arg_name = real_name(magic_func)\n    parser = MagicArgumentParser(arg_name, **kwds)\n    # Reverse the list of decorators in order to apply them in the\n    # order in which they appear in the source.\n    group = None\n    for deco in magic_func.decorators[::-1]:\n        result = deco.add_to_parser(parser, group)\n        if result is not None:\n            group = result\n\n    # Replace the magic function's docstring with the full help text.\n    magic_func.__doc__ = parser.format_help()\n\n    return parser\n\n\ndef parse_argstring(magic_func, argstring):\n    \"\"\" Parse the string of arguments for the given magic function.\n    \"\"\"\n    return magic_func.parser.parse_argstring(argstring)\n\n\ndef real_name(magic_func):\n    \"\"\" Find the real name of the magic.\n    \"\"\"\n    magic_name = magic_func.__name__\n    if magic_name.startswith('magic_'):\n        magic_name = magic_name[len('magic_'):]\n    return getattr(magic_func, 'argcmd_name', magic_name)\n\n\nclass ArgDecorator(object):\n    \"\"\" Base class for decorators to add ArgumentParser information to a method.\n    \"\"\"\n\n    def __call__(self, func):\n        if not getattr(func, 'has_arguments', False):\n            func.has_arguments = True\n            func.decorators = []\n        func.decorators.append(self)\n        return func\n\n    def add_to_parser(self, parser, group):\n        \"\"\" Add this object's information to the parser, if necessary.\n        \"\"\"\n        pass\n\n\nclass magic_arguments(ArgDecorator):\n    \"\"\" Mark the magic as having argparse arguments and possibly adjust the\n    name.\n    \"\"\"\n\n    def __init__(self, name=None):\n        self.name = name\n\n    def __call__(self, func):\n        if not getattr(func, 'has_arguments', False):\n            func.has_arguments = True\n            func.decorators = []\n        if self.name is not None:\n            func.argcmd_name = self.name\n        # This should be the first decorator in the list of decorators, thus the\n        # last to execute. Build the parser.\n        func.parser = construct_parser(func)\n        return func\n\n\nclass ArgMethodWrapper(ArgDecorator):\n\n    \"\"\"\n    Base class to define a wrapper for ArgumentParser method.\n\n    Child class must define either `_method_name` or `add_to_parser`.\n\n    \"\"\"\n\n    _method_name = None\n\n    def __init__(self, *args, **kwds):\n        self.args = args\n        self.kwds = kwds\n\n    def add_to_parser(self, parser, group):\n        \"\"\" Add this object's information to the parser.\n        \"\"\"\n        if group is not None:\n            parser = group\n        getattr(parser, self._method_name)(*self.args, **self.kwds)\n        return None\n\n\nclass argument(ArgMethodWrapper):\n    \"\"\" Store arguments and keywords to pass to add_argument().\n\n    Instances also serve to decorate command methods.\n    \"\"\"\n    _method_name = 'add_argument'\n\n\nclass defaults(ArgMethodWrapper):\n    \"\"\" Store arguments and keywords to pass to set_defaults().\n\n    Instances also serve to decorate command methods.\n    \"\"\"\n    _method_name = 'set_defaults'\n\n\nclass argument_group(ArgMethodWrapper):\n    \"\"\" Store arguments and keywords to pass to add_argument_group().\n\n    Instances also serve to decorate command methods.\n    \"\"\"\n\n    def add_to_parser(self, parser, group):\n        \"\"\" Add this object's information to the parser.\n        \"\"\"\n        return parser.add_argument_group(*self.args, **self.kwds)\n\n\nclass kwds(ArgDecorator):\n    \"\"\" Provide other keywords to the sub-parser constructor.\n    \"\"\"\n    def __init__(self, **kwds):\n        self.kwds = kwds\n\n    def __call__(self, func):\n        func = super(kwds, self).__call__(func)\n        func.argcmd_kwds = self.kwds\n        return func\n\n\n__all__ = ['magic_arguments', 'argument', 'argument_group', 'kwds',\n    'parse_argstring']\n", "path": "IPython/core/magic_arguments.py"}]}