##// END OF EJS Templates
Consolidate code to check for method in IPython.utils.dir2
Thomas Kluyver -
Show More
@@ -1,1289 +1,1277 b''
1 1 # encoding: utf-8
2 2 """Word completion for IPython.
3 3
4 4 This module is a fork of the rlcompleter module in the Python standard
5 5 library. The original enhancements made to rlcompleter have been sent
6 6 upstream and were accepted as of Python 2.3, but we need a lot more
7 7 functionality specific to IPython, so this module will continue to live as an
8 8 IPython-specific utility.
9 9
10 10 Original rlcompleter documentation:
11 11
12 12 This requires the latest extension to the readline module (the
13 13 completes keywords, built-ins and globals in __main__; when completing
14 14 NAME.NAME..., it evaluates (!) the expression up to the last dot and
15 15 completes its attributes.
16 16
17 17 It's very cool to do "import string" type "string.", hit the
18 18 completion key (twice), and see the list of names defined by the
19 19 string module!
20 20
21 21 Tip: to use the tab key as the completion key, call
22 22
23 23 readline.parse_and_bind("tab: complete")
24 24
25 25 Notes:
26 26
27 27 - Exceptions raised by the completer function are *ignored* (and
28 28 generally cause the completion to fail). This is a feature -- since
29 29 readline sets the tty device in raw (or cbreak) mode, printing a
30 30 traceback wouldn't work well without some complicated hoopla to save,
31 31 reset and restore the tty state.
32 32
33 33 - The evaluation of the NAME.NAME... form may cause arbitrary
34 34 application defined code to be executed if an object with a
35 35 ``__getattr__`` hook is found. Since it is the responsibility of the
36 36 application (or the user) to enable this feature, I consider this an
37 37 acceptable risk. More complicated expressions (e.g. function calls or
38 38 indexing operations) are *not* evaluated.
39 39
40 40 - GNU readline is also used by the built-in functions input() and
41 41 raw_input(), and thus these also benefit/suffer from the completer
42 42 features. Clearly an interactive application can benefit by
43 43 specifying its own completer function and using raw_input() for all
44 44 its input.
45 45
46 46 - When the original stdin is not a tty device, GNU readline is never
47 47 used, and this module (and the readline module) are silently inactive.
48 48 """
49 49
50 50 # Copyright (c) IPython Development Team.
51 51 # Distributed under the terms of the Modified BSD License.
52 52 #
53 53 # Some of this code originated from rlcompleter in the Python standard library
54 54 # Copyright (C) 2001 Python Software Foundation, www.python.org
55 55
56 56 import __main__
57 57 import glob
58 58 import inspect
59 59 import itertools
60 60 import keyword
61 61 import os
62 62 import re
63 63 import sys
64 64 import unicodedata
65 65 import string
66 66
67 67 from traitlets.config.configurable import Configurable
68 68 from IPython.core.error import TryNext
69 69 from IPython.core.inputsplitter import ESC_MAGIC
70 70 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
71 71 from IPython.utils import generics
72 72 from IPython.utils import io
73 73 from IPython.utils.decorators import undoc
74 from IPython.utils.dir2 import dir2, safe_hasattr
74 from IPython.utils.dir2 import dir2, get_real_method
75 75 from IPython.utils.process import arg_split
76 76 from IPython.utils.py3compat import builtin_mod, string_types, PY3
77 77 from traitlets import CBool, Enum
78 78
79 79 #-----------------------------------------------------------------------------
80 80 # Globals
81 81 #-----------------------------------------------------------------------------
82 82
83 83 # Public API
84 84 __all__ = ['Completer','IPCompleter']
85 85
86 86 if sys.platform == 'win32':
87 87 PROTECTABLES = ' '
88 88 else:
89 89 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
90 90
91 91
92 92 #-----------------------------------------------------------------------------
93 93 # Main functions and classes
94 94 #-----------------------------------------------------------------------------
95 95
96 96 def has_open_quotes(s):
97 97 """Return whether a string has open quotes.
98 98
99 99 This simply counts whether the number of quote characters of either type in
100 100 the string is odd.
101 101
102 102 Returns
103 103 -------
104 104 If there is an open quote, the quote character is returned. Else, return
105 105 False.
106 106 """
107 107 # We check " first, then ', so complex cases with nested quotes will get
108 108 # the " to take precedence.
109 109 if s.count('"') % 2:
110 110 return '"'
111 111 elif s.count("'") % 2:
112 112 return "'"
113 113 else:
114 114 return False
115 115
116 116
117 117 def protect_filename(s):
118 118 """Escape a string to protect certain characters."""
119 119
120 120 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
121 121 for ch in s])
122 122
123 123 def expand_user(path):
124 124 """Expand '~'-style usernames in strings.
125 125
126 126 This is similar to :func:`os.path.expanduser`, but it computes and returns
127 127 extra information that will be useful if the input was being used in
128 128 computing completions, and you wish to return the completions with the
129 129 original '~' instead of its expanded value.
130 130
131 131 Parameters
132 132 ----------
133 133 path : str
134 134 String to be expanded. If no ~ is present, the output is the same as the
135 135 input.
136 136
137 137 Returns
138 138 -------
139 139 newpath : str
140 140 Result of ~ expansion in the input path.
141 141 tilde_expand : bool
142 142 Whether any expansion was performed or not.
143 143 tilde_val : str
144 144 The value that ~ was replaced with.
145 145 """
146 146 # Default values
147 147 tilde_expand = False
148 148 tilde_val = ''
149 149 newpath = path
150 150
151 151 if path.startswith('~'):
152 152 tilde_expand = True
153 153 rest = len(path)-1
154 154 newpath = os.path.expanduser(path)
155 155 if rest:
156 156 tilde_val = newpath[:-rest]
157 157 else:
158 158 tilde_val = newpath
159 159
160 160 return newpath, tilde_expand, tilde_val
161 161
162 162
163 163 def compress_user(path, tilde_expand, tilde_val):
164 164 """Does the opposite of expand_user, with its outputs.
165 165 """
166 166 if tilde_expand:
167 167 return path.replace(tilde_val, '~')
168 168 else:
169 169 return path
170 170
171 171
172 172
173 173 def completions_sorting_key(word):
174 174 """key for sorting completions
175 175
176 176 This does several things:
177 177
178 178 - Lowercase all completions, so they are sorted alphabetically with
179 179 upper and lower case words mingled
180 180 - Demote any completions starting with underscores to the end
181 181 - Insert any %magic and %%cellmagic completions in the alphabetical order
182 182 by their name
183 183 """
184 184 # Case insensitive sort
185 185 word = word.lower()
186 186
187 187 prio1, prio2 = 0, 0
188 188
189 189 if word.startswith('__'):
190 190 prio1 = 2
191 191 elif word.startswith('_'):
192 192 prio1 = 1
193 193
194 194 if word.startswith('%%'):
195 195 # If there's another % in there, this is something else, so leave it alone
196 196 if not "%" in word[2:]:
197 197 word = word[2:]
198 198 prio2 = 2
199 199 elif word.startswith('%'):
200 200 if not "%" in word[1:]:
201 201 word = word[1:]
202 202 prio2 = 1
203 203
204 204 return prio1, word, prio2
205 205
206 206
207 207 @undoc
208 208 class Bunch(object): pass
209 209
210 210
211 211 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
212 212 GREEDY_DELIMS = ' =\r\n'
213 213
214 214
215 215 class CompletionSplitter(object):
216 216 """An object to split an input line in a manner similar to readline.
217 217
218 218 By having our own implementation, we can expose readline-like completion in
219 219 a uniform manner to all frontends. This object only needs to be given the
220 220 line of text to be split and the cursor position on said line, and it
221 221 returns the 'word' to be completed on at the cursor after splitting the
222 222 entire line.
223 223
224 224 What characters are used as splitting delimiters can be controlled by
225 225 setting the `delims` attribute (this is a property that internally
226 226 automatically builds the necessary regular expression)"""
227 227
228 228 # Private interface
229 229
230 230 # A string of delimiter characters. The default value makes sense for
231 231 # IPython's most typical usage patterns.
232 232 _delims = DELIMS
233 233
234 234 # The expression (a normal string) to be compiled into a regular expression
235 235 # for actual splitting. We store it as an attribute mostly for ease of
236 236 # debugging, since this type of code can be so tricky to debug.
237 237 _delim_expr = None
238 238
239 239 # The regular expression that does the actual splitting
240 240 _delim_re = None
241 241
242 242 def __init__(self, delims=None):
243 243 delims = CompletionSplitter._delims if delims is None else delims
244 244 self.delims = delims
245 245
246 246 @property
247 247 def delims(self):
248 248 """Return the string of delimiter characters."""
249 249 return self._delims
250 250
251 251 @delims.setter
252 252 def delims(self, delims):
253 253 """Set the delimiters for line splitting."""
254 254 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
255 255 self._delim_re = re.compile(expr)
256 256 self._delims = delims
257 257 self._delim_expr = expr
258 258
259 259 def split_line(self, line, cursor_pos=None):
260 260 """Split a line of text with a cursor at the given position.
261 261 """
262 262 l = line if cursor_pos is None else line[:cursor_pos]
263 263 return self._delim_re.split(l)[-1]
264 264
265 265
266 266 class Completer(Configurable):
267 267
268 268 greedy = CBool(False, config=True,
269 269 help="""Activate greedy completion
270 270
271 271 This will enable completion on elements of lists, results of function calls, etc.,
272 272 but can be unsafe because the code is actually evaluated on TAB.
273 273 """
274 274 )
275 275
276 276
277 277 def __init__(self, namespace=None, global_namespace=None, **kwargs):
278 278 """Create a new completer for the command line.
279 279
280 280 Completer(namespace=ns,global_namespace=ns2) -> completer instance.
281 281
282 282 If unspecified, the default namespace where completions are performed
283 283 is __main__ (technically, __main__.__dict__). Namespaces should be
284 284 given as dictionaries.
285 285
286 286 An optional second namespace can be given. This allows the completer
287 287 to handle cases where both the local and global scopes need to be
288 288 distinguished.
289 289
290 290 Completer instances should be used as the completion mechanism of
291 291 readline via the set_completer() call:
292 292
293 293 readline.set_completer(Completer(my_namespace).complete)
294 294 """
295 295
296 296 # Don't bind to namespace quite yet, but flag whether the user wants a
297 297 # specific namespace or to use __main__.__dict__. This will allow us
298 298 # to bind to __main__.__dict__ at completion time, not now.
299 299 if namespace is None:
300 300 self.use_main_ns = 1
301 301 else:
302 302 self.use_main_ns = 0
303 303 self.namespace = namespace
304 304
305 305 # The global namespace, if given, can be bound directly
306 306 if global_namespace is None:
307 307 self.global_namespace = {}
308 308 else:
309 309 self.global_namespace = global_namespace
310 310
311 311 super(Completer, self).__init__(**kwargs)
312 312
313 313 def complete(self, text, state):
314 314 """Return the next possible completion for 'text'.
315 315
316 316 This is called successively with state == 0, 1, 2, ... until it
317 317 returns None. The completion should begin with 'text'.
318 318
319 319 """
320 320 if self.use_main_ns:
321 321 self.namespace = __main__.__dict__
322 322
323 323 if state == 0:
324 324 if "." in text:
325 325 self.matches = self.attr_matches(text)
326 326 else:
327 327 self.matches = self.global_matches(text)
328 328 try:
329 329 return self.matches[state]
330 330 except IndexError:
331 331 return None
332 332
333 333 def global_matches(self, text):
334 334 """Compute matches when text is a simple name.
335 335
336 336 Return a list of all keywords, built-in functions and names currently
337 337 defined in self.namespace or self.global_namespace that match.
338 338
339 339 """
340 340 #print 'Completer->global_matches, txt=%r' % text # dbg
341 341 matches = []
342 342 match_append = matches.append
343 343 n = len(text)
344 344 for lst in [keyword.kwlist,
345 345 builtin_mod.__dict__.keys(),
346 346 self.namespace.keys(),
347 347 self.global_namespace.keys()]:
348 348 for word in lst:
349 349 if word[:n] == text and word != "__builtins__":
350 350 match_append(word)
351 351 return matches
352 352
353 353 def attr_matches(self, text):
354 354 """Compute matches when text contains a dot.
355 355
356 356 Assuming the text is of the form NAME.NAME....[NAME], and is
357 357 evaluatable in self.namespace or self.global_namespace, it will be
358 358 evaluated and its attributes (as revealed by dir()) are used as
359 359 possible completions. (For class instances, class members are are
360 360 also considered.)
361 361
362 362 WARNING: this can still invoke arbitrary C code, if an object
363 363 with a __getattr__ hook is evaluated.
364 364
365 365 """
366 366
367 367 #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg
368 368 # Another option, seems to work great. Catches things like ''.<tab>
369 369 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
370 370
371 371 if m:
372 372 expr, attr = m.group(1, 3)
373 373 elif self.greedy:
374 374 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
375 375 if not m2:
376 376 return []
377 377 expr, attr = m2.group(1,2)
378 378 else:
379 379 return []
380 380
381 381 try:
382 382 obj = eval(expr, self.namespace)
383 383 except:
384 384 try:
385 385 obj = eval(expr, self.global_namespace)
386 386 except:
387 387 return []
388 388
389 389 if self.limit_to__all__ and hasattr(obj, '__all__'):
390 390 words = get__all__entries(obj)
391 391 else:
392 392 words = dir2(obj)
393 393
394 394 try:
395 395 words = generics.complete_object(obj, words)
396 396 except TryNext:
397 397 pass
398 398 except Exception:
399 399 # Silence errors from completion function
400 400 #raise # dbg
401 401 pass
402 402 # Build match list to return
403 403 n = len(attr)
404 404 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
405 405 return res
406 406
407 407
408 408 def get__all__entries(obj):
409 409 """returns the strings in the __all__ attribute"""
410 410 try:
411 411 words = getattr(obj, '__all__')
412 412 except:
413 413 return []
414 414
415 415 return [w for w in words if isinstance(w, string_types)]
416 416
417 417
418 418 def match_dict_keys(keys, prefix, delims):
419 419 """Used by dict_key_matches, matching the prefix to a list of keys"""
420 420 if not prefix:
421 421 return None, 0, [repr(k) for k in keys
422 422 if isinstance(k, (string_types, bytes))]
423 423 quote_match = re.search('["\']', prefix)
424 424 quote = quote_match.group()
425 425 try:
426 426 prefix_str = eval(prefix + quote, {})
427 427 except Exception:
428 428 return None, 0, []
429 429
430 430 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
431 431 token_match = re.search(pattern, prefix, re.UNICODE)
432 432 token_start = token_match.start()
433 433 token_prefix = token_match.group()
434 434
435 435 # TODO: support bytes in Py3k
436 436 matched = []
437 437 for key in keys:
438 438 try:
439 439 if not key.startswith(prefix_str):
440 440 continue
441 441 except (AttributeError, TypeError, UnicodeError):
442 442 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
443 443 continue
444 444
445 445 # reformat remainder of key to begin with prefix
446 446 rem = key[len(prefix_str):]
447 447 # force repr wrapped in '
448 448 rem_repr = repr(rem + '"')
449 449 if rem_repr.startswith('u') and prefix[0] not in 'uU':
450 450 # Found key is unicode, but prefix is Py2 string.
451 451 # Therefore attempt to interpret key as string.
452 452 try:
453 453 rem_repr = repr(rem.encode('ascii') + '"')
454 454 except UnicodeEncodeError:
455 455 continue
456 456
457 457 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
458 458 if quote == '"':
459 459 # The entered prefix is quoted with ",
460 460 # but the match is quoted with '.
461 461 # A contained " hence needs escaping for comparison:
462 462 rem_repr = rem_repr.replace('"', '\\"')
463 463
464 464 # then reinsert prefix from start of token
465 465 matched.append('%s%s' % (token_prefix, rem_repr))
466 466 return quote, token_start, matched
467 467
468 468
469 469 def _safe_isinstance(obj, module, class_name):
470 470 """Checks if obj is an instance of module.class_name if loaded
471 471 """
472 472 return (module in sys.modules and
473 473 isinstance(obj, getattr(__import__(module), class_name)))
474 474
475 def _safe_really_hasattr(obj, name):
476 """Checks that an object genuinely has a given attribute.
477
478 Some objects claim to have any attribute that's requested, to act as a lazy
479 proxy for something else. We want to catch these cases and ignore their
480 claim to have the attribute we're interested in.
481 """
482 if safe_hasattr(obj, '_ipy_proxy_check_dont_define_this_'):
483 # If it claims this exists, don't trust it
484 return False
485
486 return safe_hasattr(obj, name)
487
488 475
489 476 def back_unicode_name_matches(text):
490 477 u"""Match unicode characters back to unicode name
491 478
492 479 This does β˜ƒ -> \\snowman
493 480
494 481 Note that snowman is not a valid python3 combining character but will be expanded.
495 482 Though it will not recombine back to the snowman character by the completion machinery.
496 483
497 484 This will not either back-complete standard sequences like \\n, \\b ...
498 485
499 486 Used on Python 3 only.
500 487 """
501 488 if len(text)<2:
502 489 return u'', ()
503 490 maybe_slash = text[-2]
504 491 if maybe_slash != '\\':
505 492 return u'', ()
506 493
507 494 char = text[-1]
508 495 # no expand on quote for completion in strings.
509 496 # nor backcomplete standard ascii keys
510 497 if char in string.ascii_letters or char in ['"',"'"]:
511 498 return u'', ()
512 499 try :
513 500 unic = unicodedata.name(char)
514 501 return '\\'+char,['\\'+unic]
515 502 except KeyError as e:
516 503 pass
517 504 return u'', ()
518 505
519 506 def back_latex_name_matches(text):
520 507 u"""Match latex characters back to unicode name
521 508
522 509 This does ->\\sqrt
523 510
524 511 Used on Python 3 only.
525 512 """
526 513 if len(text)<2:
527 514 return u'', ()
528 515 maybe_slash = text[-2]
529 516 if maybe_slash != '\\':
530 517 return u'', ()
531 518
532 519
533 520 char = text[-1]
534 521 # no expand on quote for completion in strings.
535 522 # nor backcomplete standard ascii keys
536 523 if char in string.ascii_letters or char in ['"',"'"]:
537 524 return u'', ()
538 525 try :
539 526 latex = reverse_latex_symbol[char]
540 527 # '\\' replace the \ as well
541 528 return '\\'+char,[latex]
542 529 except KeyError as e:
543 530 pass
544 531 return u'', ()
545 532
546 533
547 534 class IPCompleter(Completer):
548 535 """Extension of the completer class with IPython-specific features"""
549 536
550 537 def _greedy_changed(self, name, old, new):
551 538 """update the splitter and readline delims when greedy is changed"""
552 539 if new:
553 540 self.splitter.delims = GREEDY_DELIMS
554 541 else:
555 542 self.splitter.delims = DELIMS
556 543
557 544 if self.readline:
558 545 self.readline.set_completer_delims(self.splitter.delims)
559 546
560 547 merge_completions = CBool(True, config=True,
561 548 help="""Whether to merge completion results into a single list
562 549
563 550 If False, only the completion results from the first non-empty
564 551 completer will be returned.
565 552 """
566 553 )
567 554 omit__names = Enum((0,1,2), default_value=2, config=True,
568 555 help="""Instruct the completer to omit private method names
569 556
570 557 Specifically, when completing on ``object.<tab>``.
571 558
572 559 When 2 [default]: all names that start with '_' will be excluded.
573 560
574 561 When 1: all 'magic' names (``__foo__``) will be excluded.
575 562
576 563 When 0: nothing will be excluded.
577 564 """
578 565 )
579 566 limit_to__all__ = CBool(default_value=False, config=True,
580 567 help="""Instruct the completer to use __all__ for the completion
581 568
582 569 Specifically, when completing on ``object.<tab>``.
583 570
584 571 When True: only those names in obj.__all__ will be included.
585 572
586 573 When False [default]: the __all__ attribute is ignored
587 574 """
588 575 )
589 576
590 577 def __init__(self, shell=None, namespace=None, global_namespace=None,
591 578 use_readline=True, config=None, **kwargs):
592 579 """IPCompleter() -> completer
593 580
594 581 Return a completer object suitable for use by the readline library
595 582 via readline.set_completer().
596 583
597 584 Inputs:
598 585
599 586 - shell: a pointer to the ipython shell itself. This is needed
600 587 because this completer knows about magic functions, and those can
601 588 only be accessed via the ipython instance.
602 589
603 590 - namespace: an optional dict where completions are performed.
604 591
605 592 - global_namespace: secondary optional dict for completions, to
606 593 handle cases (such as IPython embedded inside functions) where
607 594 both Python scopes are visible.
608 595
609 596 use_readline : bool, optional
610 597 If true, use the readline library. This completer can still function
611 598 without readline, though in that case callers must provide some extra
612 599 information on each call about the current line."""
613 600
614 601 self.magic_escape = ESC_MAGIC
615 602 self.splitter = CompletionSplitter()
616 603
617 604 # Readline configuration, only used by the rlcompleter method.
618 605 if use_readline:
619 606 # We store the right version of readline so that later code
620 607 import IPython.utils.rlineimpl as readline
621 608 self.readline = readline
622 609 else:
623 610 self.readline = None
624 611
625 612 # _greedy_changed() depends on splitter and readline being defined:
626 613 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
627 614 config=config, **kwargs)
628 615
629 616 # List where completion matches will be stored
630 617 self.matches = []
631 618 self.shell = shell
632 619 # Regexp to split filenames with spaces in them
633 620 self.space_name_re = re.compile(r'([^\\] )')
634 621 # Hold a local ref. to glob.glob for speed
635 622 self.glob = glob.glob
636 623
637 624 # Determine if we are running on 'dumb' terminals, like (X)Emacs
638 625 # buffers, to avoid completion problems.
639 626 term = os.environ.get('TERM','xterm')
640 627 self.dumb_terminal = term in ['dumb','emacs']
641 628
642 629 # Special handling of backslashes needed in win32 platforms
643 630 if sys.platform == "win32":
644 631 self.clean_glob = self._clean_glob_win32
645 632 else:
646 633 self.clean_glob = self._clean_glob
647 634
648 635 #regexp to parse docstring for function signature
649 636 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
650 637 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
651 638 #use this if positional argument name is also needed
652 639 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
653 640
654 641 # All active matcher routines for completion
655 642 self.matchers = [self.python_matches,
656 643 self.file_matches,
657 644 self.magic_matches,
658 645 self.python_func_kw_matches,
659 646 self.dict_key_matches,
660 647 ]
661 648
662 649 def all_completions(self, text):
663 650 """
664 651 Wrapper around the complete method for the benefit of emacs
665 652 and pydb.
666 653 """
667 654 return self.complete(text)[1]
668 655
669 656 def _clean_glob(self,text):
670 657 return self.glob("%s*" % text)
671 658
672 659 def _clean_glob_win32(self,text):
673 660 return [f.replace("\\","/")
674 661 for f in self.glob("%s*" % text)]
675 662
676 663 def file_matches(self, text):
677 664 """Match filenames, expanding ~USER type strings.
678 665
679 666 Most of the seemingly convoluted logic in this completer is an
680 667 attempt to handle filenames with spaces in them. And yet it's not
681 668 quite perfect, because Python's readline doesn't expose all of the
682 669 GNU readline details needed for this to be done correctly.
683 670
684 671 For a filename with a space in it, the printed completions will be
685 672 only the parts after what's already been typed (instead of the
686 673 full completions, as is normally done). I don't think with the
687 674 current (as of Python 2.3) Python readline it's possible to do
688 675 better."""
689 676
690 677 #io.rprint('Completer->file_matches: <%r>' % text) # dbg
691 678
692 679 # chars that require escaping with backslash - i.e. chars
693 680 # that readline treats incorrectly as delimiters, but we
694 681 # don't want to treat as delimiters in filename matching
695 682 # when escaped with backslash
696 683 if text.startswith('!'):
697 684 text = text[1:]
698 685 text_prefix = '!'
699 686 else:
700 687 text_prefix = ''
701 688
702 689 text_until_cursor = self.text_until_cursor
703 690 # track strings with open quotes
704 691 open_quotes = has_open_quotes(text_until_cursor)
705 692
706 693 if '(' in text_until_cursor or '[' in text_until_cursor:
707 694 lsplit = text
708 695 else:
709 696 try:
710 697 # arg_split ~ shlex.split, but with unicode bugs fixed by us
711 698 lsplit = arg_split(text_until_cursor)[-1]
712 699 except ValueError:
713 700 # typically an unmatched ", or backslash without escaped char.
714 701 if open_quotes:
715 702 lsplit = text_until_cursor.split(open_quotes)[-1]
716 703 else:
717 704 return []
718 705 except IndexError:
719 706 # tab pressed on empty line
720 707 lsplit = ""
721 708
722 709 if not open_quotes and lsplit != protect_filename(lsplit):
723 710 # if protectables are found, do matching on the whole escaped name
724 711 has_protectables = True
725 712 text0,text = text,lsplit
726 713 else:
727 714 has_protectables = False
728 715 text = os.path.expanduser(text)
729 716
730 717 if text == "":
731 718 return [text_prefix + protect_filename(f) for f in self.glob("*")]
732 719
733 720 # Compute the matches from the filesystem
734 721 m0 = self.clean_glob(text.replace('\\',''))
735 722
736 723 if has_protectables:
737 724 # If we had protectables, we need to revert our changes to the
738 725 # beginning of filename so that we don't double-write the part
739 726 # of the filename we have so far
740 727 len_lsplit = len(lsplit)
741 728 matches = [text_prefix + text0 +
742 729 protect_filename(f[len_lsplit:]) for f in m0]
743 730 else:
744 731 if open_quotes:
745 732 # if we have a string with an open quote, we don't need to
746 733 # protect the names at all (and we _shouldn't_, as it
747 734 # would cause bugs when the filesystem call is made).
748 735 matches = m0
749 736 else:
750 737 matches = [text_prefix +
751 738 protect_filename(f) for f in m0]
752 739
753 740 #io.rprint('mm', matches) # dbg
754 741
755 742 # Mark directories in input list by appending '/' to their names.
756 743 matches = [x+'/' if os.path.isdir(x) else x for x in matches]
757 744 return matches
758 745
759 746 def magic_matches(self, text):
760 747 """Match magics"""
761 748 #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
762 749 # Get all shell magics now rather than statically, so magics loaded at
763 750 # runtime show up too.
764 751 lsm = self.shell.magics_manager.lsmagic()
765 752 line_magics = lsm['line']
766 753 cell_magics = lsm['cell']
767 754 pre = self.magic_escape
768 755 pre2 = pre+pre
769 756
770 757 # Completion logic:
771 758 # - user gives %%: only do cell magics
772 759 # - user gives %: do both line and cell magics
773 760 # - no prefix: do both
774 761 # In other words, line magics are skipped if the user gives %% explicitly
775 762 bare_text = text.lstrip(pre)
776 763 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
777 764 if not text.startswith(pre2):
778 765 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
779 766 return comp
780 767
781 768 def python_matches(self,text):
782 769 """Match attributes or global python names"""
783 770
784 771 #io.rprint('Completer->python_matches, txt=%r' % text) # dbg
785 772 if "." in text:
786 773 try:
787 774 matches = self.attr_matches(text)
788 775 if text.endswith('.') and self.omit__names:
789 776 if self.omit__names == 1:
790 777 # true if txt is _not_ a __ name, false otherwise:
791 778 no__name = (lambda txt:
792 779 re.match(r'.*\.__.*?__',txt) is None)
793 780 else:
794 781 # true if txt is _not_ a _ name, false otherwise:
795 782 no__name = (lambda txt:
796 783 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
797 784 matches = filter(no__name, matches)
798 785 except NameError:
799 786 # catches <undefined attributes>.<tab>
800 787 matches = []
801 788 else:
802 789 matches = self.global_matches(text)
803 790
804 791 return matches
805 792
806 793 def _default_arguments_from_docstring(self, doc):
807 794 """Parse the first line of docstring for call signature.
808 795
809 796 Docstring should be of the form 'min(iterable[, key=func])\n'.
810 797 It can also parse cython docstring of the form
811 798 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
812 799 """
813 800 if doc is None:
814 801 return []
815 802
816 803 #care only the firstline
817 804 line = doc.lstrip().splitlines()[0]
818 805
819 806 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
820 807 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
821 808 sig = self.docstring_sig_re.search(line)
822 809 if sig is None:
823 810 return []
824 811 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
825 812 sig = sig.groups()[0].split(',')
826 813 ret = []
827 814 for s in sig:
828 815 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
829 816 ret += self.docstring_kwd_re.findall(s)
830 817 return ret
831 818
832 819 def _default_arguments(self, obj):
833 820 """Return the list of default arguments of obj if it is callable,
834 821 or empty list otherwise."""
835 822 call_obj = obj
836 823 ret = []
837 824 if inspect.isbuiltin(obj):
838 825 pass
839 826 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
840 827 if inspect.isclass(obj):
841 828 #for cython embededsignature=True the constructor docstring
842 829 #belongs to the object itself not __init__
843 830 ret += self._default_arguments_from_docstring(
844 831 getattr(obj, '__doc__', ''))
845 832 # for classes, check for __init__,__new__
846 833 call_obj = (getattr(obj, '__init__', None) or
847 834 getattr(obj, '__new__', None))
848 835 # for all others, check if they are __call__able
849 836 elif hasattr(obj, '__call__'):
850 837 call_obj = obj.__call__
851 838 ret += self._default_arguments_from_docstring(
852 839 getattr(call_obj, '__doc__', ''))
853 840
854 841 if PY3:
855 842 _keeps = (inspect.Parameter.KEYWORD_ONLY,
856 843 inspect.Parameter.POSITIONAL_OR_KEYWORD)
857 844 signature = inspect.signature
858 845 else:
859 846 import IPython.utils.signatures
860 847 _keeps = (IPython.utils.signatures.Parameter.KEYWORD_ONLY,
861 848 IPython.utils.signatures.Parameter.POSITIONAL_OR_KEYWORD)
862 849 signature = IPython.utils.signatures.signature
863 850
864 851 try:
865 852 sig = signature(call_obj)
866 853 ret.extend(k for k, v in sig.parameters.items() if
867 854 v.kind in _keeps)
868 855 except ValueError:
869 856 pass
870 857
871 858 return list(set(ret))
872 859
873 860 def python_func_kw_matches(self,text):
874 861 """Match named parameters (kwargs) of the last open function"""
875 862
876 863 if "." in text: # a parameter cannot be dotted
877 864 return []
878 865 try: regexp = self.__funcParamsRegex
879 866 except AttributeError:
880 867 regexp = self.__funcParamsRegex = re.compile(r'''
881 868 '.*?(?<!\\)' | # single quoted strings or
882 869 ".*?(?<!\\)" | # double quoted strings or
883 870 \w+ | # identifier
884 871 \S # other characters
885 872 ''', re.VERBOSE | re.DOTALL)
886 873 # 1. find the nearest identifier that comes before an unclosed
887 874 # parenthesis before the cursor
888 875 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
889 876 tokens = regexp.findall(self.text_until_cursor)
890 877 tokens.reverse()
891 878 iterTokens = iter(tokens); openPar = 0
892 879
893 880 for token in iterTokens:
894 881 if token == ')':
895 882 openPar -= 1
896 883 elif token == '(':
897 884 openPar += 1
898 885 if openPar > 0:
899 886 # found the last unclosed parenthesis
900 887 break
901 888 else:
902 889 return []
903 890 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
904 891 ids = []
905 892 isId = re.compile(r'\w+$').match
906 893
907 894 while True:
908 895 try:
909 896 ids.append(next(iterTokens))
910 897 if not isId(ids[-1]):
911 898 ids.pop(); break
912 899 if not next(iterTokens) == '.':
913 900 break
914 901 except StopIteration:
915 902 break
916 903 # lookup the candidate callable matches either using global_matches
917 904 # or attr_matches for dotted names
918 905 if len(ids) == 1:
919 906 callableMatches = self.global_matches(ids[0])
920 907 else:
921 908 callableMatches = self.attr_matches('.'.join(ids[::-1]))
922 909 argMatches = []
923 910 for callableMatch in callableMatches:
924 911 try:
925 912 namedArgs = self._default_arguments(eval(callableMatch,
926 913 self.namespace))
927 914 except:
928 915 continue
929 916
930 917 for namedArg in namedArgs:
931 918 if namedArg.startswith(text):
932 919 argMatches.append("%s=" %namedArg)
933 920 return argMatches
934 921
935 922 def dict_key_matches(self, text):
936 923 "Match string keys in a dictionary, after e.g. 'foo[' "
937 924 def get_keys(obj):
938 925 # Objects can define their own completions by defining an
939 926 # _ipy_key_completions_() method.
940 if _safe_really_hasattr(obj, '_ipython_key_completions_'):
941 return obj._ipython_key_completions_()
927 method = get_real_method(obj, '_ipython_key_completions_')
928 if method is not None:
929 return method()
942 930
943 931 # Special case some common in-memory dict-like types
944 932 if isinstance(obj, dict) or\
945 933 _safe_isinstance(obj, 'pandas', 'DataFrame'):
946 934 try:
947 935 return list(obj.keys())
948 936 except Exception:
949 937 return []
950 938 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
951 939 _safe_isinstance(obj, 'numpy', 'void'):
952 940 return obj.dtype.names or []
953 941 return []
954 942
955 943 try:
956 944 regexps = self.__dict_key_regexps
957 945 except AttributeError:
958 946 dict_key_re_fmt = r'''(?x)
959 947 ( # match dict-referring expression wrt greedy setting
960 948 %s
961 949 )
962 950 \[ # open bracket
963 951 \s* # and optional whitespace
964 952 ([uUbB]? # string prefix (r not handled)
965 953 (?: # unclosed string
966 954 '(?:[^']|(?<!\\)\\')*
967 955 |
968 956 "(?:[^"]|(?<!\\)\\")*
969 957 )
970 958 )?
971 959 $
972 960 '''
973 961 regexps = self.__dict_key_regexps = {
974 962 False: re.compile(dict_key_re_fmt % '''
975 963 # identifiers separated by .
976 964 (?!\d)\w+
977 965 (?:\.(?!\d)\w+)*
978 966 '''),
979 967 True: re.compile(dict_key_re_fmt % '''
980 968 .+
981 969 ''')
982 970 }
983 971
984 972 match = regexps[self.greedy].search(self.text_until_cursor)
985 973 if match is None:
986 974 return []
987 975
988 976 expr, prefix = match.groups()
989 977 try:
990 978 obj = eval(expr, self.namespace)
991 979 except Exception:
992 980 try:
993 981 obj = eval(expr, self.global_namespace)
994 982 except Exception:
995 983 return []
996 984
997 985 keys = get_keys(obj)
998 986 if not keys:
999 987 return keys
1000 988 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
1001 989 if not matches:
1002 990 return matches
1003 991
1004 992 # get the cursor position of
1005 993 # - the text being completed
1006 994 # - the start of the key text
1007 995 # - the start of the completion
1008 996 text_start = len(self.text_until_cursor) - len(text)
1009 997 if prefix:
1010 998 key_start = match.start(2)
1011 999 completion_start = key_start + token_offset
1012 1000 else:
1013 1001 key_start = completion_start = match.end()
1014 1002
1015 1003 # grab the leading prefix, to make sure all completions start with `text`
1016 1004 if text_start > key_start:
1017 1005 leading = ''
1018 1006 else:
1019 1007 leading = text[text_start:completion_start]
1020 1008
1021 1009 # the index of the `[` character
1022 1010 bracket_idx = match.end(1)
1023 1011
1024 1012 # append closing quote and bracket as appropriate
1025 1013 # this is *not* appropriate if the opening quote or bracket is outside
1026 1014 # the text given to this method
1027 1015 suf = ''
1028 1016 continuation = self.line_buffer[len(self.text_until_cursor):]
1029 1017 if key_start > text_start and closing_quote:
1030 1018 # quotes were opened inside text, maybe close them
1031 1019 if continuation.startswith(closing_quote):
1032 1020 continuation = continuation[len(closing_quote):]
1033 1021 else:
1034 1022 suf += closing_quote
1035 1023 if bracket_idx > text_start:
1036 1024 # brackets were opened inside text, maybe close them
1037 1025 if not continuation.startswith(']'):
1038 1026 suf += ']'
1039 1027
1040 1028 return [leading + k + suf for k in matches]
1041 1029
1042 1030 def unicode_name_matches(self, text):
1043 1031 u"""Match Latex-like syntax for unicode characters base
1044 1032 on the name of the character.
1045 1033
1046 1034 This does \\GREEK SMALL LETTER ETA -> Ξ·
1047 1035
1048 1036 Works only on valid python 3 identifier, or on combining characters that
1049 1037 will combine to form a valid identifier.
1050 1038
1051 1039 Used on Python 3 only.
1052 1040 """
1053 1041 slashpos = text.rfind('\\')
1054 1042 if slashpos > -1:
1055 1043 s = text[slashpos+1:]
1056 1044 try :
1057 1045 unic = unicodedata.lookup(s)
1058 1046 # allow combining chars
1059 1047 if ('a'+unic).isidentifier():
1060 1048 return '\\'+s,[unic]
1061 1049 except KeyError as e:
1062 1050 pass
1063 1051 return u'', []
1064 1052
1065 1053
1066 1054
1067 1055
1068 1056 def latex_matches(self, text):
1069 1057 u"""Match Latex syntax for unicode characters.
1070 1058
1071 1059 This does both \\alp -> \\alpha and \\alpha -> Ξ±
1072 1060
1073 1061 Used on Python 3 only.
1074 1062 """
1075 1063 slashpos = text.rfind('\\')
1076 1064 if slashpos > -1:
1077 1065 s = text[slashpos:]
1078 1066 if s in latex_symbols:
1079 1067 # Try to complete a full latex symbol to unicode
1080 1068 # \\alpha -> Ξ±
1081 1069 return s, [latex_symbols[s]]
1082 1070 else:
1083 1071 # If a user has partially typed a latex symbol, give them
1084 1072 # a full list of options \al -> [\aleph, \alpha]
1085 1073 matches = [k for k in latex_symbols if k.startswith(s)]
1086 1074 return s, matches
1087 1075 return u'', []
1088 1076
1089 1077 def dispatch_custom_completer(self, text):
1090 1078 #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg
1091 1079 line = self.line_buffer
1092 1080 if not line.strip():
1093 1081 return None
1094 1082
1095 1083 # Create a little structure to pass all the relevant information about
1096 1084 # the current completion to any custom completer.
1097 1085 event = Bunch()
1098 1086 event.line = line
1099 1087 event.symbol = text
1100 1088 cmd = line.split(None,1)[0]
1101 1089 event.command = cmd
1102 1090 event.text_until_cursor = self.text_until_cursor
1103 1091
1104 1092 #print "\ncustom:{%s]\n" % event # dbg
1105 1093
1106 1094 # for foo etc, try also to find completer for %foo
1107 1095 if not cmd.startswith(self.magic_escape):
1108 1096 try_magic = self.custom_completers.s_matches(
1109 1097 self.magic_escape + cmd)
1110 1098 else:
1111 1099 try_magic = []
1112 1100
1113 1101 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1114 1102 try_magic,
1115 1103 self.custom_completers.flat_matches(self.text_until_cursor)):
1116 1104 #print "try",c # dbg
1117 1105 try:
1118 1106 res = c(event)
1119 1107 if res:
1120 1108 # first, try case sensitive match
1121 1109 withcase = [r for r in res if r.startswith(text)]
1122 1110 if withcase:
1123 1111 return withcase
1124 1112 # if none, then case insensitive ones are ok too
1125 1113 text_low = text.lower()
1126 1114 return [r for r in res if r.lower().startswith(text_low)]
1127 1115 except TryNext:
1128 1116 pass
1129 1117
1130 1118 return None
1131 1119
1132 1120 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1133 1121 """Find completions for the given text and line context.
1134 1122
1135 1123 Note that both the text and the line_buffer are optional, but at least
1136 1124 one of them must be given.
1137 1125
1138 1126 Parameters
1139 1127 ----------
1140 1128 text : string, optional
1141 1129 Text to perform the completion on. If not given, the line buffer
1142 1130 is split using the instance's CompletionSplitter object.
1143 1131
1144 1132 line_buffer : string, optional
1145 1133 If not given, the completer attempts to obtain the current line
1146 1134 buffer via readline. This keyword allows clients which are
1147 1135 requesting for text completions in non-readline contexts to inform
1148 1136 the completer of the entire text.
1149 1137
1150 1138 cursor_pos : int, optional
1151 1139 Index of the cursor in the full line buffer. Should be provided by
1152 1140 remote frontends where kernel has no access to frontend state.
1153 1141
1154 1142 Returns
1155 1143 -------
1156 1144 text : str
1157 1145 Text that was actually used in the completion.
1158 1146
1159 1147 matches : list
1160 1148 A list of completion matches.
1161 1149 """
1162 1150 # io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
1163 1151
1164 1152 # if the cursor position isn't given, the only sane assumption we can
1165 1153 # make is that it's at the end of the line (the common case)
1166 1154 if cursor_pos is None:
1167 1155 cursor_pos = len(line_buffer) if text is None else len(text)
1168 1156
1169 1157 if PY3:
1170 1158
1171 1159 base_text = text if not line_buffer else line_buffer[:cursor_pos]
1172 1160 latex_text, latex_matches = self.latex_matches(base_text)
1173 1161 if latex_matches:
1174 1162 return latex_text, latex_matches
1175 1163 name_text = ''
1176 1164 name_matches = []
1177 1165 for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches):
1178 1166 name_text, name_matches = meth(base_text)
1179 1167 if name_text:
1180 1168 return name_text, name_matches
1181 1169
1182 1170 # if text is either None or an empty string, rely on the line buffer
1183 1171 if not text:
1184 1172 text = self.splitter.split_line(line_buffer, cursor_pos)
1185 1173
1186 1174 # If no line buffer is given, assume the input text is all there was
1187 1175 if line_buffer is None:
1188 1176 line_buffer = text
1189 1177
1190 1178 self.line_buffer = line_buffer
1191 1179 self.text_until_cursor = self.line_buffer[:cursor_pos]
1192 1180 # io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
1193 1181
1194 1182 # Start with a clean slate of completions
1195 1183 self.matches[:] = []
1196 1184 custom_res = self.dispatch_custom_completer(text)
1197 1185 if custom_res is not None:
1198 1186 # did custom completers produce something?
1199 1187 self.matches = custom_res
1200 1188 else:
1201 1189 # Extend the list of completions with the results of each
1202 1190 # matcher, so we return results to the user from all
1203 1191 # namespaces.
1204 1192 if self.merge_completions:
1205 1193 self.matches = []
1206 1194 for matcher in self.matchers:
1207 1195 try:
1208 1196 self.matches.extend(matcher(text))
1209 1197 except:
1210 1198 # Show the ugly traceback if the matcher causes an
1211 1199 # exception, but do NOT crash the kernel!
1212 1200 sys.excepthook(*sys.exc_info())
1213 1201 else:
1214 1202 for matcher in self.matchers:
1215 1203 self.matches = matcher(text)
1216 1204 if self.matches:
1217 1205 break
1218 1206 # FIXME: we should extend our api to return a dict with completions for
1219 1207 # different types of objects. The rlcomplete() method could then
1220 1208 # simply collapse the dict into a list for readline, but we'd have
1221 1209 # richer completion semantics in other evironments.
1222 1210
1223 1211 self.matches = sorted(set(self.matches), key=completions_sorting_key)
1224 1212
1225 1213 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
1226 1214 return text, self.matches
1227 1215
1228 1216 def rlcomplete(self, text, state):
1229 1217 """Return the state-th possible completion for 'text'.
1230 1218
1231 1219 This is called successively with state == 0, 1, 2, ... until it
1232 1220 returns None. The completion should begin with 'text'.
1233 1221
1234 1222 Parameters
1235 1223 ----------
1236 1224 text : string
1237 1225 Text to perform the completion on.
1238 1226
1239 1227 state : int
1240 1228 Counter used by readline.
1241 1229 """
1242 1230 if state==0:
1243 1231
1244 1232 self.line_buffer = line_buffer = self.readline.get_line_buffer()
1245 1233 cursor_pos = self.readline.get_endidx()
1246 1234
1247 1235 #io.rprint("\nRLCOMPLETE: %r %r %r" %
1248 1236 # (text, line_buffer, cursor_pos) ) # dbg
1249 1237
1250 1238 # if there is only a tab on a line with only whitespace, instead of
1251 1239 # the mostly useless 'do you want to see all million completions'
1252 1240 # message, just do the right thing and give the user his tab!
1253 1241 # Incidentally, this enables pasting of tabbed text from an editor
1254 1242 # (as long as autoindent is off).
1255 1243
1256 1244 # It should be noted that at least pyreadline still shows file
1257 1245 # completions - is there a way around it?
1258 1246
1259 1247 # don't apply this on 'dumb' terminals, such as emacs buffers, so
1260 1248 # we don't interfere with their own tab-completion mechanism.
1261 1249 if not (self.dumb_terminal or line_buffer.strip()):
1262 1250 self.readline.insert_text('\t')
1263 1251 sys.stdout.flush()
1264 1252 return None
1265 1253
1266 1254 # Note: debugging exceptions that may occur in completion is very
1267 1255 # tricky, because readline unconditionally silences them. So if
1268 1256 # during development you suspect a bug in the completion code, turn
1269 1257 # this flag on temporarily by uncommenting the second form (don't
1270 1258 # flip the value in the first line, as the '# dbg' marker can be
1271 1259 # automatically detected and is used elsewhere).
1272 1260 DEBUG = False
1273 1261 #DEBUG = True # dbg
1274 1262 if DEBUG:
1275 1263 try:
1276 1264 self.complete(text, line_buffer, cursor_pos)
1277 1265 except:
1278 1266 import traceback; traceback.print_exc()
1279 1267 else:
1280 1268 # The normal production version is here
1281 1269
1282 1270 # This method computes the self.matches array
1283 1271 self.complete(text, line_buffer, cursor_pos)
1284 1272
1285 1273 try:
1286 1274 return self.matches[state]
1287 1275 except IndexError:
1288 1276 return None
1289 1277
@@ -1,295 +1,294 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Displayhook for IPython.
3 3
4 4 This defines a callable class that IPython uses for `sys.displayhook`.
5 5 """
6 6
7 7 # Copyright (c) IPython Development Team.
8 8 # Distributed under the terms of the Modified BSD License.
9 9
10 10 from __future__ import print_function
11 11
12 12 import sys
13 13 import io as _io
14 14 import tokenize
15 15
16 from IPython.core.formatters import _safe_get_formatter_method
17 16 from traitlets.config.configurable import Configurable
18 17 from IPython.utils import io
19 18 from IPython.utils.py3compat import builtin_mod, cast_unicode_py2
20 19 from traitlets import Instance, Float
21 20 from warnings import warn
22 21
23 22 # TODO: Move the various attributes (cache_size, [others now moved]). Some
24 23 # of these are also attributes of InteractiveShell. They should be on ONE object
25 24 # only and the other objects should ask that one object for their values.
26 25
27 26 class DisplayHook(Configurable):
28 27 """The custom IPython displayhook to replace sys.displayhook.
29 28
30 29 This class does many things, but the basic idea is that it is a callable
31 30 that gets called anytime user code returns a value.
32 31 """
33 32
34 33 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
35 34 allow_none=True)
36 35 exec_result = Instance('IPython.core.interactiveshell.ExecutionResult',
37 36 allow_none=True)
38 37 cull_fraction = Float(0.2)
39 38
40 39 def __init__(self, shell=None, cache_size=1000, **kwargs):
41 40 super(DisplayHook, self).__init__(shell=shell, **kwargs)
42 41 cache_size_min = 3
43 42 if cache_size <= 0:
44 43 self.do_full_cache = 0
45 44 cache_size = 0
46 45 elif cache_size < cache_size_min:
47 46 self.do_full_cache = 0
48 47 cache_size = 0
49 48 warn('caching was disabled (min value for cache size is %s).' %
50 49 cache_size_min,level=3)
51 50 else:
52 51 self.do_full_cache = 1
53 52
54 53 self.cache_size = cache_size
55 54
56 55 # we need a reference to the user-level namespace
57 56 self.shell = shell
58 57
59 58 self._,self.__,self.___ = '','',''
60 59
61 60 # these are deliberately global:
62 61 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
63 62 self.shell.user_ns.update(to_user_ns)
64 63
65 64 @property
66 65 def prompt_count(self):
67 66 return self.shell.execution_count
68 67
69 68 #-------------------------------------------------------------------------
70 69 # Methods used in __call__. Override these methods to modify the behavior
71 70 # of the displayhook.
72 71 #-------------------------------------------------------------------------
73 72
74 73 def check_for_underscore(self):
75 74 """Check if the user has set the '_' variable by hand."""
76 75 # If something injected a '_' variable in __builtin__, delete
77 76 # ipython's automatic one so we don't clobber that. gettext() in
78 77 # particular uses _, so we need to stay away from it.
79 78 if '_' in builtin_mod.__dict__:
80 79 try:
81 80 del self.shell.user_ns['_']
82 81 except KeyError:
83 82 pass
84 83
85 84 def quiet(self):
86 85 """Should we silence the display hook because of ';'?"""
87 86 # do not print output if input ends in ';'
88 87
89 88 try:
90 89 cell = cast_unicode_py2(self.shell.history_manager.input_hist_parsed[-1])
91 90 except IndexError:
92 91 # some uses of ipshellembed may fail here
93 92 return False
94 93
95 94 sio = _io.StringIO(cell)
96 95 tokens = list(tokenize.generate_tokens(sio.readline))
97 96
98 97 for token in reversed(tokens):
99 98 if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT):
100 99 continue
101 100 if (token[0] == tokenize.OP) and (token[1] == ';'):
102 101 return True
103 102 else:
104 103 return False
105 104
106 105 def start_displayhook(self):
107 106 """Start the displayhook, initializing resources."""
108 107 pass
109 108
110 109 def write_output_prompt(self):
111 110 """Write the output prompt.
112 111
113 112 The default implementation simply writes the prompt to
114 113 ``io.stdout``.
115 114 """
116 115 # Use write, not print which adds an extra space.
117 116 io.stdout.write(self.shell.separate_out)
118 117 outprompt = self.shell.prompt_manager.render('out')
119 118 if self.do_full_cache:
120 119 io.stdout.write(outprompt)
121 120
122 121 def compute_format_data(self, result):
123 122 """Compute format data of the object to be displayed.
124 123
125 124 The format data is a generalization of the :func:`repr` of an object.
126 125 In the default implementation the format data is a :class:`dict` of
127 126 key value pair where the keys are valid MIME types and the values
128 127 are JSON'able data structure containing the raw data for that MIME
129 128 type. It is up to frontends to determine pick a MIME to to use and
130 129 display that data in an appropriate manner.
131 130
132 131 This method only computes the format data for the object and should
133 132 NOT actually print or write that to a stream.
134 133
135 134 Parameters
136 135 ----------
137 136 result : object
138 137 The Python object passed to the display hook, whose format will be
139 138 computed.
140 139
141 140 Returns
142 141 -------
143 142 (format_dict, md_dict) : dict
144 143 format_dict is a :class:`dict` whose keys are valid MIME types and values are
145 144 JSON'able raw data for that MIME type. It is recommended that
146 145 all return values of this should always include the "text/plain"
147 146 MIME type representation of the object.
148 147 md_dict is a :class:`dict` with the same MIME type keys
149 148 of metadata associated with each output.
150 149
151 150 """
152 151 return self.shell.display_formatter.format(result)
153 152
154 153 def write_format_data(self, format_dict, md_dict=None):
155 154 """Write the format data dict to the frontend.
156 155
157 156 This default version of this method simply writes the plain text
158 157 representation of the object to ``io.stdout``. Subclasses should
159 158 override this method to send the entire `format_dict` to the
160 159 frontends.
161 160
162 161 Parameters
163 162 ----------
164 163 format_dict : dict
165 164 The format dict for the object passed to `sys.displayhook`.
166 165 md_dict : dict (optional)
167 166 The metadata dict to be associated with the display data.
168 167 """
169 168 if 'text/plain' not in format_dict:
170 169 # nothing to do
171 170 return
172 171 # We want to print because we want to always make sure we have a
173 172 # newline, even if all the prompt separators are ''. This is the
174 173 # standard IPython behavior.
175 174 result_repr = format_dict['text/plain']
176 175 if '\n' in result_repr:
177 176 # So that multi-line strings line up with the left column of
178 177 # the screen, instead of having the output prompt mess up
179 178 # their first line.
180 179 # We use the prompt template instead of the expanded prompt
181 180 # because the expansion may add ANSI escapes that will interfere
182 181 # with our ability to determine whether or not we should add
183 182 # a newline.
184 183 prompt_template = self.shell.prompt_manager.out_template
185 184 if prompt_template and not prompt_template.endswith('\n'):
186 185 # But avoid extraneous empty lines.
187 186 result_repr = '\n' + result_repr
188 187
189 188 print(result_repr, file=io.stdout)
190 189
191 190 def update_user_ns(self, result):
192 191 """Update user_ns with various things like _, __, _1, etc."""
193 192
194 193 # Avoid recursive reference when displaying _oh/Out
195 194 if result is not self.shell.user_ns['_oh']:
196 195 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
197 196 self.cull_cache()
198 197 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
199 198 # we cause buggy behavior for things like gettext).
200 199
201 200 if '_' not in builtin_mod.__dict__:
202 201 self.___ = self.__
203 202 self.__ = self._
204 203 self._ = result
205 204 self.shell.push({'_':self._,
206 205 '__':self.__,
207 206 '___':self.___}, interactive=False)
208 207
209 208 # hackish access to top-level namespace to create _1,_2... dynamically
210 209 to_main = {}
211 210 if self.do_full_cache:
212 211 new_result = '_'+repr(self.prompt_count)
213 212 to_main[new_result] = result
214 213 self.shell.push(to_main, interactive=False)
215 214 self.shell.user_ns['_oh'][self.prompt_count] = result
216 215
217 216 def fill_exec_result(self, result):
218 217 if self.exec_result is not None:
219 218 self.exec_result.result = result
220 219
221 220 def log_output(self, format_dict):
222 221 """Log the output."""
223 222 if 'text/plain' not in format_dict:
224 223 # nothing to do
225 224 return
226 225 if self.shell.logger.log_output:
227 226 self.shell.logger.log_write(format_dict['text/plain'], 'output')
228 227 self.shell.history_manager.output_hist_reprs[self.prompt_count] = \
229 228 format_dict['text/plain']
230 229
231 230 def finish_displayhook(self):
232 231 """Finish up all displayhook activities."""
233 232 io.stdout.write(self.shell.separate_out2)
234 233 io.stdout.flush()
235 234
236 235 def __call__(self, result=None):
237 236 """Printing with history cache management.
238 237
239 238 This is invoked everytime the interpreter needs to print, and is
240 239 activated by setting the variable sys.displayhook to it.
241 240 """
242 241 self.check_for_underscore()
243 242 if result is not None and not self.quiet():
244 243 self.start_displayhook()
245 244 self.write_output_prompt()
246 245 format_dict, md_dict = self.compute_format_data(result)
247 246 self.update_user_ns(result)
248 247 self.fill_exec_result(result)
249 248 if format_dict:
250 249 self.write_format_data(format_dict, md_dict)
251 250 self.log_output(format_dict)
252 251 self.finish_displayhook()
253 252
254 253 def cull_cache(self):
255 254 """Output cache is full, cull the oldest entries"""
256 255 oh = self.shell.user_ns.get('_oh', {})
257 256 sz = len(oh)
258 257 cull_count = max(int(sz * self.cull_fraction), 2)
259 258 warn('Output cache limit (currently {sz} entries) hit.\n'
260 259 'Flushing oldest {cull_count} entries.'.format(sz=sz, cull_count=cull_count))
261 260
262 261 for i, n in enumerate(sorted(oh)):
263 262 if i >= cull_count:
264 263 break
265 264 self.shell.user_ns.pop('_%i' % n, None)
266 265 oh.pop(n, None)
267 266
268 267
269 268 def flush(self):
270 269 if not self.do_full_cache:
271 270 raise ValueError("You shouldn't have reached the cache flush "
272 271 "if full caching is not enabled!")
273 272 # delete auto-generated vars from global namespace
274 273
275 274 for n in range(1,self.prompt_count + 1):
276 275 key = '_'+repr(n)
277 276 try:
278 277 del self.shell.user_ns[key]
279 278 except: pass
280 279 # In some embedded circumstances, the user_ns doesn't have the
281 280 # '_oh' key set up.
282 281 oh = self.shell.user_ns.get('_oh', None)
283 282 if oh is not None:
284 283 oh.clear()
285 284
286 285 # Release our own references to objects:
287 286 self._, self.__, self.___ = '', '', ''
288 287
289 288 if '_' not in builtin_mod.__dict__:
290 289 self.shell.user_ns.update({'_':None,'__':None, '___':None})
291 290 import gc
292 291 # TODO: Is this really needed?
293 292 # IronPython blocks here forever
294 293 if sys.platform != "cli":
295 294 gc.collect()
@@ -1,974 +1,952 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Display formatters.
3 3
4 4 Inheritance diagram:
5 5
6 6 .. inheritance-diagram:: IPython.core.formatters
7 7 :parts: 3
8 8 """
9 9
10 10 # Copyright (c) IPython Development Team.
11 11 # Distributed under the terms of the Modified BSD License.
12 12
13 13 import abc
14 14 import inspect
15 15 import json
16 16 import sys
17 17 import traceback
18 18 import warnings
19 19
20 20 from decorator import decorator
21 21
22 22 from traitlets.config.configurable import Configurable
23 23 from IPython.core.getipython import get_ipython
24 24 from IPython.utils.sentinel import Sentinel
25 from IPython.utils.dir2 import get_real_method
25 26 from IPython.lib import pretty
26 27 from traitlets import (
27 28 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
28 29 ForwardDeclaredInstance,
29 30 )
30 31 from IPython.utils.py3compat import (
31 32 with_metaclass, string_types, unicode_type,
32 33 )
33 34
34 35
35 #-----------------------------------------------------------------------------
36 # The main DisplayFormatter class
37 #-----------------------------------------------------------------------------
38
39
40 def _safe_get_formatter_method(obj, name):
41 """Safely get a formatter method
42
43 - Classes cannot have formatter methods, only instance
44 - protect against proxy objects that claim to have everything
45 """
46 if inspect.isclass(obj):
47 # repr methods only make sense on instances, not classes
48 return None
49 method = pretty._safe_getattr(obj, name, None)
50 if callable(method):
51 # obj claims to have repr method...
52 if callable(pretty._safe_getattr(obj, '_ipython_canary_method_should_not_exist_', None)):
53 # ...but don't trust proxy objects that claim to have everything
54 return None
55 return method
56
57
58 36 class DisplayFormatter(Configurable):
59 37
60 38 # When set to true only the default plain text formatter will be used.
61 39 plain_text_only = Bool(False, config=True)
62 40 def _plain_text_only_changed(self, name, old, new):
63 41 warnings.warn("""DisplayFormatter.plain_text_only is deprecated.
64 42
65 43 It will be removed in IPython 5.0
66 44
67 45 Use DisplayFormatter.active_types = ['text/plain']
68 46 for the same effect.
69 47 """, DeprecationWarning)
70 48 if new:
71 49 self.active_types = ['text/plain']
72 50 else:
73 51 self.active_types = self.format_types
74 52
75 53 active_types = List(Unicode(), config=True,
76 54 help="""List of currently active mime-types to display.
77 55 You can use this to set a white-list for formats to display.
78 56
79 57 Most users will not need to change this value.
80 58 """)
81 59 def _active_types_default(self):
82 60 return self.format_types
83 61
84 62 def _active_types_changed(self, name, old, new):
85 63 for key, formatter in self.formatters.items():
86 64 if key in new:
87 65 formatter.enabled = True
88 66 else:
89 67 formatter.enabled = False
90 68
91 69 ipython_display_formatter = ForwardDeclaredInstance('FormatterABC')
92 70 def _ipython_display_formatter_default(self):
93 71 return IPythonDisplayFormatter(parent=self)
94 72
95 73 # A dict of formatter whose keys are format types (MIME types) and whose
96 74 # values are subclasses of BaseFormatter.
97 75 formatters = Dict()
98 76 def _formatters_default(self):
99 77 """Activate the default formatters."""
100 78 formatter_classes = [
101 79 PlainTextFormatter,
102 80 HTMLFormatter,
103 81 MarkdownFormatter,
104 82 SVGFormatter,
105 83 PNGFormatter,
106 84 PDFFormatter,
107 85 JPEGFormatter,
108 86 LatexFormatter,
109 87 JSONFormatter,
110 88 JavascriptFormatter
111 89 ]
112 90 d = {}
113 91 for cls in formatter_classes:
114 92 f = cls(parent=self)
115 93 d[f.format_type] = f
116 94 return d
117 95
118 96 def format(self, obj, include=None, exclude=None):
119 97 """Return a format data dict for an object.
120 98
121 99 By default all format types will be computed.
122 100
123 101 The following MIME types are currently implemented:
124 102
125 103 * text/plain
126 104 * text/html
127 105 * text/markdown
128 106 * text/latex
129 107 * application/json
130 108 * application/javascript
131 109 * application/pdf
132 110 * image/png
133 111 * image/jpeg
134 112 * image/svg+xml
135 113
136 114 Parameters
137 115 ----------
138 116 obj : object
139 117 The Python object whose format data will be computed.
140 118 include : list or tuple, optional
141 119 A list of format type strings (MIME types) to include in the
142 120 format data dict. If this is set *only* the format types included
143 121 in this list will be computed.
144 122 exclude : list or tuple, optional
145 123 A list of format type string (MIME types) to exclude in the format
146 124 data dict. If this is set all format types will be computed,
147 125 except for those included in this argument.
148 126
149 127 Returns
150 128 -------
151 129 (format_dict, metadata_dict) : tuple of two dicts
152 130
153 131 format_dict is a dictionary of key/value pairs, one of each format that was
154 132 generated for the object. The keys are the format types, which
155 133 will usually be MIME type strings and the values and JSON'able
156 134 data structure containing the raw data for the representation in
157 135 that format.
158 136
159 137 metadata_dict is a dictionary of metadata about each mime-type output.
160 138 Its keys will be a strict subset of the keys in format_dict.
161 139 """
162 140 format_dict = {}
163 141 md_dict = {}
164 142
165 143 if self.ipython_display_formatter(obj):
166 144 # object handled itself, don't proceed
167 145 return {}, {}
168 146
169 147 for format_type, formatter in self.formatters.items():
170 148 if include and format_type not in include:
171 149 continue
172 150 if exclude and format_type in exclude:
173 151 continue
174 152
175 153 md = None
176 154 try:
177 155 data = formatter(obj)
178 156 except:
179 157 # FIXME: log the exception
180 158 raise
181 159
182 160 # formatters can return raw data or (data, metadata)
183 161 if isinstance(data, tuple) and len(data) == 2:
184 162 data, md = data
185 163
186 164 if data is not None:
187 165 format_dict[format_type] = data
188 166 if md is not None:
189 167 md_dict[format_type] = md
190 168
191 169 return format_dict, md_dict
192 170
193 171 @property
194 172 def format_types(self):
195 173 """Return the format types (MIME types) of the active formatters."""
196 174 return list(self.formatters.keys())
197 175
198 176
199 177 #-----------------------------------------------------------------------------
200 178 # Formatters for specific format types (text, html, svg, etc.)
201 179 #-----------------------------------------------------------------------------
202 180
203 181
204 182 def _safe_repr(obj):
205 183 """Try to return a repr of an object
206 184
207 185 always returns a string, at least.
208 186 """
209 187 try:
210 188 return repr(obj)
211 189 except Exception as e:
212 190 return "un-repr-able object (%r)" % e
213 191
214 192
215 193 class FormatterWarning(UserWarning):
216 194 """Warning class for errors in formatters"""
217 195
218 196 @decorator
219 197 def catch_format_error(method, self, *args, **kwargs):
220 198 """show traceback on failed format call"""
221 199 try:
222 200 r = method(self, *args, **kwargs)
223 201 except NotImplementedError:
224 202 # don't warn on NotImplementedErrors
225 203 return None
226 204 except Exception:
227 205 exc_info = sys.exc_info()
228 206 ip = get_ipython()
229 207 if ip is not None:
230 208 ip.showtraceback(exc_info)
231 209 else:
232 210 traceback.print_exception(*exc_info)
233 211 return None
234 212 return self._check_return(r, args[0])
235 213
236 214
237 215 class FormatterABC(with_metaclass(abc.ABCMeta, object)):
238 216 """ Abstract base class for Formatters.
239 217
240 218 A formatter is a callable class that is responsible for computing the
241 219 raw format data for a particular format type (MIME type). For example,
242 220 an HTML formatter would have a format type of `text/html` and would return
243 221 the HTML representation of the object when called.
244 222 """
245 223
246 224 # The format type of the data returned, usually a MIME type.
247 225 format_type = 'text/plain'
248 226
249 227 # Is the formatter enabled...
250 228 enabled = True
251 229
252 230 @abc.abstractmethod
253 231 def __call__(self, obj):
254 232 """Return a JSON'able representation of the object.
255 233
256 234 If the object cannot be formatted by this formatter,
257 235 warn and return None.
258 236 """
259 237 return repr(obj)
260 238
261 239
262 240 def _mod_name_key(typ):
263 241 """Return a (__module__, __name__) tuple for a type.
264 242
265 243 Used as key in Formatter.deferred_printers.
266 244 """
267 245 module = getattr(typ, '__module__', None)
268 246 name = getattr(typ, '__name__', None)
269 247 return (module, name)
270 248
271 249
272 250 def _get_type(obj):
273 251 """Return the type of an instance (old and new-style)"""
274 252 return getattr(obj, '__class__', None) or type(obj)
275 253
276 254
277 255 _raise_key_error = Sentinel('_raise_key_error', __name__,
278 256 """
279 257 Special value to raise a KeyError
280 258
281 259 Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop`
282 260 """)
283 261
284 262
285 263 class BaseFormatter(Configurable):
286 264 """A base formatter class that is configurable.
287 265
288 266 This formatter should usually be used as the base class of all formatters.
289 267 It is a traited :class:`Configurable` class and includes an extensible
290 268 API for users to determine how their objects are formatted. The following
291 269 logic is used to find a function to format an given object.
292 270
293 271 1. The object is introspected to see if it has a method with the name
294 272 :attr:`print_method`. If is does, that object is passed to that method
295 273 for formatting.
296 274 2. If no print method is found, three internal dictionaries are consulted
297 275 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
298 276 and :attr:`deferred_printers`.
299 277
300 278 Users should use these dictionaries to register functions that will be
301 279 used to compute the format data for their objects (if those objects don't
302 280 have the special print methods). The easiest way of using these
303 281 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
304 282 methods.
305 283
306 284 If no function/callable is found to compute the format data, ``None`` is
307 285 returned and this format type is not used.
308 286 """
309 287
310 288 format_type = Unicode('text/plain')
311 289 _return_type = string_types
312 290
313 291 enabled = Bool(True, config=True)
314 292
315 293 print_method = ObjectName('__repr__')
316 294
317 295 # The singleton printers.
318 296 # Maps the IDs of the builtin singleton objects to the format functions.
319 297 singleton_printers = Dict(config=True)
320 298
321 299 # The type-specific printers.
322 300 # Map type objects to the format functions.
323 301 type_printers = Dict(config=True)
324 302
325 303 # The deferred-import type-specific printers.
326 304 # Map (modulename, classname) pairs to the format functions.
327 305 deferred_printers = Dict(config=True)
328 306
329 307 @catch_format_error
330 308 def __call__(self, obj):
331 309 """Compute the format for an object."""
332 310 if self.enabled:
333 311 # lookup registered printer
334 312 try:
335 313 printer = self.lookup(obj)
336 314 except KeyError:
337 315 pass
338 316 else:
339 317 return printer(obj)
340 318 # Finally look for special method names
341 method = _safe_get_formatter_method(obj, self.print_method)
319 method = get_real_method(obj, self.print_method)
342 320 if method is not None:
343 321 return method()
344 322 return None
345 323 else:
346 324 return None
347 325
348 326 def __contains__(self, typ):
349 327 """map in to lookup_by_type"""
350 328 try:
351 329 self.lookup_by_type(typ)
352 330 except KeyError:
353 331 return False
354 332 else:
355 333 return True
356 334
357 335 def _check_return(self, r, obj):
358 336 """Check that a return value is appropriate
359 337
360 338 Return the value if so, None otherwise, warning if invalid.
361 339 """
362 340 if r is None or isinstance(r, self._return_type) or \
363 341 (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)):
364 342 return r
365 343 else:
366 344 warnings.warn(
367 345 "%s formatter returned invalid type %s (expected %s) for object: %s" % \
368 346 (self.format_type, type(r), self._return_type, _safe_repr(obj)),
369 347 FormatterWarning
370 348 )
371 349
372 350 def lookup(self, obj):
373 351 """Look up the formatter for a given instance.
374 352
375 353 Parameters
376 354 ----------
377 355 obj : object instance
378 356
379 357 Returns
380 358 -------
381 359 f : callable
382 360 The registered formatting callable for the type.
383 361
384 362 Raises
385 363 ------
386 364 KeyError if the type has not been registered.
387 365 """
388 366 # look for singleton first
389 367 obj_id = id(obj)
390 368 if obj_id in self.singleton_printers:
391 369 return self.singleton_printers[obj_id]
392 370 # then lookup by type
393 371 return self.lookup_by_type(_get_type(obj))
394 372
395 373 def lookup_by_type(self, typ):
396 374 """Look up the registered formatter for a type.
397 375
398 376 Parameters
399 377 ----------
400 378 typ : type or '__module__.__name__' string for a type
401 379
402 380 Returns
403 381 -------
404 382 f : callable
405 383 The registered formatting callable for the type.
406 384
407 385 Raises
408 386 ------
409 387 KeyError if the type has not been registered.
410 388 """
411 389 if isinstance(typ, string_types):
412 390 typ_key = tuple(typ.rsplit('.',1))
413 391 if typ_key not in self.deferred_printers:
414 392 # We may have it cached in the type map. We will have to
415 393 # iterate over all of the types to check.
416 394 for cls in self.type_printers:
417 395 if _mod_name_key(cls) == typ_key:
418 396 return self.type_printers[cls]
419 397 else:
420 398 return self.deferred_printers[typ_key]
421 399 else:
422 400 for cls in pretty._get_mro(typ):
423 401 if cls in self.type_printers or self._in_deferred_types(cls):
424 402 return self.type_printers[cls]
425 403
426 404 # If we have reached here, the lookup failed.
427 405 raise KeyError("No registered printer for {0!r}".format(typ))
428 406
429 407 def for_type(self, typ, func=None):
430 408 """Add a format function for a given type.
431 409
432 410 Parameters
433 411 -----------
434 412 typ : type or '__module__.__name__' string for a type
435 413 The class of the object that will be formatted using `func`.
436 414 func : callable
437 415 A callable for computing the format data.
438 416 `func` will be called with the object to be formatted,
439 417 and will return the raw data in this formatter's format.
440 418 Subclasses may use a different call signature for the
441 419 `func` argument.
442 420
443 421 If `func` is None or not specified, there will be no change,
444 422 only returning the current value.
445 423
446 424 Returns
447 425 -------
448 426 oldfunc : callable
449 427 The currently registered callable.
450 428 If you are registering a new formatter,
451 429 this will be the previous value (to enable restoring later).
452 430 """
453 431 # if string given, interpret as 'pkg.module.class_name'
454 432 if isinstance(typ, string_types):
455 433 type_module, type_name = typ.rsplit('.', 1)
456 434 return self.for_type_by_name(type_module, type_name, func)
457 435
458 436 try:
459 437 oldfunc = self.lookup_by_type(typ)
460 438 except KeyError:
461 439 oldfunc = None
462 440
463 441 if func is not None:
464 442 self.type_printers[typ] = func
465 443
466 444 return oldfunc
467 445
468 446 def for_type_by_name(self, type_module, type_name, func=None):
469 447 """Add a format function for a type specified by the full dotted
470 448 module and name of the type, rather than the type of the object.
471 449
472 450 Parameters
473 451 ----------
474 452 type_module : str
475 453 The full dotted name of the module the type is defined in, like
476 454 ``numpy``.
477 455 type_name : str
478 456 The name of the type (the class name), like ``dtype``
479 457 func : callable
480 458 A callable for computing the format data.
481 459 `func` will be called with the object to be formatted,
482 460 and will return the raw data in this formatter's format.
483 461 Subclasses may use a different call signature for the
484 462 `func` argument.
485 463
486 464 If `func` is None or unspecified, there will be no change,
487 465 only returning the current value.
488 466
489 467 Returns
490 468 -------
491 469 oldfunc : callable
492 470 The currently registered callable.
493 471 If you are registering a new formatter,
494 472 this will be the previous value (to enable restoring later).
495 473 """
496 474 key = (type_module, type_name)
497 475
498 476 try:
499 477 oldfunc = self.lookup_by_type("%s.%s" % key)
500 478 except KeyError:
501 479 oldfunc = None
502 480
503 481 if func is not None:
504 482 self.deferred_printers[key] = func
505 483 return oldfunc
506 484
507 485 def pop(self, typ, default=_raise_key_error):
508 486 """Pop a formatter for the given type.
509 487
510 488 Parameters
511 489 ----------
512 490 typ : type or '__module__.__name__' string for a type
513 491 default : object
514 492 value to be returned if no formatter is registered for typ.
515 493
516 494 Returns
517 495 -------
518 496 obj : object
519 497 The last registered object for the type.
520 498
521 499 Raises
522 500 ------
523 501 KeyError if the type is not registered and default is not specified.
524 502 """
525 503
526 504 if isinstance(typ, string_types):
527 505 typ_key = tuple(typ.rsplit('.',1))
528 506 if typ_key not in self.deferred_printers:
529 507 # We may have it cached in the type map. We will have to
530 508 # iterate over all of the types to check.
531 509 for cls in self.type_printers:
532 510 if _mod_name_key(cls) == typ_key:
533 511 old = self.type_printers.pop(cls)
534 512 break
535 513 else:
536 514 old = default
537 515 else:
538 516 old = self.deferred_printers.pop(typ_key)
539 517 else:
540 518 if typ in self.type_printers:
541 519 old = self.type_printers.pop(typ)
542 520 else:
543 521 old = self.deferred_printers.pop(_mod_name_key(typ), default)
544 522 if old is _raise_key_error:
545 523 raise KeyError("No registered value for {0!r}".format(typ))
546 524 return old
547 525
548 526 def _in_deferred_types(self, cls):
549 527 """
550 528 Check if the given class is specified in the deferred type registry.
551 529
552 530 Successful matches will be moved to the regular type registry for future use.
553 531 """
554 532 mod = getattr(cls, '__module__', None)
555 533 name = getattr(cls, '__name__', None)
556 534 key = (mod, name)
557 535 if key in self.deferred_printers:
558 536 # Move the printer over to the regular registry.
559 537 printer = self.deferred_printers.pop(key)
560 538 self.type_printers[cls] = printer
561 539 return True
562 540 return False
563 541
564 542
565 543 class PlainTextFormatter(BaseFormatter):
566 544 """The default pretty-printer.
567 545
568 546 This uses :mod:`IPython.lib.pretty` to compute the format data of
569 547 the object. If the object cannot be pretty printed, :func:`repr` is used.
570 548 See the documentation of :mod:`IPython.lib.pretty` for details on
571 549 how to write pretty printers. Here is a simple example::
572 550
573 551 def dtype_pprinter(obj, p, cycle):
574 552 if cycle:
575 553 return p.text('dtype(...)')
576 554 if hasattr(obj, 'fields'):
577 555 if obj.fields is None:
578 556 p.text(repr(obj))
579 557 else:
580 558 p.begin_group(7, 'dtype([')
581 559 for i, field in enumerate(obj.descr):
582 560 if i > 0:
583 561 p.text(',')
584 562 p.breakable()
585 563 p.pretty(field)
586 564 p.end_group(7, '])')
587 565 """
588 566
589 567 # The format type of data returned.
590 568 format_type = Unicode('text/plain')
591 569
592 570 # This subclass ignores this attribute as it always need to return
593 571 # something.
594 572 enabled = Bool(True, config=False)
595 573
596 574 max_seq_length = Integer(pretty.MAX_SEQ_LENGTH, config=True,
597 575 help="""Truncate large collections (lists, dicts, tuples, sets) to this size.
598 576
599 577 Set to 0 to disable truncation.
600 578 """
601 579 )
602 580
603 581 # Look for a _repr_pretty_ methods to use for pretty printing.
604 582 print_method = ObjectName('_repr_pretty_')
605 583
606 584 # Whether to pretty-print or not.
607 585 pprint = Bool(True, config=True)
608 586
609 587 # Whether to be verbose or not.
610 588 verbose = Bool(False, config=True)
611 589
612 590 # The maximum width.
613 591 max_width = Integer(79, config=True)
614 592
615 593 # The newline character.
616 594 newline = Unicode('\n', config=True)
617 595
618 596 # format-string for pprinting floats
619 597 float_format = Unicode('%r')
620 598 # setter for float precision, either int or direct format-string
621 599 float_precision = CUnicode('', config=True)
622 600
623 601 def _float_precision_changed(self, name, old, new):
624 602 """float_precision changed, set float_format accordingly.
625 603
626 604 float_precision can be set by int or str.
627 605 This will set float_format, after interpreting input.
628 606 If numpy has been imported, numpy print precision will also be set.
629 607
630 608 integer `n` sets format to '%.nf', otherwise, format set directly.
631 609
632 610 An empty string returns to defaults (repr for float, 8 for numpy).
633 611
634 612 This parameter can be set via the '%precision' magic.
635 613 """
636 614
637 615 if '%' in new:
638 616 # got explicit format string
639 617 fmt = new
640 618 try:
641 619 fmt%3.14159
642 620 except Exception:
643 621 raise ValueError("Precision must be int or format string, not %r"%new)
644 622 elif new:
645 623 # otherwise, should be an int
646 624 try:
647 625 i = int(new)
648 626 assert i >= 0
649 627 except ValueError:
650 628 raise ValueError("Precision must be int or format string, not %r"%new)
651 629 except AssertionError:
652 630 raise ValueError("int precision must be non-negative, not %r"%i)
653 631
654 632 fmt = '%%.%if'%i
655 633 if 'numpy' in sys.modules:
656 634 # set numpy precision if it has been imported
657 635 import numpy
658 636 numpy.set_printoptions(precision=i)
659 637 else:
660 638 # default back to repr
661 639 fmt = '%r'
662 640 if 'numpy' in sys.modules:
663 641 import numpy
664 642 # numpy default is 8
665 643 numpy.set_printoptions(precision=8)
666 644 self.float_format = fmt
667 645
668 646 # Use the default pretty printers from IPython.lib.pretty.
669 647 def _singleton_printers_default(self):
670 648 return pretty._singleton_pprinters.copy()
671 649
672 650 def _type_printers_default(self):
673 651 d = pretty._type_pprinters.copy()
674 652 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
675 653 return d
676 654
677 655 def _deferred_printers_default(self):
678 656 return pretty._deferred_type_pprinters.copy()
679 657
680 658 #### FormatterABC interface ####
681 659
682 660 @catch_format_error
683 661 def __call__(self, obj):
684 662 """Compute the pretty representation of the object."""
685 663 if not self.pprint:
686 664 return repr(obj)
687 665 else:
688 666 # handle str and unicode on Python 2
689 667 # io.StringIO only accepts unicode,
690 668 # cStringIO doesn't handle unicode on py2,
691 669 # StringIO allows str, unicode but only ascii str
692 670 stream = pretty.CUnicodeIO()
693 671 printer = pretty.RepresentationPrinter(stream, self.verbose,
694 672 self.max_width, self.newline,
695 673 max_seq_length=self.max_seq_length,
696 674 singleton_pprinters=self.singleton_printers,
697 675 type_pprinters=self.type_printers,
698 676 deferred_pprinters=self.deferred_printers)
699 677 printer.pretty(obj)
700 678 printer.flush()
701 679 return stream.getvalue()
702 680
703 681
704 682 class HTMLFormatter(BaseFormatter):
705 683 """An HTML formatter.
706 684
707 685 To define the callables that compute the HTML representation of your
708 686 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
709 687 or :meth:`for_type_by_name` methods to register functions that handle
710 688 this.
711 689
712 690 The return value of this formatter should be a valid HTML snippet that
713 691 could be injected into an existing DOM. It should *not* include the
714 692 ```<html>`` or ```<body>`` tags.
715 693 """
716 694 format_type = Unicode('text/html')
717 695
718 696 print_method = ObjectName('_repr_html_')
719 697
720 698
721 699 class MarkdownFormatter(BaseFormatter):
722 700 """A Markdown formatter.
723 701
724 702 To define the callables that compute the Markdown representation of your
725 703 objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type`
726 704 or :meth:`for_type_by_name` methods to register functions that handle
727 705 this.
728 706
729 707 The return value of this formatter should be a valid Markdown.
730 708 """
731 709 format_type = Unicode('text/markdown')
732 710
733 711 print_method = ObjectName('_repr_markdown_')
734 712
735 713 class SVGFormatter(BaseFormatter):
736 714 """An SVG formatter.
737 715
738 716 To define the callables that compute the SVG representation of your
739 717 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
740 718 or :meth:`for_type_by_name` methods to register functions that handle
741 719 this.
742 720
743 721 The return value of this formatter should be valid SVG enclosed in
744 722 ```<svg>``` tags, that could be injected into an existing DOM. It should
745 723 *not* include the ```<html>`` or ```<body>`` tags.
746 724 """
747 725 format_type = Unicode('image/svg+xml')
748 726
749 727 print_method = ObjectName('_repr_svg_')
750 728
751 729
752 730 class PNGFormatter(BaseFormatter):
753 731 """A PNG formatter.
754 732
755 733 To define the callables that compute the PNG representation of your
756 734 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
757 735 or :meth:`for_type_by_name` methods to register functions that handle
758 736 this.
759 737
760 738 The return value of this formatter should be raw PNG data, *not*
761 739 base64 encoded.
762 740 """
763 741 format_type = Unicode('image/png')
764 742
765 743 print_method = ObjectName('_repr_png_')
766 744
767 745 _return_type = (bytes, unicode_type)
768 746
769 747
770 748 class JPEGFormatter(BaseFormatter):
771 749 """A JPEG formatter.
772 750
773 751 To define the callables that compute the JPEG representation of your
774 752 objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
775 753 or :meth:`for_type_by_name` methods to register functions that handle
776 754 this.
777 755
778 756 The return value of this formatter should be raw JPEG data, *not*
779 757 base64 encoded.
780 758 """
781 759 format_type = Unicode('image/jpeg')
782 760
783 761 print_method = ObjectName('_repr_jpeg_')
784 762
785 763 _return_type = (bytes, unicode_type)
786 764
787 765
788 766 class LatexFormatter(BaseFormatter):
789 767 """A LaTeX formatter.
790 768
791 769 To define the callables that compute the LaTeX representation of your
792 770 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
793 771 or :meth:`for_type_by_name` methods to register functions that handle
794 772 this.
795 773
796 774 The return value of this formatter should be a valid LaTeX equation,
797 775 enclosed in either ```$```, ```$$``` or another LaTeX equation
798 776 environment.
799 777 """
800 778 format_type = Unicode('text/latex')
801 779
802 780 print_method = ObjectName('_repr_latex_')
803 781
804 782
805 783 class JSONFormatter(BaseFormatter):
806 784 """A JSON string formatter.
807 785
808 786 To define the callables that compute the JSONable representation of
809 787 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
810 788 or :meth:`for_type_by_name` methods to register functions that handle
811 789 this.
812 790
813 791 The return value of this formatter should be a JSONable list or dict.
814 792 JSON scalars (None, number, string) are not allowed, only dict or list containers.
815 793 """
816 794 format_type = Unicode('application/json')
817 795 _return_type = (list, dict)
818 796
819 797 print_method = ObjectName('_repr_json_')
820 798
821 799 def _check_return(self, r, obj):
822 800 """Check that a return value is appropriate
823 801
824 802 Return the value if so, None otherwise, warning if invalid.
825 803 """
826 804 if r is None:
827 805 return
828 806 md = None
829 807 if isinstance(r, tuple):
830 808 # unpack data, metadata tuple for type checking on first element
831 809 r, md = r
832 810
833 811 # handle deprecated JSON-as-string form from IPython < 3
834 812 if isinstance(r, string_types):
835 813 warnings.warn("JSON expects JSONable list/dict containers, not JSON strings",
836 814 FormatterWarning)
837 815 r = json.loads(r)
838 816
839 817 if md is not None:
840 818 # put the tuple back together
841 819 r = (r, md)
842 820 return super(JSONFormatter, self)._check_return(r, obj)
843 821
844 822
845 823 class JavascriptFormatter(BaseFormatter):
846 824 """A Javascript formatter.
847 825
848 826 To define the callables that compute the Javascript representation of
849 827 your objects, define a :meth:`_repr_javascript_` method or use the
850 828 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
851 829 that handle this.
852 830
853 831 The return value of this formatter should be valid Javascript code and
854 832 should *not* be enclosed in ```<script>``` tags.
855 833 """
856 834 format_type = Unicode('application/javascript')
857 835
858 836 print_method = ObjectName('_repr_javascript_')
859 837
860 838
861 839 class PDFFormatter(BaseFormatter):
862 840 """A PDF formatter.
863 841
864 842 To define the callables that compute the PDF representation of your
865 843 objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type`
866 844 or :meth:`for_type_by_name` methods to register functions that handle
867 845 this.
868 846
869 847 The return value of this formatter should be raw PDF data, *not*
870 848 base64 encoded.
871 849 """
872 850 format_type = Unicode('application/pdf')
873 851
874 852 print_method = ObjectName('_repr_pdf_')
875 853
876 854 _return_type = (bytes, unicode_type)
877 855
878 856 class IPythonDisplayFormatter(BaseFormatter):
879 857 """A Formatter for objects that know how to display themselves.
880 858
881 859 To define the callables that compute the representation of your
882 860 objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type`
883 861 or :meth:`for_type_by_name` methods to register functions that handle
884 862 this. Unlike mime-type displays, this method should not return anything,
885 863 instead calling any appropriate display methods itself.
886 864
887 865 This display formatter has highest priority.
888 866 If it fires, no other display formatter will be called.
889 867 """
890 868 print_method = ObjectName('_ipython_display_')
891 869 _return_type = (type(None), bool)
892 870
893 871
894 872 @catch_format_error
895 873 def __call__(self, obj):
896 874 """Compute the format for an object."""
897 875 if self.enabled:
898 876 # lookup registered printer
899 877 try:
900 878 printer = self.lookup(obj)
901 879 except KeyError:
902 880 pass
903 881 else:
904 882 printer(obj)
905 883 return True
906 884 # Finally look for special method names
907 method = _safe_get_formatter_method(obj, self.print_method)
885 method = get_real_method(obj, self.print_method)
908 886 if method is not None:
909 887 method()
910 888 return True
911 889
912 890
913 891 FormatterABC.register(BaseFormatter)
914 892 FormatterABC.register(PlainTextFormatter)
915 893 FormatterABC.register(HTMLFormatter)
916 894 FormatterABC.register(MarkdownFormatter)
917 895 FormatterABC.register(SVGFormatter)
918 896 FormatterABC.register(PNGFormatter)
919 897 FormatterABC.register(PDFFormatter)
920 898 FormatterABC.register(JPEGFormatter)
921 899 FormatterABC.register(LatexFormatter)
922 900 FormatterABC.register(JSONFormatter)
923 901 FormatterABC.register(JavascriptFormatter)
924 902 FormatterABC.register(IPythonDisplayFormatter)
925 903
926 904
927 905 def format_display_data(obj, include=None, exclude=None):
928 906 """Return a format data dict for an object.
929 907
930 908 By default all format types will be computed.
931 909
932 910 The following MIME types are currently implemented:
933 911
934 912 * text/plain
935 913 * text/html
936 914 * text/markdown
937 915 * text/latex
938 916 * application/json
939 917 * application/javascript
940 918 * application/pdf
941 919 * image/png
942 920 * image/jpeg
943 921 * image/svg+xml
944 922
945 923 Parameters
946 924 ----------
947 925 obj : object
948 926 The Python object whose format data will be computed.
949 927
950 928 Returns
951 929 -------
952 930 format_dict : dict
953 931 A dictionary of key/value pairs, one or each format that was
954 932 generated for the object. The keys are the format types, which
955 933 will usually be MIME type strings and the values and JSON'able
956 934 data structure containing the raw data for the representation in
957 935 that format.
958 936 include : list or tuple, optional
959 937 A list of format type strings (MIME types) to include in the
960 938 format data dict. If this is set *only* the format types included
961 939 in this list will be computed.
962 940 exclude : list or tuple, optional
963 941 A list of format type string (MIME types) to exclue in the format
964 942 data dict. If this is set all format types will be computed,
965 943 except for those included in this argument.
966 944 """
967 945 from IPython.core.interactiveshell import InteractiveShell
968 946
969 947 InteractiveShell.instance().display_formatter.format(
970 948 obj,
971 949 include,
972 950 exclude
973 951 )
974 952
@@ -1,58 +1,81 b''
1 1 # encoding: utf-8
2 2 """A fancy version of Python's builtin :func:`dir` function.
3 3 """
4 4
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2008-2011 The IPython Development Team
7 #
8 # Distributed under the terms of the BSD License. The full license is in
9 # the file COPYING, distributed as part of this software.
10 #-----------------------------------------------------------------------------
11
12 #-----------------------------------------------------------------------------
13 # Imports
14 #-----------------------------------------------------------------------------
15 from .py3compat import string_types
5 # Copyright (c) IPython Development Team.
6 # Distributed under the terms of the Modified BSD License.
16 7
17 #-----------------------------------------------------------------------------
18 # Code
19 #-----------------------------------------------------------------------------
8 import inspect
9 from .py3compat import string_types
20 10
21 11
22 12 def safe_hasattr(obj, attr):
23 13 """In recent versions of Python, hasattr() only catches AttributeError.
24 14 This catches all errors.
25 15 """
26 16 try:
27 17 getattr(obj, attr)
28 18 return True
29 19 except:
30 20 return False
31 21
32 22
33 23 def dir2(obj):
34 24 """dir2(obj) -> list of strings
35 25
36 26 Extended version of the Python builtin dir(), which does a few extra
37 27 checks.
38 28
39 29 This version is guaranteed to return only a list of true strings, whereas
40 30 dir() returns anything that objects inject into themselves, even if they
41 31 are later not really valid for attribute access (many extension libraries
42 32 have such bugs).
43 33 """
44 34
45 35 # Start building the attribute list via dir(), and then complete it
46 36 # with a few extra special-purpose calls.
47 37
48 38 try:
49 39 words = set(dir(obj))
50 40 except Exception:
51 41 # TypeError: dir(obj) does not return a list
52 42 words = set()
53 43
54 44 # filter out non-string attributes which may be stuffed by dir() calls
55 45 # and poor coding in third-party modules
56 46
57 47 words = [w for w in words if isinstance(w, string_types)]
58 48 return sorted(words)
49
50
51 def get_real_method(obj, name):
52 """Like getattr, but with a few extra sanity checks:
53
54 - If obj is a class, ignore its methods
55 - Check if obj is a proxy that claims to have all attributes
56 - Catch attribute access failing with any exception
57 - Check that the attribute is a callable object
58
59 Returns the method or None.
60 """
61 if inspect.isclass(obj):
62 return None
63
64 try:
65 canary = getattr(obj, '_ipython_canary_method_should_not_exist_', None)
66 except Exception:
67 return None
68
69 if canary is not None:
70 # It claimed to have an attribute it should never have
71 return None
72
73 try:
74 m = getattr(obj, name, None)
75 except Exception:
76 return None
77
78 if callable(m):
79 return m
80
81 return None
General Comments 0
You need to be logged in to leave comments. Login now