magic.py 25 KB

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