##// END OF EJS Templates
Remove deprecated "define_magic", that marked to be removed for 5.0
Matthias Bussonnier -
Show More
@@ -1,699 +1,680 b''
1 1 # encoding: utf-8
2 2 """Magic functions for InteractiveShell.
3 3 """
4 4 from __future__ import print_function
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 8 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
9 9 # Copyright (C) 2008 The IPython Development Team
10 10
11 11 # Distributed under the terms of the BSD License. The full license is in
12 12 # the file COPYING, distributed as part of this software.
13 13 #-----------------------------------------------------------------------------
14 14
15 15 import os
16 16 import re
17 17 import sys
18 18 import types
19 19 from getopt import getopt, GetoptError
20 20
21 21 from traitlets.config.configurable import Configurable
22 22 from IPython.core import oinspect
23 23 from IPython.core.error import UsageError
24 24 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
25 25 from decorator import decorator
26 26 from IPython.utils.ipstruct import Struct
27 27 from IPython.utils.process import arg_split
28 28 from IPython.utils.py3compat import string_types, iteritems
29 29 from IPython.utils.text import dedent
30 30 from traitlets import Bool, Dict, Instance, observe
31 31 from logging import error
32 32
33 33 #-----------------------------------------------------------------------------
34 34 # Globals
35 35 #-----------------------------------------------------------------------------
36 36
37 37 # A dict we'll use for each class that has magics, used as temporary storage to
38 38 # pass information between the @line/cell_magic method decorators and the
39 39 # @magics_class class decorator, because the method decorators have no
40 40 # access to the class when they run. See for more details:
41 41 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
42 42
43 43 magics = dict(line={}, cell={})
44 44
45 45 magic_kinds = ('line', 'cell')
46 46 magic_spec = ('line', 'cell', 'line_cell')
47 47 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
48 48
49 49 #-----------------------------------------------------------------------------
50 50 # Utility classes and functions
51 51 #-----------------------------------------------------------------------------
52 52
53 53 class Bunch: pass
54 54
55 55
56 56 def on_off(tag):
57 57 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
58 58 return ['OFF','ON'][tag]
59 59
60 60
61 61 def compress_dhist(dh):
62 62 """Compress a directory history into a new one with at most 20 entries.
63 63
64 64 Return a new list made from the first and last 10 elements of dhist after
65 65 removal of duplicates.
66 66 """
67 67 head, tail = dh[:-10], dh[-10:]
68 68
69 69 newhead = []
70 70 done = set()
71 71 for h in head:
72 72 if h in done:
73 73 continue
74 74 newhead.append(h)
75 75 done.add(h)
76 76
77 77 return newhead + tail
78 78
79 79
80 80 def needs_local_scope(func):
81 81 """Decorator to mark magic functions which need to local scope to run."""
82 82 func.needs_local_scope = True
83 83 return func
84 84
85 85 #-----------------------------------------------------------------------------
86 86 # Class and method decorators for registering magics
87 87 #-----------------------------------------------------------------------------
88 88
89 89 def magics_class(cls):
90 90 """Class decorator for all subclasses of the main Magics class.
91 91
92 92 Any class that subclasses Magics *must* also apply this decorator, to
93 93 ensure that all the methods that have been decorated as line/cell magics
94 94 get correctly registered in the class instance. This is necessary because
95 95 when method decorators run, the class does not exist yet, so they
96 96 temporarily store their information into a module global. Application of
97 97 this class decorator copies that global data to the class instance and
98 98 clears the global.
99 99
100 100 Obviously, this mechanism is not thread-safe, which means that the
101 101 *creation* of subclasses of Magic should only be done in a single-thread
102 102 context. Instantiation of the classes has no restrictions. Given that
103 103 these classes are typically created at IPython startup time and before user
104 104 application code becomes active, in practice this should not pose any
105 105 problems.
106 106 """
107 107 cls.registered = True
108 108 cls.magics = dict(line = magics['line'],
109 109 cell = magics['cell'])
110 110 magics['line'] = {}
111 111 magics['cell'] = {}
112 112 return cls
113 113
114 114
115 115 def record_magic(dct, magic_kind, magic_name, func):
116 116 """Utility function to store a function as a magic of a specific kind.
117 117
118 118 Parameters
119 119 ----------
120 120 dct : dict
121 121 A dictionary with 'line' and 'cell' subdicts.
122 122
123 123 magic_kind : str
124 124 Kind of magic to be stored.
125 125
126 126 magic_name : str
127 127 Key to store the magic as.
128 128
129 129 func : function
130 130 Callable object to store.
131 131 """
132 132 if magic_kind == 'line_cell':
133 133 dct['line'][magic_name] = dct['cell'][magic_name] = func
134 134 else:
135 135 dct[magic_kind][magic_name] = func
136 136
137 137
138 138 def validate_type(magic_kind):
139 139 """Ensure that the given magic_kind is valid.
140 140
141 141 Check that the given magic_kind is one of the accepted spec types (stored
142 142 in the global `magic_spec`), raise ValueError otherwise.
143 143 """
144 144 if magic_kind not in magic_spec:
145 145 raise ValueError('magic_kind must be one of %s, %s given' %
146 146 magic_kinds, magic_kind)
147 147
148 148
149 149 # The docstrings for the decorator below will be fairly similar for the two
150 150 # types (method and function), so we generate them here once and reuse the
151 151 # templates below.
152 152 _docstring_template = \
153 153 """Decorate the given {0} as {1} magic.
154 154
155 155 The decorator can be used with or without arguments, as follows.
156 156
157 157 i) without arguments: it will create a {1} magic named as the {0} being
158 158 decorated::
159 159
160 160 @deco
161 161 def foo(...)
162 162
163 163 will create a {1} magic named `foo`.
164 164
165 165 ii) with one string argument: which will be used as the actual name of the
166 166 resulting magic::
167 167
168 168 @deco('bar')
169 169 def foo(...)
170 170
171 171 will create a {1} magic named `bar`.
172 172 """
173 173
174 174 # These two are decorator factories. While they are conceptually very similar,
175 175 # there are enough differences in the details that it's simpler to have them
176 176 # written as completely standalone functions rather than trying to share code
177 177 # and make a single one with convoluted logic.
178 178
179 179 def _method_magic_marker(magic_kind):
180 180 """Decorator factory for methods in Magics subclasses.
181 181 """
182 182
183 183 validate_type(magic_kind)
184 184
185 185 # This is a closure to capture the magic_kind. We could also use a class,
186 186 # but it's overkill for just that one bit of state.
187 187 def magic_deco(arg):
188 188 call = lambda f, *a, **k: f(*a, **k)
189 189
190 190 if callable(arg):
191 191 # "Naked" decorator call (just @foo, no args)
192 192 func = arg
193 193 name = func.__name__
194 194 retval = decorator(call, func)
195 195 record_magic(magics, magic_kind, name, name)
196 196 elif isinstance(arg, string_types):
197 197 # Decorator called with arguments (@foo('bar'))
198 198 name = arg
199 199 def mark(func, *a, **kw):
200 200 record_magic(magics, magic_kind, name, func.__name__)
201 201 return decorator(call, func)
202 202 retval = mark
203 203 else:
204 204 raise TypeError("Decorator can only be called with "
205 205 "string or function")
206 206 return retval
207 207
208 208 # Ensure the resulting decorator has a usable docstring
209 209 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
210 210 return magic_deco
211 211
212 212
213 213 def _function_magic_marker(magic_kind):
214 214 """Decorator factory for standalone functions.
215 215 """
216 216 validate_type(magic_kind)
217 217
218 218 # This is a closure to capture the magic_kind. We could also use a class,
219 219 # but it's overkill for just that one bit of state.
220 220 def magic_deco(arg):
221 221 call = lambda f, *a, **k: f(*a, **k)
222 222
223 223 # Find get_ipython() in the caller's namespace
224 224 caller = sys._getframe(1)
225 225 for ns in ['f_locals', 'f_globals', 'f_builtins']:
226 226 get_ipython = getattr(caller, ns).get('get_ipython')
227 227 if get_ipython is not None:
228 228 break
229 229 else:
230 230 raise NameError('Decorator can only run in context where '
231 231 '`get_ipython` exists')
232 232
233 233 ip = get_ipython()
234 234
235 235 if callable(arg):
236 236 # "Naked" decorator call (just @foo, no args)
237 237 func = arg
238 238 name = func.__name__
239 239 ip.register_magic_function(func, magic_kind, name)
240 240 retval = decorator(call, func)
241 241 elif isinstance(arg, string_types):
242 242 # Decorator called with arguments (@foo('bar'))
243 243 name = arg
244 244 def mark(func, *a, **kw):
245 245 ip.register_magic_function(func, magic_kind, name)
246 246 return decorator(call, func)
247 247 retval = mark
248 248 else:
249 249 raise TypeError("Decorator can only be called with "
250 250 "string or function")
251 251 return retval
252 252
253 253 # Ensure the resulting decorator has a usable docstring
254 254 ds = _docstring_template.format('function', magic_kind)
255 255
256 256 ds += dedent("""
257 257 Note: this decorator can only be used in a context where IPython is already
258 258 active, so that the `get_ipython()` call succeeds. You can therefore use
259 259 it in your startup files loaded after IPython initializes, but *not* in the
260 260 IPython configuration file itself, which is executed before IPython is
261 261 fully up and running. Any file located in the `startup` subdirectory of
262 262 your configuration profile will be OK in this sense.
263 263 """)
264 264
265 265 magic_deco.__doc__ = ds
266 266 return magic_deco
267 267
268 268
269 269 # Create the actual decorators for public use
270 270
271 271 # These three are used to decorate methods in class definitions
272 272 line_magic = _method_magic_marker('line')
273 273 cell_magic = _method_magic_marker('cell')
274 274 line_cell_magic = _method_magic_marker('line_cell')
275 275
276 276 # These three decorate standalone functions and perform the decoration
277 277 # immediately. They can only run where get_ipython() works
278 278 register_line_magic = _function_magic_marker('line')
279 279 register_cell_magic = _function_magic_marker('cell')
280 280 register_line_cell_magic = _function_magic_marker('line_cell')
281 281
282 282 #-----------------------------------------------------------------------------
283 283 # Core Magic classes
284 284 #-----------------------------------------------------------------------------
285 285
286 286 class MagicsManager(Configurable):
287 287 """Object that handles all magic-related functionality for IPython.
288 288 """
289 289 # Non-configurable class attributes
290 290
291 291 # A two-level dict, first keyed by magic type, then by magic function, and
292 292 # holding the actual callable object as value. This is the dict used for
293 293 # magic function dispatch
294 294 magics = Dict()
295 295
296 296 # A registry of the original objects that we've been given holding magics.
297 297 registry = Dict()
298 298
299 299 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
300 300
301 301 auto_magic = Bool(True, help=
302 302 "Automatically call line magics without requiring explicit % prefix"
303 303 ).tag(config=True)
304 304 @observe('auto_magic')
305 305 def _auto_magic_changed(self, change):
306 306 self.shell.automagic = change['new']
307 307
308 308 _auto_status = [
309 309 'Automagic is OFF, % prefix IS needed for line magics.',
310 310 'Automagic is ON, % prefix IS NOT needed for line magics.']
311 311
312 312 user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True)
313 313
314 314 def __init__(self, shell=None, config=None, user_magics=None, **traits):
315 315
316 316 super(MagicsManager, self).__init__(shell=shell, config=config,
317 317 user_magics=user_magics, **traits)
318 318 self.magics = dict(line={}, cell={})
319 319 # Let's add the user_magics to the registry for uniformity, so *all*
320 320 # registered magic containers can be found there.
321 321 self.registry[user_magics.__class__.__name__] = user_magics
322 322
323 323 def auto_status(self):
324 324 """Return descriptive string with automagic status."""
325 325 return self._auto_status[self.auto_magic]
326 326
327 327 def lsmagic(self):
328 328 """Return a dict of currently available magic functions.
329 329
330 330 The return dict has the keys 'line' and 'cell', corresponding to the
331 331 two types of magics we support. Each value is a list of names.
332 332 """
333 333 return self.magics
334 334
335 335 def lsmagic_docs(self, brief=False, missing=''):
336 336 """Return dict of documentation of magic functions.
337 337
338 338 The return dict has the keys 'line' and 'cell', corresponding to the
339 339 two types of magics we support. Each value is a dict keyed by magic
340 340 name whose value is the function docstring. If a docstring is
341 341 unavailable, the value of `missing` is used instead.
342 342
343 343 If brief is True, only the first line of each docstring will be returned.
344 344 """
345 345 docs = {}
346 346 for m_type in self.magics:
347 347 m_docs = {}
348 348 for m_name, m_func in iteritems(self.magics[m_type]):
349 349 if m_func.__doc__:
350 350 if brief:
351 351 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
352 352 else:
353 353 m_docs[m_name] = m_func.__doc__.rstrip()
354 354 else:
355 355 m_docs[m_name] = missing
356 356 docs[m_type] = m_docs
357 357 return docs
358 358
359 359 def register(self, *magic_objects):
360 360 """Register one or more instances of Magics.
361 361
362 362 Take one or more classes or instances of classes that subclass the main
363 363 `core.Magic` class, and register them with IPython to use the magic
364 364 functions they provide. The registration process will then ensure that
365 365 any methods that have decorated to provide line and/or cell magics will
366 366 be recognized with the `%x`/`%%x` syntax as a line/cell magic
367 367 respectively.
368 368
369 369 If classes are given, they will be instantiated with the default
370 370 constructor. If your classes need a custom constructor, you should
371 371 instanitate them first and pass the instance.
372 372
373 373 The provided arguments can be an arbitrary mix of classes and instances.
374 374
375 375 Parameters
376 376 ----------
377 377 magic_objects : one or more classes or instances
378 378 """
379 379 # Start by validating them to ensure they have all had their magic
380 380 # methods registered at the instance level
381 381 for m in magic_objects:
382 382 if not m.registered:
383 383 raise ValueError("Class of magics %r was constructed without "
384 384 "the @register_magics class decorator")
385 385 if isinstance(m, type):
386 386 # If we're given an uninstantiated class
387 387 m = m(shell=self.shell)
388 388
389 389 # Now that we have an instance, we can register it and update the
390 390 # table of callables
391 391 self.registry[m.__class__.__name__] = m
392 392 for mtype in magic_kinds:
393 393 self.magics[mtype].update(m.magics[mtype])
394 394
395 395 def register_function(self, func, magic_kind='line', magic_name=None):
396 396 """Expose a standalone function as magic function for IPython.
397 397
398 398 This will create an IPython magic (line, cell or both) from a
399 399 standalone function. The functions should have the following
400 400 signatures:
401 401
402 402 * For line magics: `def f(line)`
403 403 * For cell magics: `def f(line, cell)`
404 404 * For a function that does both: `def f(line, cell=None)`
405 405
406 406 In the latter case, the function will be called with `cell==None` when
407 407 invoked as `%f`, and with cell as a string when invoked as `%%f`.
408 408
409 409 Parameters
410 410 ----------
411 411 func : callable
412 412 Function to be registered as a magic.
413 413
414 414 magic_kind : str
415 415 Kind of magic, one of 'line', 'cell' or 'line_cell'
416 416
417 417 magic_name : optional str
418 418 If given, the name the magic will have in the IPython namespace. By
419 419 default, the name of the function itself is used.
420 420 """
421 421
422 422 # Create the new method in the user_magics and register it in the
423 423 # global table
424 424 validate_type(magic_kind)
425 425 magic_name = func.__name__ if magic_name is None else magic_name
426 426 setattr(self.user_magics, magic_name, func)
427 427 record_magic(self.magics, magic_kind, magic_name, func)
428 428
429 def define_magic(self, name, func):
430 """[Deprecated] Expose own function as magic function for IPython.
431
432 Will be removed in IPython 5.0
433
434 Example::
435
436 def foo_impl(self, parameter_s=''):
437 'My very own magic!. (Use docstrings, IPython reads them).'
438 print 'Magic function. Passed parameter is between < >:'
439 print '<%s>' % parameter_s
440 print 'The self object is:', self
441
442 ip.define_magic('foo',foo_impl)
443 """
444 meth = types.MethodType(func, self.user_magics)
445 setattr(self.user_magics, name, meth)
446 record_magic(self.magics, 'line', name, meth)
447
448 429 def register_alias(self, alias_name, magic_name, magic_kind='line'):
449 430 """Register an alias to a magic function.
450 431
451 432 The alias is an instance of :class:`MagicAlias`, which holds the
452 433 name and kind of the magic it should call. Binding is done at
453 434 call time, so if the underlying magic function is changed the alias
454 435 will call the new function.
455 436
456 437 Parameters
457 438 ----------
458 439 alias_name : str
459 440 The name of the magic to be registered.
460 441
461 442 magic_name : str
462 443 The name of an existing magic.
463 444
464 445 magic_kind : str
465 446 Kind of magic, one of 'line' or 'cell'
466 447 """
467 448
468 449 # `validate_type` is too permissive, as it allows 'line_cell'
469 450 # which we do not handle.
470 451 if magic_kind not in magic_kinds:
471 452 raise ValueError('magic_kind must be one of %s, %s given' %
472 453 magic_kinds, magic_kind)
473 454
474 455 alias = MagicAlias(self.shell, magic_name, magic_kind)
475 456 setattr(self.user_magics, alias_name, alias)
476 457 record_magic(self.magics, magic_kind, alias_name, alias)
477 458
478 459 # Key base class that provides the central functionality for magics.
479 460
480 461
481 462 class Magics(Configurable):
482 463 """Base class for implementing magic functions.
483 464
484 465 Shell functions which can be reached as %function_name. All magic
485 466 functions should accept a string, which they can parse for their own
486 467 needs. This can make some functions easier to type, eg `%cd ../`
487 468 vs. `%cd("../")`
488 469
489 470 Classes providing magic functions need to subclass this class, and they
490 471 MUST:
491 472
492 473 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
493 474 individual methods as magic functions, AND
494 475
495 476 - Use the class decorator `@magics_class` to ensure that the magic
496 477 methods are properly registered at the instance level upon instance
497 478 initialization.
498 479
499 480 See :mod:`magic_functions` for examples of actual implementation classes.
500 481 """
501 482 # Dict holding all command-line options for each magic.
502 483 options_table = None
503 484 # Dict for the mapping of magic names to methods, set by class decorator
504 485 magics = None
505 486 # Flag to check that the class decorator was properly applied
506 487 registered = False
507 488 # Instance of IPython shell
508 489 shell = None
509 490
510 491 def __init__(self, shell=None, **kwargs):
511 492 if not(self.__class__.registered):
512 493 raise ValueError('Magics subclass without registration - '
513 494 'did you forget to apply @magics_class?')
514 495 if shell is not None:
515 496 if hasattr(shell, 'configurables'):
516 497 shell.configurables.append(self)
517 498 if hasattr(shell, 'config'):
518 499 kwargs.setdefault('parent', shell)
519 500
520 501 self.shell = shell
521 502 self.options_table = {}
522 503 # The method decorators are run when the instance doesn't exist yet, so
523 504 # they can only record the names of the methods they are supposed to
524 505 # grab. Only now, that the instance exists, can we create the proper
525 506 # mapping to bound methods. So we read the info off the original names
526 507 # table and replace each method name by the actual bound method.
527 508 # But we mustn't clobber the *class* mapping, in case of multiple instances.
528 509 class_magics = self.magics
529 510 self.magics = {}
530 511 for mtype in magic_kinds:
531 512 tab = self.magics[mtype] = {}
532 513 cls_tab = class_magics[mtype]
533 514 for magic_name, meth_name in iteritems(cls_tab):
534 515 if isinstance(meth_name, string_types):
535 516 # it's a method name, grab it
536 517 tab[magic_name] = getattr(self, meth_name)
537 518 else:
538 519 # it's the real thing
539 520 tab[magic_name] = meth_name
540 521 # Configurable **needs** to be initiated at the end or the config
541 522 # magics get screwed up.
542 523 super(Magics, self).__init__(**kwargs)
543 524
544 525 def arg_err(self,func):
545 526 """Print docstring if incorrect arguments were passed"""
546 527 print('Error in arguments:')
547 528 print(oinspect.getdoc(func))
548 529
549 530 def format_latex(self, strng):
550 531 """Format a string for latex inclusion."""
551 532
552 533 # Characters that need to be escaped for latex:
553 534 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
554 535 # Magic command names as headers:
555 536 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
556 537 re.MULTILINE)
557 538 # Magic commands
558 539 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
559 540 re.MULTILINE)
560 541 # Paragraph continue
561 542 par_re = re.compile(r'\\$',re.MULTILINE)
562 543
563 544 # The "\n" symbol
564 545 newline_re = re.compile(r'\\n')
565 546
566 547 # Now build the string for output:
567 548 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
568 549 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
569 550 strng)
570 551 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
571 552 strng = par_re.sub(r'\\\\',strng)
572 553 strng = escape_re.sub(r'\\\1',strng)
573 554 strng = newline_re.sub(r'\\textbackslash{}n',strng)
574 555 return strng
575 556
576 557 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
577 558 """Parse options passed to an argument string.
578 559
579 560 The interface is similar to that of :func:`getopt.getopt`, but it
580 561 returns a :class:`~IPython.utils.struct.Struct` with the options as keys
581 562 and the stripped argument string still as a string.
582 563
583 564 arg_str is quoted as a true sys.argv vector by using shlex.split.
584 565 This allows us to easily expand variables, glob files, quote
585 566 arguments, etc.
586 567
587 568 Parameters
588 569 ----------
589 570
590 571 arg_str : str
591 572 The arguments to parse.
592 573
593 574 opt_str : str
594 575 The options specification.
595 576
596 577 mode : str, default 'string'
597 578 If given as 'list', the argument string is returned as a list (split
598 579 on whitespace) instead of a string.
599 580
600 581 list_all : bool, default False
601 582 Put all option values in lists. Normally only options
602 583 appearing more than once are put in a list.
603 584
604 585 posix : bool, default True
605 586 Whether to split the input line in POSIX mode or not, as per the
606 587 conventions outlined in the :mod:`shlex` module from the standard
607 588 library.
608 589 """
609 590
610 591 # inject default options at the beginning of the input line
611 592 caller = sys._getframe(1).f_code.co_name
612 593 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
613 594
614 595 mode = kw.get('mode','string')
615 596 if mode not in ['string','list']:
616 597 raise ValueError('incorrect mode given: %s' % mode)
617 598 # Get options
618 599 list_all = kw.get('list_all',0)
619 600 posix = kw.get('posix', os.name == 'posix')
620 601 strict = kw.get('strict', True)
621 602
622 603 # Check if we have more than one argument to warrant extra processing:
623 604 odict = {} # Dictionary with options
624 605 args = arg_str.split()
625 606 if len(args) >= 1:
626 607 # If the list of inputs only has 0 or 1 thing in it, there's no
627 608 # need to look for options
628 609 argv = arg_split(arg_str, posix, strict)
629 610 # Do regular option processing
630 611 try:
631 612 opts,args = getopt(argv, opt_str, long_opts)
632 613 except GetoptError as e:
633 614 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
634 615 " ".join(long_opts)))
635 616 for o,a in opts:
636 617 if o.startswith('--'):
637 618 o = o[2:]
638 619 else:
639 620 o = o[1:]
640 621 try:
641 622 odict[o].append(a)
642 623 except AttributeError:
643 624 odict[o] = [odict[o],a]
644 625 except KeyError:
645 626 if list_all:
646 627 odict[o] = [a]
647 628 else:
648 629 odict[o] = a
649 630
650 631 # Prepare opts,args for return
651 632 opts = Struct(odict)
652 633 if mode == 'string':
653 634 args = ' '.join(args)
654 635
655 636 return opts,args
656 637
657 638 def default_option(self, fn, optstr):
658 639 """Make an entry in the options_table for fn, with value optstr"""
659 640
660 641 if fn not in self.lsmagic():
661 642 error("%s is not a magic function" % fn)
662 643 self.options_table[fn] = optstr
663 644
664 645
665 646 class MagicAlias(object):
666 647 """An alias to another magic function.
667 648
668 649 An alias is determined by its magic name and magic kind. Lookup
669 650 is done at call time, so if the underlying magic changes the alias
670 651 will call the new function.
671 652
672 653 Use the :meth:`MagicsManager.register_alias` method or the
673 654 `%alias_magic` magic function to create and register a new alias.
674 655 """
675 656 def __init__(self, shell, magic_name, magic_kind):
676 657 self.shell = shell
677 658 self.magic_name = magic_name
678 659 self.magic_kind = magic_kind
679 660
680 661 self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
681 662 self.__doc__ = "Alias for `%s`." % self.pretty_target
682 663
683 664 self._in_call = False
684 665
685 666 def __call__(self, *args, **kwargs):
686 667 """Call the magic alias."""
687 668 fn = self.shell.find_magic(self.magic_name, self.magic_kind)
688 669 if fn is None:
689 670 raise UsageError("Magic `%s` not found." % self.pretty_target)
690 671
691 672 # Protect against infinite recursion.
692 673 if self._in_call:
693 674 raise UsageError("Infinite recursion detected; "
694 675 "magic aliases cannot call themselves.")
695 676 self._in_call = True
696 677 try:
697 678 return fn(*args, **kwargs)
698 679 finally:
699 680 self._in_call = False
General Comments 0
You need to be logged in to leave comments. Login now