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