config.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. """Implementation of configuration-related magic functions.
  2. """
  3. from __future__ import print_function
  4. from __future__ import absolute_import
  5. #-----------------------------------------------------------------------------
  6. # Copyright (c) 2012 The IPython Development Team.
  7. #
  8. # Distributed under the terms of the Modified BSD License.
  9. #
  10. # The full license is in the file COPYING.txt, distributed with this software.
  11. #-----------------------------------------------------------------------------
  12. #-----------------------------------------------------------------------------
  13. # Imports
  14. #-----------------------------------------------------------------------------
  15. # Stdlib
  16. import re
  17. # Our own packages
  18. from IPython.core.error import UsageError
  19. from IPython.core.magic import Magics, magics_class, line_magic
  20. from logging import error
  21. #-----------------------------------------------------------------------------
  22. # Magic implementation classes
  23. #-----------------------------------------------------------------------------
  24. reg = re.compile('^\w+\.\w+$')
  25. @magics_class
  26. class ConfigMagics(Magics):
  27. def __init__(self, shell):
  28. super(ConfigMagics, self).__init__(shell)
  29. self.configurables = []
  30. @line_magic
  31. def config(self, s):
  32. """configure IPython
  33. %config Class[.trait=value]
  34. This magic exposes most of the IPython config system. Any
  35. Configurable class should be able to be configured with the simple
  36. line::
  37. %config Class.trait=value
  38. Where `value` will be resolved in the user's namespace, if it is an
  39. expression or variable name.
  40. Examples
  41. --------
  42. To see what classes are available for config, pass no arguments::
  43. In [1]: %config
  44. Available objects for config:
  45. TerminalInteractiveShell
  46. HistoryManager
  47. PrefilterManager
  48. AliasManager
  49. IPCompleter
  50. DisplayFormatter
  51. To view what is configurable on a given class, just pass the class
  52. name::
  53. In [2]: %config IPCompleter
  54. IPCompleter options
  55. -----------------
  56. IPCompleter.omit__names=<Enum>
  57. Current: 2
  58. Choices: (0, 1, 2)
  59. Instruct the completer to omit private method names
  60. Specifically, when completing on ``object.<tab>``.
  61. When 2 [default]: all names that start with '_' will be excluded.
  62. When 1: all 'magic' names (``__foo__``) will be excluded.
  63. When 0: nothing will be excluded.
  64. IPCompleter.merge_completions=<CBool>
  65. Current: True
  66. Whether to merge completion results into a single list
  67. If False, only the completion results from the first non-empty
  68. completer will be returned.
  69. IPCompleter.limit_to__all__=<CBool>
  70. Current: False
  71. Instruct the completer to use __all__ for the completion
  72. Specifically, when completing on ``object.<tab>``.
  73. When True: only those names in obj.__all__ will be included.
  74. When False [default]: the __all__ attribute is ignored
  75. IPCompleter.greedy=<CBool>
  76. Current: False
  77. Activate greedy completion
  78. This will enable completion on elements of lists, results of
  79. function calls, etc., but can be unsafe because the code is
  80. actually evaluated on TAB.
  81. but the real use is in setting values::
  82. In [3]: %config IPCompleter.greedy = True
  83. and these values are read from the user_ns if they are variables::
  84. In [4]: feeling_greedy=False
  85. In [5]: %config IPCompleter.greedy = feeling_greedy
  86. """
  87. from traitlets.config.loader import Config
  88. # some IPython objects are Configurable, but do not yet have
  89. # any configurable traits. Exclude them from the effects of
  90. # this magic, as their presence is just noise:
  91. configurables = [ c for c in self.shell.configurables
  92. if c.__class__.class_traits(config=True) ]
  93. classnames = [ c.__class__.__name__ for c in configurables ]
  94. line = s.strip()
  95. if not line:
  96. # print available configurable names
  97. print("Available objects for config:")
  98. for name in classnames:
  99. print(" ", name)
  100. return
  101. elif line in classnames:
  102. # `%config TerminalInteractiveShell` will print trait info for
  103. # TerminalInteractiveShell
  104. c = configurables[classnames.index(line)]
  105. cls = c.__class__
  106. help = cls.class_get_help(c)
  107. # strip leading '--' from cl-args:
  108. help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
  109. print(help)
  110. return
  111. elif reg.match(line):
  112. cls, attr = line.split('.')
  113. return getattr(configurables[classnames.index(cls)],attr)
  114. elif '=' not in line:
  115. msg = "Invalid config statement: %r, "\
  116. "should be `Class.trait = value`."
  117. ll = line.lower()
  118. for classname in classnames:
  119. if ll == classname.lower():
  120. msg = msg + '\nDid you mean %s (note the case)?' % classname
  121. break
  122. raise UsageError( msg % line)
  123. # otherwise, assume we are setting configurables.
  124. # leave quotes on args when splitting, because we want
  125. # unquoted args to eval in user_ns
  126. cfg = Config()
  127. exec("cfg."+line, locals(), self.shell.user_ns)
  128. for configurable in configurables:
  129. try:
  130. configurable.update_config(cfg)
  131. except Exception as e:
  132. error(e)