##// END OF EJS Templates
Update what's new and limit number of subclasses....
Matthias Bussonnier -
Show More
@@ -1,1059 +1,1062 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Tools for inspecting Python objects.
3 3
4 4 Uses syntax highlighting for presenting the various information elements.
5 5
6 6 Similar in spirit to the inspect module, but all calls take a name argument to
7 7 reference the name under which an object is being read.
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 __all__ = ['Inspector','InspectColors']
14 14
15 15 # stdlib modules
16 16 import ast
17 17 import inspect
18 18 from inspect import signature
19 19 import linecache
20 20 import warnings
21 21 import os
22 22 from textwrap import dedent
23 23 import types
24 24 import io as stdlib_io
25 25 from itertools import zip_longest
26 26
27 27 # IPython's own
28 28 from IPython.core import page
29 29 from IPython.lib.pretty import pretty
30 30 from IPython.testing.skipdoctest import skip_doctest
31 31 from IPython.utils import PyColorize
32 32 from IPython.utils import openpy
33 33 from IPython.utils import py3compat
34 34 from IPython.utils.dir2 import safe_hasattr
35 35 from IPython.utils.path import compress_user
36 36 from IPython.utils.text import indent
37 37 from IPython.utils.wildcard import list_namespace
38 38 from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable
39 39 from IPython.utils.py3compat import cast_unicode
40 40 from IPython.utils.colorable import Colorable
41 41 from IPython.utils.decorators import undoc
42 42
43 43 from pygments import highlight
44 44 from pygments.lexers import PythonLexer
45 45 from pygments.formatters import HtmlFormatter
46 46
47 47 def pylight(code):
48 48 return highlight(code, PythonLexer(), HtmlFormatter(noclasses=True))
49 49
50 50 # builtin docstrings to ignore
51 51 _func_call_docstring = types.FunctionType.__call__.__doc__
52 52 _object_init_docstring = object.__init__.__doc__
53 53 _builtin_type_docstrings = {
54 54 inspect.getdoc(t) for t in (types.ModuleType, types.MethodType,
55 55 types.FunctionType, property)
56 56 }
57 57
58 58 _builtin_func_type = type(all)
59 59 _builtin_meth_type = type(str.upper) # Bound methods have the same type as builtin functions
60 60 #****************************************************************************
61 61 # Builtin color schemes
62 62
63 63 Colors = TermColors # just a shorthand
64 64
65 65 InspectColors = PyColorize.ANSICodeColors
66 66
67 67 #****************************************************************************
68 68 # Auxiliary functions and objects
69 69
70 70 # See the messaging spec for the definition of all these fields. This list
71 71 # effectively defines the order of display
72 72 info_fields = ['type_name', 'base_class', 'string_form', 'namespace',
73 73 'length', 'file', 'definition', 'docstring', 'source',
74 74 'init_definition', 'class_docstring', 'init_docstring',
75 75 'call_def', 'call_docstring',
76 76 # These won't be printed but will be used to determine how to
77 77 # format the object
78 78 'ismagic', 'isalias', 'isclass', 'argspec', 'found', 'name'
79 79 ]
80 80
81 81
82 82 def object_info(**kw):
83 83 """Make an object info dict with all fields present."""
84 84 infodict = dict(zip_longest(info_fields, [None]))
85 85 infodict.update(kw)
86 86 return infodict
87 87
88 88
89 89 def get_encoding(obj):
90 90 """Get encoding for python source file defining obj
91 91
92 92 Returns None if obj is not defined in a sourcefile.
93 93 """
94 94 ofile = find_file(obj)
95 95 # run contents of file through pager starting at line where the object
96 96 # is defined, as long as the file isn't binary and is actually on the
97 97 # filesystem.
98 98 if ofile is None:
99 99 return None
100 100 elif ofile.endswith(('.so', '.dll', '.pyd')):
101 101 return None
102 102 elif not os.path.isfile(ofile):
103 103 return None
104 104 else:
105 105 # Print only text files, not extension binaries. Note that
106 106 # getsourcelines returns lineno with 1-offset and page() uses
107 107 # 0-offset, so we must adjust.
108 108 with stdlib_io.open(ofile, 'rb') as buffer: # Tweaked to use io.open for Python 2
109 109 encoding, lines = openpy.detect_encoding(buffer.readline)
110 110 return encoding
111 111
112 112 def getdoc(obj):
113 113 """Stable wrapper around inspect.getdoc.
114 114
115 115 This can't crash because of attribute problems.
116 116
117 117 It also attempts to call a getdoc() method on the given object. This
118 118 allows objects which provide their docstrings via non-standard mechanisms
119 119 (like Pyro proxies) to still be inspected by ipython's ? system.
120 120 """
121 121 # Allow objects to offer customized documentation via a getdoc method:
122 122 try:
123 123 ds = obj.getdoc()
124 124 except Exception:
125 125 pass
126 126 else:
127 127 if isinstance(ds, str):
128 128 return inspect.cleandoc(ds)
129 129 docstr = inspect.getdoc(obj)
130 130 encoding = get_encoding(obj)
131 131 return py3compat.cast_unicode(docstr, encoding=encoding)
132 132
133 133
134 134 def getsource(obj, oname=''):
135 135 """Wrapper around inspect.getsource.
136 136
137 137 This can be modified by other projects to provide customized source
138 138 extraction.
139 139
140 140 Parameters
141 141 ----------
142 142 obj : object
143 143 an object whose source code we will attempt to extract
144 144 oname : str
145 145 (optional) a name under which the object is known
146 146
147 147 Returns
148 148 -------
149 149 src : unicode or None
150 150
151 151 """
152 152
153 153 if isinstance(obj, property):
154 154 sources = []
155 155 for attrname in ['fget', 'fset', 'fdel']:
156 156 fn = getattr(obj, attrname)
157 157 if fn is not None:
158 158 encoding = get_encoding(fn)
159 159 oname_prefix = ('%s.' % oname) if oname else ''
160 160 sources.append(cast_unicode(
161 161 ''.join(('# ', oname_prefix, attrname)),
162 162 encoding=encoding))
163 163 if inspect.isfunction(fn):
164 164 sources.append(dedent(getsource(fn)))
165 165 else:
166 166 # Default str/repr only prints function name,
167 167 # pretty.pretty prints module name too.
168 168 sources.append(cast_unicode(
169 169 '%s%s = %s\n' % (
170 170 oname_prefix, attrname, pretty(fn)),
171 171 encoding=encoding))
172 172 if sources:
173 173 return '\n'.join(sources)
174 174 else:
175 175 return None
176 176
177 177 else:
178 178 # Get source for non-property objects.
179 179
180 180 obj = _get_wrapped(obj)
181 181
182 182 try:
183 183 src = inspect.getsource(obj)
184 184 except TypeError:
185 185 # The object itself provided no meaningful source, try looking for
186 186 # its class definition instead.
187 187 if hasattr(obj, '__class__'):
188 188 try:
189 189 src = inspect.getsource(obj.__class__)
190 190 except TypeError:
191 191 return None
192 192
193 193 encoding = get_encoding(obj)
194 194 return cast_unicode(src, encoding=encoding)
195 195
196 196
197 197 def is_simple_callable(obj):
198 198 """True if obj is a function ()"""
199 199 return (inspect.isfunction(obj) or inspect.ismethod(obj) or \
200 200 isinstance(obj, _builtin_func_type) or isinstance(obj, _builtin_meth_type))
201 201
202 202
203 203 def getargspec(obj):
204 204 """Wrapper around :func:`inspect.getfullargspec` on Python 3, and
205 205 :func:inspect.getargspec` on Python 2.
206 206
207 207 In addition to functions and methods, this can also handle objects with a
208 208 ``__call__`` attribute.
209 209 """
210 210 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
211 211 obj = obj.__call__
212 212
213 213 return inspect.getfullargspec(obj)
214 214
215 215
216 216 def format_argspec(argspec):
217 217 """Format argspect, convenience wrapper around inspect's.
218 218
219 219 This takes a dict instead of ordered arguments and calls
220 220 inspect.format_argspec with the arguments in the necessary order.
221 221 """
222 222 return inspect.formatargspec(argspec['args'], argspec['varargs'],
223 223 argspec['varkw'], argspec['defaults'])
224 224
225 225 @undoc
226 226 def call_tip(oinfo, format_call=True):
227 227 """DEPRECATED. Extract call tip data from an oinfo dict.
228 228 """
229 229 warnings.warn('`call_tip` function is deprecated as of IPython 6.0'
230 230 'and will be removed in future versions.', DeprecationWarning, stacklevel=2)
231 231 # Get call definition
232 232 argspec = oinfo.get('argspec')
233 233 if argspec is None:
234 234 call_line = None
235 235 else:
236 236 # Callable objects will have 'self' as their first argument, prune
237 237 # it out if it's there for clarity (since users do *not* pass an
238 238 # extra first argument explicitly).
239 239 try:
240 240 has_self = argspec['args'][0] == 'self'
241 241 except (KeyError, IndexError):
242 242 pass
243 243 else:
244 244 if has_self:
245 245 argspec['args'] = argspec['args'][1:]
246 246
247 247 call_line = oinfo['name']+format_argspec(argspec)
248 248
249 249 # Now get docstring.
250 250 # The priority is: call docstring, constructor docstring, main one.
251 251 doc = oinfo.get('call_docstring')
252 252 if doc is None:
253 253 doc = oinfo.get('init_docstring')
254 254 if doc is None:
255 255 doc = oinfo.get('docstring','')
256 256
257 257 return call_line, doc
258 258
259 259
260 260 def _get_wrapped(obj):
261 261 """Get the original object if wrapped in one or more @decorators
262 262
263 263 Some objects automatically construct similar objects on any unrecognised
264 264 attribute access (e.g. unittest.mock.call). To protect against infinite loops,
265 265 this will arbitrarily cut off after 100 levels of obj.__wrapped__
266 266 attribute access. --TK, Jan 2016
267 267 """
268 268 orig_obj = obj
269 269 i = 0
270 270 while safe_hasattr(obj, '__wrapped__'):
271 271 obj = obj.__wrapped__
272 272 i += 1
273 273 if i > 100:
274 274 # __wrapped__ is probably a lie, so return the thing we started with
275 275 return orig_obj
276 276 return obj
277 277
278 278 def find_file(obj):
279 279 """Find the absolute path to the file where an object was defined.
280 280
281 281 This is essentially a robust wrapper around `inspect.getabsfile`.
282 282
283 283 Returns None if no file can be found.
284 284
285 285 Parameters
286 286 ----------
287 287 obj : any Python object
288 288
289 289 Returns
290 290 -------
291 291 fname : str
292 292 The absolute path to the file where the object was defined.
293 293 """
294 294 obj = _get_wrapped(obj)
295 295
296 296 fname = None
297 297 try:
298 298 fname = inspect.getabsfile(obj)
299 299 except TypeError:
300 300 # For an instance, the file that matters is where its class was
301 301 # declared.
302 302 if hasattr(obj, '__class__'):
303 303 try:
304 304 fname = inspect.getabsfile(obj.__class__)
305 305 except TypeError:
306 306 # Can happen for builtins
307 307 pass
308 308 except:
309 309 pass
310 310 return cast_unicode(fname)
311 311
312 312
313 313 def find_source_lines(obj):
314 314 """Find the line number in a file where an object was defined.
315 315
316 316 This is essentially a robust wrapper around `inspect.getsourcelines`.
317 317
318 318 Returns None if no file can be found.
319 319
320 320 Parameters
321 321 ----------
322 322 obj : any Python object
323 323
324 324 Returns
325 325 -------
326 326 lineno : int
327 327 The line number where the object definition starts.
328 328 """
329 329 obj = _get_wrapped(obj)
330 330
331 331 try:
332 332 try:
333 333 lineno = inspect.getsourcelines(obj)[1]
334 334 except TypeError:
335 335 # For instances, try the class object like getsource() does
336 336 if hasattr(obj, '__class__'):
337 337 lineno = inspect.getsourcelines(obj.__class__)[1]
338 338 else:
339 339 lineno = None
340 340 except:
341 341 return None
342 342
343 343 return lineno
344 344
345 345 class Inspector(Colorable):
346 346
347 347 def __init__(self, color_table=InspectColors,
348 348 code_color_table=PyColorize.ANSICodeColors,
349 349 scheme=None,
350 350 str_detail_level=0,
351 351 parent=None, config=None):
352 352 super(Inspector, self).__init__(parent=parent, config=config)
353 353 self.color_table = color_table
354 354 self.parser = PyColorize.Parser(out='str', parent=self, style=scheme)
355 355 self.format = self.parser.format
356 356 self.str_detail_level = str_detail_level
357 357 self.set_active_scheme(scheme)
358 358
359 359 def _getdef(self,obj,oname=''):
360 360 """Return the call signature for any callable object.
361 361
362 362 If any exception is generated, None is returned instead and the
363 363 exception is suppressed."""
364 364 try:
365 365 hdef = _render_signature(signature(obj), oname)
366 366 return cast_unicode(hdef)
367 367 except:
368 368 return None
369 369
370 370 def __head(self,h):
371 371 """Return a header string with proper colors."""
372 372 return '%s%s%s' % (self.color_table.active_colors.header,h,
373 373 self.color_table.active_colors.normal)
374 374
375 375 def set_active_scheme(self, scheme):
376 376 if scheme is not None:
377 377 self.color_table.set_active_scheme(scheme)
378 378 self.parser.color_table.set_active_scheme(scheme)
379 379
380 380 def noinfo(self, msg, oname):
381 381 """Generic message when no information is found."""
382 382 print('No %s found' % msg, end=' ')
383 383 if oname:
384 384 print('for %s' % oname)
385 385 else:
386 386 print()
387 387
388 388 def pdef(self, obj, oname=''):
389 389 """Print the call signature for any callable object.
390 390
391 391 If the object is a class, print the constructor information."""
392 392
393 393 if not callable(obj):
394 394 print('Object is not callable.')
395 395 return
396 396
397 397 header = ''
398 398
399 399 if inspect.isclass(obj):
400 400 header = self.__head('Class constructor information:\n')
401 401
402 402
403 403 output = self._getdef(obj,oname)
404 404 if output is None:
405 405 self.noinfo('definition header',oname)
406 406 else:
407 407 print(header,self.format(output), end=' ')
408 408
409 409 # In Python 3, all classes are new-style, so they all have __init__.
410 410 @skip_doctest
411 411 def pdoc(self, obj, oname='', formatter=None):
412 412 """Print the docstring for any object.
413 413
414 414 Optional:
415 415 -formatter: a function to run the docstring through for specially
416 416 formatted docstrings.
417 417
418 418 Examples
419 419 --------
420 420
421 421 In [1]: class NoInit:
422 422 ...: pass
423 423
424 424 In [2]: class NoDoc:
425 425 ...: def __init__(self):
426 426 ...: pass
427 427
428 428 In [3]: %pdoc NoDoc
429 429 No documentation found for NoDoc
430 430
431 431 In [4]: %pdoc NoInit
432 432 No documentation found for NoInit
433 433
434 434 In [5]: obj = NoInit()
435 435
436 436 In [6]: %pdoc obj
437 437 No documentation found for obj
438 438
439 439 In [5]: obj2 = NoDoc()
440 440
441 441 In [6]: %pdoc obj2
442 442 No documentation found for obj2
443 443 """
444 444
445 445 head = self.__head # For convenience
446 446 lines = []
447 447 ds = getdoc(obj)
448 448 if formatter:
449 449 ds = formatter(ds).get('plain/text', ds)
450 450 if ds:
451 451 lines.append(head("Class docstring:"))
452 452 lines.append(indent(ds))
453 453 if inspect.isclass(obj) and hasattr(obj, '__init__'):
454 454 init_ds = getdoc(obj.__init__)
455 455 if init_ds is not None:
456 456 lines.append(head("Init docstring:"))
457 457 lines.append(indent(init_ds))
458 458 elif hasattr(obj,'__call__'):
459 459 call_ds = getdoc(obj.__call__)
460 460 if call_ds:
461 461 lines.append(head("Call docstring:"))
462 462 lines.append(indent(call_ds))
463 463
464 464 if not lines:
465 465 self.noinfo('documentation',oname)
466 466 else:
467 467 page.page('\n'.join(lines))
468 468
469 469 def psource(self, obj, oname=''):
470 470 """Print the source code for an object."""
471 471
472 472 # Flush the source cache because inspect can return out-of-date source
473 473 linecache.checkcache()
474 474 try:
475 475 src = getsource(obj, oname=oname)
476 476 except Exception:
477 477 src = None
478 478
479 479 if src is None:
480 480 self.noinfo('source', oname)
481 481 else:
482 482 page.page(self.format(src))
483 483
484 484 def pfile(self, obj, oname=''):
485 485 """Show the whole file where an object was defined."""
486 486
487 487 lineno = find_source_lines(obj)
488 488 if lineno is None:
489 489 self.noinfo('file', oname)
490 490 return
491 491
492 492 ofile = find_file(obj)
493 493 # run contents of file through pager starting at line where the object
494 494 # is defined, as long as the file isn't binary and is actually on the
495 495 # filesystem.
496 496 if ofile.endswith(('.so', '.dll', '.pyd')):
497 497 print('File %r is binary, not printing.' % ofile)
498 498 elif not os.path.isfile(ofile):
499 499 print('File %r does not exist, not printing.' % ofile)
500 500 else:
501 501 # Print only text files, not extension binaries. Note that
502 502 # getsourcelines returns lineno with 1-offset and page() uses
503 503 # 0-offset, so we must adjust.
504 504 page.page(self.format(openpy.read_py_file(ofile, skip_encoding_cookie=False)), lineno - 1)
505 505
506 506 def _format_fields(self, fields, title_width=0):
507 507 """Formats a list of fields for display.
508 508
509 509 Parameters
510 510 ----------
511 511 fields : list
512 512 A list of 2-tuples: (field_title, field_content)
513 513 title_width : int
514 514 How many characters to pad titles to. Default to longest title.
515 515 """
516 516 out = []
517 517 header = self.__head
518 518 if title_width == 0:
519 519 title_width = max(len(title) + 2 for title, _ in fields)
520 520 for title, content in fields:
521 521 if len(content.splitlines()) > 1:
522 522 title = header(title + ':') + '\n'
523 523 else:
524 524 title = header((title + ':').ljust(title_width))
525 525 out.append(cast_unicode(title) + cast_unicode(content))
526 526 return "\n".join(out)
527 527
528 528 def _mime_format(self, text, formatter=None):
529 529 """Return a mime bundle representation of the input text.
530 530
531 531 - if `formatter` is None, the returned mime bundle has
532 532 a `text/plain` field, with the input text.
533 533 a `text/html` field with a `<pre>` tag containing the input text.
534 534
535 535 - if `formatter` is not None, it must be a callable transforming the
536 536 input text into a mime bundle. Default values for `text/plain` and
537 537 `text/html` representations are the ones described above.
538 538
539 539 Note:
540 540
541 541 Formatters returning strings are supported but this behavior is deprecated.
542 542
543 543 """
544 544 text = cast_unicode(text)
545 545 defaults = {
546 546 'text/plain': text,
547 547 'text/html': '<pre>' + text + '</pre>'
548 548 }
549 549
550 550 if formatter is None:
551 551 return defaults
552 552 else:
553 553 formatted = formatter(text)
554 554
555 555 if not isinstance(formatted, dict):
556 556 # Handle the deprecated behavior of a formatter returning
557 557 # a string instead of a mime bundle.
558 558 return {
559 559 'text/plain': formatted,
560 560 'text/html': '<pre>' + formatted + '</pre>'
561 561 }
562 562
563 563 else:
564 564 return dict(defaults, **formatted)
565 565
566 566
567 567 def format_mime(self, bundle):
568 568
569 569 text_plain = bundle['text/plain']
570 570
571 571 text = ''
572 572 heads, bodies = list(zip(*text_plain))
573 573 _len = max(len(h) for h in heads)
574 574
575 575 for head, body in zip(heads, bodies):
576 576 body = body.strip('\n')
577 577 delim = '\n' if '\n' in body else ' '
578 578 text += self.__head(head+':') + (_len - len(head))*' ' +delim + body +'\n'
579 579
580 580 bundle['text/plain'] = text
581 581 return bundle
582 582
583 583 def _get_info(self, obj, oname='', formatter=None, info=None, detail_level=0):
584 584 """Retrieve an info dict and format it.
585 585
586 586 Parameters
587 587 ==========
588 588
589 589 obj: any
590 590 Object to inspect and return info from
591 591 oname: str (default: ''):
592 592 Name of the variable pointing to `obj`.
593 593 formatter: callable
594 594 info:
595 595 already computed information
596 596 detail_level: integer
597 597 Granularity of detail level, if set to 1, give more information.
598 598 """
599 599
600 600 info = self._info(obj, oname=oname, info=info, detail_level=detail_level)
601 601
602 602 _mime = {
603 603 'text/plain': [],
604 604 'text/html': '',
605 605 }
606 606
607 607 def append_field(bundle, title, key, formatter=None):
608 608 field = info[key]
609 609 if field is not None:
610 610 formatted_field = self._mime_format(field, formatter)
611 611 bundle['text/plain'].append((title, formatted_field['text/plain']))
612 612 bundle['text/html'] += '<h1>' + title + '</h1>\n' + formatted_field['text/html'] + '\n'
613 613
614 614 def code_formatter(text):
615 615 return {
616 616 'text/plain': self.format(text),
617 617 'text/html': pylight(text)
618 618 }
619 619
620 620 if info['isalias']:
621 621 append_field(_mime, 'Repr', 'string_form')
622 622
623 623 elif info['ismagic']:
624 624 if detail_level > 0:
625 625 append_field(_mime, 'Source', 'source', code_formatter)
626 626 else:
627 627 append_field(_mime, 'Docstring', 'docstring', formatter)
628 628 append_field(_mime, 'File', 'file')
629 629
630 630 elif info['isclass'] or is_simple_callable(obj):
631 631 # Functions, methods, classes
632 632 append_field(_mime, 'Signature', 'definition', code_formatter)
633 633 append_field(_mime, 'Init signature', 'init_definition', code_formatter)
634 634 append_field(_mime, 'Docstring', 'docstring', formatter)
635 635 if detail_level > 0 and info['source']:
636 636 append_field(_mime, 'Source', 'source', code_formatter)
637 637 else:
638 638 append_field(_mime, 'Init docstring', 'init_docstring', formatter)
639 639
640 640 append_field(_mime, 'File', 'file')
641 641 append_field(_mime, 'Type', 'type_name')
642 642 append_field(_mime, 'Subclasses', 'subclasses')
643 643
644 644 else:
645 645 # General Python objects
646 646 append_field(_mime, 'Signature', 'definition', code_formatter)
647 647 append_field(_mime, 'Call signature', 'call_def', code_formatter)
648 648 append_field(_mime, 'Type', 'type_name')
649 649 append_field(_mime, 'String form', 'string_form')
650 650
651 651 # Namespace
652 652 if info['namespace'] != 'Interactive':
653 653 append_field(_mime, 'Namespace', 'namespace')
654 654
655 655 append_field(_mime, 'Length', 'length')
656 656 append_field(_mime, 'File', 'file')
657 657
658 658 # Source or docstring, depending on detail level and whether
659 659 # source found.
660 660 if detail_level > 0 and info['source']:
661 661 append_field(_mime, 'Source', 'source', code_formatter)
662 662 else:
663 663 append_field(_mime, 'Docstring', 'docstring', formatter)
664 664
665 665 append_field(_mime, 'Class docstring', 'class_docstring', formatter)
666 666 append_field(_mime, 'Init docstring', 'init_docstring', formatter)
667 667 append_field(_mime, 'Call docstring', 'call_docstring', formatter)
668 668
669 669
670 670 return self.format_mime(_mime)
671 671
672 672 def pinfo(self, obj, oname='', formatter=None, info=None, detail_level=0, enable_html_pager=True):
673 673 """Show detailed information about an object.
674 674
675 675 Optional arguments:
676 676
677 677 - oname: name of the variable pointing to the object.
678 678
679 679 - formatter: callable (optional)
680 680 A special formatter for docstrings.
681 681
682 682 The formatter is a callable that takes a string as an input
683 683 and returns either a formatted string or a mime type bundle
684 684 in the form of a dictionary.
685 685
686 686 Although the support of custom formatter returning a string
687 687 instead of a mime type bundle is deprecated.
688 688
689 689 - info: a structure with some information fields which may have been
690 690 precomputed already.
691 691
692 692 - detail_level: if set to 1, more information is given.
693 693 """
694 694 info = self._get_info(obj, oname, formatter, info, detail_level)
695 695 if not enable_html_pager:
696 696 del info['text/html']
697 697 page.page(info)
698 698
699 699 def info(self, obj, oname='', formatter=None, info=None, detail_level=0):
700 700 """DEPRECATED. Compute a dict with detailed information about an object.
701 701 """
702 702 if formatter is not None:
703 703 warnings.warn('The `formatter` keyword argument to `Inspector.info`'
704 704 'is deprecated as of IPython 5.0 and will have no effects.',
705 705 DeprecationWarning, stacklevel=2)
706 706 return self._info(obj, oname=oname, info=info, detail_level=detail_level)
707 707
708 708 def _info(self, obj, oname='', info=None, detail_level=0) -> dict:
709 709 """Compute a dict with detailed information about an object.
710 710
711 711 Parameters
712 712 ==========
713 713
714 714 obj: any
715 715 An object to find information about
716 716 oname: str (default: ''):
717 717 Name of the variable pointing to `obj`.
718 718 info: (default: None)
719 719 A struct (dict like with attr access) with some information fields
720 720 which may have been precomputed already.
721 721 detail_level: int (default:0)
722 722 If set to 1, more information is given.
723 723
724 724 Returns
725 725 =======
726 726
727 727 An object info dict with known fields from `info_fields`.
728 728 """
729 729
730 730 if info is None:
731 731 ismagic = False
732 732 isalias = False
733 733 ospace = ''
734 734 else:
735 735 ismagic = info.ismagic
736 736 isalias = info.isalias
737 737 ospace = info.namespace
738 738
739 739 # Get docstring, special-casing aliases:
740 740 if isalias:
741 741 if not callable(obj):
742 742 try:
743 743 ds = "Alias to the system command:\n %s" % obj[1]
744 744 except:
745 745 ds = "Alias: " + str(obj)
746 746 else:
747 747 ds = "Alias to " + str(obj)
748 748 if obj.__doc__:
749 749 ds += "\nDocstring:\n" + obj.__doc__
750 750 else:
751 751 ds = getdoc(obj)
752 752 if ds is None:
753 753 ds = '<no docstring>'
754 754
755 755 # store output in a dict, we initialize it here and fill it as we go
756 756 out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic, subclasses=None)
757 757
758 758 string_max = 200 # max size of strings to show (snipped if longer)
759 759 shalf = int((string_max - 5) / 2)
760 760
761 761 if ismagic:
762 762 out['type_name'] = 'Magic function'
763 763 elif isalias:
764 764 out['type_name'] = 'System alias'
765 765 else:
766 766 out['type_name'] = type(obj).__name__
767 767
768 768 try:
769 769 bclass = obj.__class__
770 770 out['base_class'] = str(bclass)
771 771 except:
772 772 pass
773 773
774 774 # String form, but snip if too long in ? form (full in ??)
775 775 if detail_level >= self.str_detail_level:
776 776 try:
777 777 ostr = str(obj)
778 778 str_head = 'string_form'
779 779 if not detail_level and len(ostr)>string_max:
780 780 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
781 781 ostr = ("\n" + " " * len(str_head.expandtabs())).\
782 782 join(q.strip() for q in ostr.split("\n"))
783 783 out[str_head] = ostr
784 784 except:
785 785 pass
786 786
787 787 if ospace:
788 788 out['namespace'] = ospace
789 789
790 790 # Length (for strings and lists)
791 791 try:
792 792 out['length'] = str(len(obj))
793 793 except Exception:
794 794 pass
795 795
796 796 # Filename where object was defined
797 797 binary_file = False
798 798 fname = find_file(obj)
799 799 if fname is None:
800 800 # if anything goes wrong, we don't want to show source, so it's as
801 801 # if the file was binary
802 802 binary_file = True
803 803 else:
804 804 if fname.endswith(('.so', '.dll', '.pyd')):
805 805 binary_file = True
806 806 elif fname.endswith('<string>'):
807 807 fname = 'Dynamically generated function. No source code available.'
808 808 out['file'] = compress_user(fname)
809 809
810 810 # Original source code for a callable, class or property.
811 811 if detail_level:
812 812 # Flush the source cache because inspect can return out-of-date
813 813 # source
814 814 linecache.checkcache()
815 815 try:
816 816 if isinstance(obj, property) or not binary_file:
817 817 src = getsource(obj, oname)
818 818 if src is not None:
819 819 src = src.rstrip()
820 820 out['source'] = src
821 821
822 822 except Exception:
823 823 pass
824 824
825 825 # Add docstring only if no source is to be shown (avoid repetitions).
826 826 if ds and not self._source_contains_docstring(out.get('source'), ds):
827 827 out['docstring'] = ds
828 828
829 829 # Constructor docstring for classes
830 830 if inspect.isclass(obj):
831 831 out['isclass'] = True
832 832
833 833 # get the init signature:
834 834 try:
835 835 init_def = self._getdef(obj, oname)
836 836 except AttributeError:
837 837 init_def = None
838 838
839 839 # get the __init__ docstring
840 840 try:
841 841 obj_init = obj.__init__
842 842 except AttributeError:
843 843 init_ds = None
844 844 else:
845 845 if init_def is None:
846 846 # Get signature from init if top-level sig failed.
847 847 # Can happen for built-in types (list, etc.).
848 848 try:
849 849 init_def = self._getdef(obj_init, oname)
850 850 except AttributeError:
851 851 pass
852 852 init_ds = getdoc(obj_init)
853 853 # Skip Python's auto-generated docstrings
854 854 if init_ds == _object_init_docstring:
855 855 init_ds = None
856 856
857 857 if init_def:
858 858 out['init_definition'] = init_def
859 859
860 860 if init_ds:
861 861 out['init_docstring'] = init_ds
862 862
863 863 names = [sub.__name__ for sub in obj.__subclasses__()]
864 all_names = ', '.join(names)
864 if len(names) < 10:
865 all_names = ', '.join(names)
866 else:
867 all_names = ', '.join(names[:10]+['...'])
865 868 out['subclasses'] = all_names
866 869 # and class docstring for instances:
867 870 else:
868 871 # reconstruct the function definition and print it:
869 872 defln = self._getdef(obj, oname)
870 873 if defln:
871 874 out['definition'] = defln
872 875
873 876 # First, check whether the instance docstring is identical to the
874 877 # class one, and print it separately if they don't coincide. In
875 878 # most cases they will, but it's nice to print all the info for
876 879 # objects which use instance-customized docstrings.
877 880 if ds:
878 881 try:
879 882 cls = getattr(obj,'__class__')
880 883 except:
881 884 class_ds = None
882 885 else:
883 886 class_ds = getdoc(cls)
884 887 # Skip Python's auto-generated docstrings
885 888 if class_ds in _builtin_type_docstrings:
886 889 class_ds = None
887 890 if class_ds and ds != class_ds:
888 891 out['class_docstring'] = class_ds
889 892
890 893 # Next, try to show constructor docstrings
891 894 try:
892 895 init_ds = getdoc(obj.__init__)
893 896 # Skip Python's auto-generated docstrings
894 897 if init_ds == _object_init_docstring:
895 898 init_ds = None
896 899 except AttributeError:
897 900 init_ds = None
898 901 if init_ds:
899 902 out['init_docstring'] = init_ds
900 903
901 904 # Call form docstring for callable instances
902 905 if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
903 906 call_def = self._getdef(obj.__call__, oname)
904 907 if call_def and (call_def != out.get('definition')):
905 908 # it may never be the case that call def and definition differ,
906 909 # but don't include the same signature twice
907 910 out['call_def'] = call_def
908 911 call_ds = getdoc(obj.__call__)
909 912 # Skip Python's auto-generated docstrings
910 913 if call_ds == _func_call_docstring:
911 914 call_ds = None
912 915 if call_ds:
913 916 out['call_docstring'] = call_ds
914 917
915 918 # Compute the object's argspec as a callable. The key is to decide
916 919 # whether to pull it from the object itself, from its __init__ or
917 920 # from its __call__ method.
918 921
919 922 if inspect.isclass(obj):
920 923 # Old-style classes need not have an __init__
921 924 callable_obj = getattr(obj, "__init__", None)
922 925 elif callable(obj):
923 926 callable_obj = obj
924 927 else:
925 928 callable_obj = None
926 929
927 930 if callable_obj is not None:
928 931 try:
929 932 argspec = getargspec(callable_obj)
930 933 except Exception:
931 934 # For extensions/builtins we can't retrieve the argspec
932 935 pass
933 936 else:
934 937 # named tuples' _asdict() method returns an OrderedDict, but we
935 938 # we want a normal
936 939 out['argspec'] = argspec_dict = dict(argspec._asdict())
937 940 # We called this varkw before argspec became a named tuple.
938 941 # With getfullargspec it's also called varkw.
939 942 if 'varkw' not in argspec_dict:
940 943 argspec_dict['varkw'] = argspec_dict.pop('keywords')
941 944
942 945 return object_info(**out)
943 946
944 947 @staticmethod
945 948 def _source_contains_docstring(src, doc):
946 949 """
947 950 Check whether the source *src* contains the docstring *doc*.
948 951
949 952 This is is helper function to skip displaying the docstring if the
950 953 source already contains it, avoiding repetition of information.
951 954 """
952 955 try:
953 956 def_node, = ast.parse(dedent(src)).body
954 957 return ast.get_docstring(def_node) == doc
955 958 except Exception:
956 959 # The source can become invalid or even non-existent (because it
957 960 # is re-fetched from the source file) so the above code fail in
958 961 # arbitrary ways.
959 962 return False
960 963
961 964 def psearch(self,pattern,ns_table,ns_search=[],
962 965 ignore_case=False,show_all=False):
963 966 """Search namespaces with wildcards for objects.
964 967
965 968 Arguments:
966 969
967 970 - pattern: string containing shell-like wildcards to use in namespace
968 971 searches and optionally a type specification to narrow the search to
969 972 objects of that type.
970 973
971 974 - ns_table: dict of name->namespaces for search.
972 975
973 976 Optional arguments:
974 977
975 978 - ns_search: list of namespace names to include in search.
976 979
977 980 - ignore_case(False): make the search case-insensitive.
978 981
979 982 - show_all(False): show all names, including those starting with
980 983 underscores.
981 984 """
982 985 #print 'ps pattern:<%r>' % pattern # dbg
983 986
984 987 # defaults
985 988 type_pattern = 'all'
986 989 filter = ''
987 990
988 991 cmds = pattern.split()
989 992 len_cmds = len(cmds)
990 993 if len_cmds == 1:
991 994 # Only filter pattern given
992 995 filter = cmds[0]
993 996 elif len_cmds == 2:
994 997 # Both filter and type specified
995 998 filter,type_pattern = cmds
996 999 else:
997 1000 raise ValueError('invalid argument string for psearch: <%s>' %
998 1001 pattern)
999 1002
1000 1003 # filter search namespaces
1001 1004 for name in ns_search:
1002 1005 if name not in ns_table:
1003 1006 raise ValueError('invalid namespace <%s>. Valid names: %s' %
1004 1007 (name,ns_table.keys()))
1005 1008
1006 1009 #print 'type_pattern:',type_pattern # dbg
1007 1010 search_result, namespaces_seen = set(), set()
1008 1011 for ns_name in ns_search:
1009 1012 ns = ns_table[ns_name]
1010 1013 # Normally, locals and globals are the same, so we just check one.
1011 1014 if id(ns) in namespaces_seen:
1012 1015 continue
1013 1016 namespaces_seen.add(id(ns))
1014 1017 tmp_res = list_namespace(ns, type_pattern, filter,
1015 1018 ignore_case=ignore_case, show_all=show_all)
1016 1019 search_result.update(tmp_res)
1017 1020
1018 1021 page.page('\n'.join(sorted(search_result)))
1019 1022
1020 1023
1021 1024 def _render_signature(obj_signature, obj_name):
1022 1025 """
1023 1026 This was mostly taken from inspect.Signature.__str__.
1024 1027 Look there for the comments.
1025 1028 The only change is to add linebreaks when this gets too long.
1026 1029 """
1027 1030 result = []
1028 1031 pos_only = False
1029 1032 kw_only = True
1030 1033 for param in obj_signature.parameters.values():
1031 1034 if param.kind == inspect._POSITIONAL_ONLY:
1032 1035 pos_only = True
1033 1036 elif pos_only:
1034 1037 result.append('/')
1035 1038 pos_only = False
1036 1039
1037 1040 if param.kind == inspect._VAR_POSITIONAL:
1038 1041 kw_only = False
1039 1042 elif param.kind == inspect._KEYWORD_ONLY and kw_only:
1040 1043 result.append('*')
1041 1044 kw_only = False
1042 1045
1043 1046 result.append(str(param))
1044 1047
1045 1048 if pos_only:
1046 1049 result.append('/')
1047 1050
1048 1051 # add up name, parameters, braces (2), and commas
1049 1052 if len(obj_name) + sum(len(r) + 2 for r in result) > 75:
1050 1053 # This doesn’t fit behind “Signature: ” in an inspect window.
1051 1054 rendered = '{}(\n{})'.format(obj_name, ''.join(' {},\n'.format(result)))
1052 1055 else:
1053 1056 rendered = '{}({})'.format(obj_name, ', '.join(result))
1054 1057
1055 1058 if obj_signature.return_annotation is not inspect._empty:
1056 1059 anno = inspect.formatannotation(obj_signature.return_annotation)
1057 1060 rendered += ' -> {}'.format(anno)
1058 1061
1059 1062 return rendered
@@ -1,354 +1,406 b''
1 1 ============
2 2 7.x Series
3 3 ============
4 4
5 .. _whatsnew720:
6
7 IPython 7.2.0
8 =============
9
10 IPython 7.2.0 bring minor fixes, improvement and new options.
11
12 - Fix a bug preventing to enable PySide2 gui integration :ghpull:`11464`
13 - Run CI on Mac OS ! :ghpull:`11471`
14 - Fix IPython "Demo" mode. :ghpull:`11498`
15 - Fix ``%run`` magic with path in name :ghpull:`11499`
16 - Fix: add CWD to sys.path *after* stdlib :ghpull:`11502`
17 - Better rendering of signatures, especially long ones. :ghpull:`11505`
18 - Re enable jedi by default if installed :ghpull:`11506`
19 - Add New ``minimal`` exception reporting mode (useful for educational purpose). See :ghpull:`11509`
20
21
22 Added ability to show subclasses when using pinfo and other utilities
23 ---------------------------------------------------------------------
24
25 When using ``?``/``??`` on a class, IPython will now list the first 10 subclasses.
26
27 Special Thanks to Chris Mentzel of the Moore Foundation for this feature, Chris
28 is one of the people who played a critical role in IPython/Jupyter getting
29 funding.
30
31 We are grateful for all the help Chris gave us through the years, We are now
32 proud to have code contributed by Chris in IPython.
33
34 OSMagics.cd_force_quiet configuration option
35 --------------------------------------------
36
37 You can set this option to force the %cd magic to behave as if ``-q`` was passed:
38 ::
39
40 In [1]: cd /
41 /
42
43 In [2]: %config OSMagics.cd_force_quiet = True
44
45 In [3]: cd /tmp
46
47 In [4]:
48
49 See :ghpull:`11491`
50
51 In vi editing mode, whether the prompt includes the current vi mode can now be configured
52 -----------------------------------------------------------------------------------------
53
54 Set the ``TerminalInteractiveShell.prompt_includes_vi_mode`` to a boolean value
55 (default: True) to control this feature. See :ghpull:`11492`
56
5 57 .. _whatsnew710:
6 58
7 59 IPython 7.1.0
8 60 =============
9 61
10 62 IPython 7.1.0 is the first minor release after 7.0.0 and mostly bring fixes to
11 63 new feature, internal refactor and regressions that happen during the 6.x->7.x
12 64 transition. It also bring **Compatibility with Python 3.7.1**, as were
13 65 unwillingly relying on a bug in CPython.
14 66
15 67 New Core Dev:
16 68
17 69 - We welcome Jonathan Slenders to the commiters. Jonathan has done a fantastic
18 70 work on Prompt toolkit, and we'd like to recognise his impact by giving him
19 71 commit rights. :ghissue:`11397`
20 72
21 73 Notables Changes
22 74
23 75 - Major update of "latex to unicode" tab completion map (see below)
24 76
25 77 Notable New Features:
26 78
27 79 - Restore functionality and documentation of the **sphinx directive**, which
28 80 is now stricter (fail on error by default), gained configuration options,
29 81 have a brand new documentation page :ref:`ipython_directive`, which need
30 82 some cleanup. It is also now *tested* so we hope to have less regressions.
31 83 :ghpull:`11402`
32 84
33 85 - ``IPython.display.Video`` now supports ``width`` and ``height`` arguments,
34 86 allowing a custom width and height to be set instead of using the video's
35 87 width and height. :ghpull:`11353`
36 88
37 89 - Warn when using ``HTML('<iframe>')`` instead of ``IFrame`` :ghpull:`11350`
38 90
39 91 - Allow Dynamic switching of editing mode between vi/emacs and show
40 92 normal/input mode in prompt when using vi. :ghpull:`11390`. Use ``%config
41 93 TerminalInteractiveShell.editing_mode = 'vi'`` or ``%config
42 94 TerminalInteractiveShell.editing_mode = 'emacs'`` to dynamically spwitch
43 95
44 96
45 97 Notable Fixes:
46 98
47 99 - Fix entering of **multi-line block in terminal** IPython, and various
48 100 crashes in the new input transformation machinery :ghpull:`11354`,
49 101 :ghpull:`11356`, :ghpull:`11358`, these ones also fix a **Compatibility but
50 102 with Python 3.7.1**.
51 103
52 104 - Fix moving through generator stack in ipdb :ghpull:`11266`
53 105
54 106 - Magics arguments now support quoting. :ghpull:`11330`
55 107
56 108 - Re-add ``rprint`` and ``rprinte`` aliases. :ghpull:`11331`
57 109
58 110 - Remove implicit dependency to ``ipython_genutils`` :ghpull:`11317`
59 111
60 112 - Make ``nonlocal`` raise ``SyntaxError`` instead of silently failing in async
61 113 mode. :ghpull:`11382`
62 114
63 115 - Fix mishandling of magics and ``= !`` assignment just after a dedent in
64 116 nested code blocks :ghpull:`11418`
65 117
66 118 - Fix instructions for custom shortcuts :ghpull:`11426`
67 119
68 120
69 121 Notable Internals improvements:
70 122
71 123 - Use of ``os.scandir`` (Python 3 only) to speedup some file system operations.
72 124 :ghpull:`11365`
73 125
74 126 - use ``perf_counter`` instead of ``clock`` for more precise
75 127 timing result with ``%time`` :ghpull:`11376`
76 128
77 129 Many thanks to all the contributors and in particular to ``bartskowron``, and
78 130 ``tonyfast`` who handled a pretty complicated bugs in the input machinery. We
79 131 had a number of first time contributors and maybe hacktoberfest participant that
80 132 made significant contributions, and helped us free some time to focus on more
81 133 complicated bugs.
82 134
83 135 You
84 136 can see all the closed issues and Merged PR, new features and fixes `here
85 137 <https://github.com/ipython/ipython/issues?utf8=%E2%9C%93&q=+is%3Aclosed+milestone%3A7.1+>`_.
86 138
87 139 Unicode Completion update
88 140 -------------------------
89 141
90 142 In IPython 7.1 the Unicode completion map has been updated and synchronized with
91 143 the Julia language.
92 144
93 145 Added and removed character characters:
94 146
95 147 ``\jmath`` (``ȷ``), ``\\underleftrightarrow`` (U+034D, combining) have been
96 148 added, while ``\\textasciicaron`` have been removed
97 149
98 150 Some sequence have seen their prefix removed:
99 151
100 152 - 6 characters ``\text...<tab>`` should now be inputed with ``\...<tab>`` directly,
101 153 - 45 characters ``\Elz...<tab>`` should now be inputed with ``\...<tab>`` directly,
102 154 - 65 characters ``\B...<tab>`` should now be inputed with ``\...<tab>`` directly,
103 155 - 450 characters ``\m...<tab>`` should now be inputed with ``\...<tab>`` directly,
104 156
105 157 Some sequence have seen their prefix shortened:
106 158
107 159 - 5 characters ``\mitBbb...<tab>`` should now be inputed with ``\bbi...<tab>`` directly,
108 160 - 52 characters ``\mit...<tab>`` should now be inputed with ``\i...<tab>`` directly,
109 161 - 216 characters ``\mbfit...<tab>`` should now be inputed with ``\bi...<tab>`` directly,
110 162 - 222 characters ``\mbf...<tab>`` should now be inputed with ``\b...<tab>`` directly,
111 163
112 164 A couple of character had their sequence simplified:
113 165
114 166 - ``ð``, type ``\dh<tab>``, instead of ``\eth<tab>``
115 167 - ``ħ``, type ``\hbar<tab>``, instead of ``\Elzxh<tab>``
116 168 - ``ɸ``, type ``\ltphi<tab>``, instead of ``\textphi<tab>``
117 169 - ``ϴ``, type ``\varTheta<tab>``, instead of ``\textTheta<tab>``
118 170 - ``ℇ``, type ``\eulermascheroni<tab>``, instead of ``\Eulerconst<tab>``
119 171 - ``ℎ``, type ``\planck<tab>``, instead of ``\Planckconst<tab>``
120 172
121 173 - U+0336 (COMBINING LONG STROKE OVERLAY), type ``\strike<tab>``, instead of ``\Elzbar<tab>``.
122 174
123 175 A couple of sequences have been updated:
124 176
125 177 - ``\varepsilon`` now give ``ɛ`` (GREEK SMALL LETTER EPSILON) instead of ``ε`` (GREEK LUNATE EPSILON SYMBOL),
126 178 - ``\underbar`` now give U+0331 (COMBINING MACRON BELOW) instead of U+0332 (COMBINING LOW LINE).
127 179
128 180
129 181 .. _whatsnew700:
130 182
131 183 IPython 7.0.0
132 184 =============
133 185
134 186 Released Thursday September 27th, 2018
135 187
136 188 IPython 7 include major features improvement as you can read in the following
137 189 changelog. This is also the second major version of IPython to support only
138 190 Python 3 – starting at Python 3.4. Python 2 is still community supported
139 191 on the bugfix only 5.x branch, but we remind you that Python 2 "end of life"
140 192 is on Jan 1st 2020.
141 193
142 194 We were able to backport bug fixes to the 5.x branch thanks to our backport bot which
143 195 backported more than `70 Pull-Requests
144 196 <https://github.com/ipython/ipython/pulls?page=3&q=is%3Apr+sort%3Aupdated-desc+author%3Aapp%2Fmeeseeksdev++5.x&utf8=%E2%9C%93>`_, but there are still many PRs that required manually work, and this is an area of the project were you can easily contribute by looking for `PRs still needed backport <https://github.com/ipython/ipython/issues?q=label%3A%22Still+Needs+Manual+Backport%22+is%3Aclosed+sort%3Aupdated-desc>`_
145 197
146 198 IPython 6.x branch will likely not see any further release unless critical
147 199 bugs are found.
148 200
149 201 Make sure you have pip > 9.0 before upgrading. You should be able to update by simply running
150 202
151 203 .. code::
152 204
153 205 pip install ipython --upgrade
154 206
155 207 .. only:: ipydev
156 208
157 209 If you are trying to install or update an ``alpha``, ``beta``, or ``rc``
158 210 version, use pip ``--pre`` flag.
159 211
160 212 .. code::
161 213
162 214 pip install ipython --upgrade --pre
163 215
164 216
165 217 Or if you have conda installed:
166 218
167 219 .. code::
168 220
169 221 conda install ipython
170 222
171 223
172 224
173 225 Prompt Toolkit 2.0
174 226 ------------------
175 227
176 228 IPython 7.0+ now uses ``prompt_toolkit 2.0``, if you still need to use earlier
177 229 ``prompt_toolkit`` version you may need to pin IPython to ``<7.0``.
178 230
179 231 Autowait: Asynchronous REPL
180 232 ---------------------------
181 233
182 234 Staring with IPython 7.0 and on Python 3.6+, IPython can automatically await
183 235 code at top level, you should not need to access an event loop or runner
184 236 yourself. To know more read the :ref:`autoawait` section of our docs, see
185 237 :ghpull:`11265` or try the following code::
186 238
187 239 Python 3.6.0
188 240 Type 'copyright', 'credits' or 'license' for more information
189 241 IPython 7.0.0 -- An enhanced Interactive Python. Type '?' for help.
190 242
191 243 In [1]: import aiohttp
192 244 ...: result = aiohttp.get('https://api.github.com')
193 245
194 246 In [2]: response = await result
195 247 <pause for a few 100s ms>
196 248
197 249 In [3]: await response.json()
198 250 Out[3]:
199 251 {'authorizations_url': 'https://api.github.com/authorizations',
200 252 'code_search_url': 'https://api.github.com/search/code?q={query}{&page,per_page,sort,order}',
201 253 ...
202 254 }
203 255
204 256 .. note::
205 257
206 258 Async integration is experimental code, behavior may change or be removed
207 259 between Python and IPython versions without warnings.
208 260
209 261 Integration is by default with `asyncio`, but other libraries can be configured,
210 262 like ``curio`` or ``trio``, to improve concurrency in the REPL::
211 263
212 264 In [1]: %autoawait trio
213 265
214 266 In [2]: import trio
215 267
216 268 In [3]: async def child(i):
217 269 ...: print(" child %s goes to sleep"%i)
218 270 ...: await trio.sleep(2)
219 271 ...: print(" child %s wakes up"%i)
220 272
221 273 In [4]: print('parent start')
222 274 ...: async with trio.open_nursery() as n:
223 275 ...: for i in range(3):
224 276 ...: n.spawn(child, i)
225 277 ...: print('parent end')
226 278 parent start
227 279 child 2 goes to sleep
228 280 child 0 goes to sleep
229 281 child 1 goes to sleep
230 282 <about 2 seconds pause>
231 283 child 2 wakes up
232 284 child 1 wakes up
233 285 child 0 wakes up
234 286 parent end
235 287
236 288 See :ref:`autoawait` for more information.
237 289
238 290
239 291 Asynchronous code in a Notebook interface or any other frontend using the
240 292 Jupyter Protocol will need further updates of the IPykernel package.
241 293
242 294 Non-Asynchronous code
243 295 ~~~~~~~~~~~~~~~~~~~~~
244 296
245 297 As the internal API of IPython is now asynchronous, IPython needs to run under
246 298 an event loop. In order to allow many workflows, (like using the :magic:`%run`
247 299 magic, or copy_pasting code that explicitly starts/stop event loop), when
248 300 top-level code is detected as not being asynchronous, IPython code is advanced
249 301 via a pseudo-synchronous runner, and may not advance pending tasks.
250 302
251 303 Change to Nested Embed
252 304 ~~~~~~~~~~~~~~~~~~~~~~
253 305
254 306 The introduction of the ability to run async code had some effect on the
255 307 ``IPython.embed()`` API. By default embed will not allow you to run asynchronous
256 308 code unless a event loop is specified.
257 309
258 310 Effects on Magics
259 311 ~~~~~~~~~~~~~~~~~
260 312
261 313 Some magics will not work with Async, and will need updates. Contribution
262 314 welcome.
263 315
264 316 Expected Future changes
265 317 ~~~~~~~~~~~~~~~~~~~~~~~
266 318
267 319 We expect more internal but public IPython function to become ``async``, and
268 320 will likely end up having a persisting event loop while IPython is running.
269 321
270 322 Thanks
271 323 ~~~~~~
272 324
273 325 This took more than a year in the making, and the code was rebased a number of
274 326 time leading to commit authorship that may have been lost in the final
275 327 Pull-Request. Huge thanks to many people for contribution, discussion, code,
276 328 documentation, use-case: dalejung, danielballan, ellisonbg, fperez, gnestor,
277 329 minrk, njsmith, pganssle, tacaswell, takluyver , vidartf ... And many others.
278 330
279 331
280 332 Autoreload Improvement
281 333 ----------------------
282 334
283 335 The magic :magic:`%autoreload 2 <autoreload>` now captures new methods added to
284 336 classes. Earlier, only methods existing as of the initial import were being
285 337 tracked and updated.
286 338
287 339 This new feature helps dual environment development - Jupyter+IDE - where the
288 340 code gradually moves from notebook cells to package files, as it gets
289 341 structured.
290 342
291 343 **Example**: An instance of the class ``MyClass`` will be able to access the
292 344 method ``cube()`` after it is uncommented and the file ``file1.py`` saved on
293 345 disk.
294 346
295 347
296 348 .. code::
297 349
298 350 # notebook
299 351
300 352 from mymodule import MyClass
301 353 first = MyClass(5)
302 354
303 355 .. code::
304 356
305 357 # mymodule/file1.py
306 358
307 359 class MyClass:
308 360
309 361 def __init__(self, a=10):
310 362 self.a = a
311 363
312 364 def square(self):
313 365 print('compute square')
314 366 return self.a*self.a
315 367
316 368 # def cube(self):
317 369 # print('compute cube')
318 370 # return self.a*self.a*self.a
319 371
320 372
321 373
322 374
323 375 Misc
324 376 ----
325 377
326 378 The autoindent feature that was deprecated in 5.x was re-enabled and
327 379 un-deprecated in :ghpull:`11257`
328 380
329 381 Make :magic:`%run -n -i ... <run>` work correctly. Earlier, if :magic:`%run` was
330 382 passed both arguments, ``-n`` would be silently ignored. See :ghpull:`10308`
331 383
332 384
333 385 The :cellmagic:`%%script` (as well as :cellmagic:`%%bash`,
334 386 :cellmagic:`%%ruby`... ) cell magics now raise by default if the return code of
335 387 the given code is non-zero (thus halting execution of further cells in a
336 388 notebook). The behavior can be disable by passing the ``--no-raise-error`` flag.
337 389
338 390
339 391 Deprecations
340 392 ------------
341 393
342 394 A couple of unused function and methods have been deprecated and will be removed
343 395 in future versions:
344 396
345 397 - ``IPython.utils.io.raw_print_err``
346 398 - ``IPython.utils.io.raw_print``
347 399
348 400
349 401 Backwards incompatible changes
350 402 ------------------------------
351 403
352 404 * The API for transforming input before it is parsed as Python code has been
353 405 completely redesigned, and any custom input transformations will need to be
354 406 rewritten. See :doc:`/config/inputtransforms` for details of the new API.
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now