Debian Codegraph @

IPython/extensions/autoreload.py

raw
1 """IPython extension to reload modules before executing user code.
2
3 ``autoreload`` reloads modules automatically before entering the execution of
4 code typed at the IPython prompt.
5
6 This makes for example the following workflow possible:
7
8 .. sourcecode:: ipython
9
10 In [1]: %load_ext autoreload
11
12 In [2]: %autoreload 2
13
14 In [3]: from foo import some_function
15
16 In [4]: some_function()
17 Out[4]: 42
18
19 In [5]: # open foo.py in an editor and change some_function to return 43
20
21 In [6]: some_function()
22 Out[6]: 43
23
24 The module was reloaded without reloading it explicitly, and the object
25 imported with ``from foo import ...`` was also updated.
26
27 Usage
28 =====
29
30 The following magic commands are provided:
31
32 ``%autoreload``, ``%autoreload now``
33
34 Reload all modules (except those excluded by ``%aimport``)
35 automatically now.
36
37 ``%autoreload 0``, ``%autoreload off``
38
39 Disable automatic reloading.
40
41 ``%autoreload 1``, ``%autoreload explicit``
42
43 Reload all modules imported with ``%aimport`` every time before
44 executing the Python code typed.
45
46 ``%autoreload 2``, ``%autoreload all``
47
48 Reload all modules (except those excluded by ``%aimport``) every
49 time before executing the Python code typed.
50
51 ``%autoreload 3``, ``%autoreload complete``
52
53 Same as 2/all, but also adds any new objects in the module. See
54 unit test at IPython/extensions/tests/test_autoreload.py::test_autoload_newly_added_objects
55
56 Adding ``--print`` or ``-p`` to the ``%autoreload`` line will print autoreload activity to
57 standard out. ``--log`` or ``-l`` will do it to the log at INFO level; both can be used
58 simultaneously.
59
60 ``%aimport``
61
62 List modules which are to be automatically imported or not to be imported.
63
64 ``%aimport foo``
65
66 Import module 'foo' and mark it to be autoreloaded for ``%autoreload 1``
67
68 ``%aimport foo, bar``
69
70 Import modules 'foo', 'bar' and mark them to be autoreloaded for ``%autoreload 1``
71
72 ``%aimport -foo``
73
74 Mark module 'foo' to not be autoreloaded.
75
76 Import Conflict Resolution
77 ==========================
78
79 In ``%autoreload 3`` mode, the extension tracks ``from X import Y`` style imports
80 and intelligently resolves conflicts when the same name is imported multiple ways.
81
82 Import tracking occurs after successful code execution, ensuring that only valid
83 imports are tracked. This approach handles edge cases such as:
84
85 - Importing a name that doesn't initially exist in a module, then adding that name
86 to the module and importing it again
87 - Conflicts between aliased imports (``from X import Y as Z``) and direct imports
88 (``from X import Z``)
89
90 When conflicts occur:
91
92 - If you first do ``from X import Y as Z`` then later ``from X import Z``,
93 the extension will switch to reloading ``Z`` instead of ``Y`` under the name ``Z``.
94
95 - Similarly, if you first do ``from X import Z`` then later ``from X import Y as Z``,
96 the extension will switch to reloading ``Y`` as ``Z`` instead of the original ``Z``.
97
98 - The most recent successful import always takes precedence in conflict resolution.
99
100 Caveats
101 =======
102
103 Reloading Python modules in a reliable way is in general difficult,
104 and unexpected things may occur. ``%autoreload`` tries to work around
105 common pitfalls by replacing function code objects and parts of
106 classes previously in the module with new versions. This makes the
107 following things to work:
108
109 - Functions and classes imported via 'from xxx import foo' are upgraded
110 to new versions when 'xxx' is reloaded.
111
112 - Methods and properties of classes are upgraded on reload, so that
113 calling 'c.foo()' on an object 'c' created before the reload causes
114 the new code for 'foo' to be executed.
115
116 Some of the known remaining caveats are:
117
118 - Replacing code objects does not always succeed: changing a @property
119 in a class to an ordinary method or a method to a member variable
120 can cause problems (but in old objects only).
121
122 - Functions that are removed (eg. via monkey-patching) from a module
123 before it is reloaded are not upgraded.
124
125 - C extension modules cannot be reloaded, and so cannot be autoreloaded.
126
127 - While comparing Enum and Flag, the 'is' Identity Operator is used (even in the case '==' has been used (Similar to the 'None' keyword)).
128
129 - Reloading a module, or importing the same module by a different name, creates new Enums. These may look the same, but are not.
130 """
131
132 from IPython.core import magic_arguments
133 from IPython.core.magic import Magics, magics_class, line_magic
134 from IPython.extensions.deduperreload.deduperreload import DeduperReloader
135
136 __skip_doctest__ = True
137
138 # -----------------------------------------------------------------------------
139 # Copyright (C) 2000 Thomas Heller
140 # Copyright (C) 2008 Pauli Virtanen <[email protected]>
141 # Copyright (C) 2012 The IPython Development Team
142 #
143 # Distributed under the terms of the BSD License. The full license is in
144 # the file COPYING, distributed as part of this software.
145 # -----------------------------------------------------------------------------
146 #
147 # This IPython module is written by Pauli Virtanen, based on the autoreload
148 # code by Thomas Heller.
149
150 # -----------------------------------------------------------------------------
151 # Imports
152 # -----------------------------------------------------------------------------
153
154 import ast
155 import os
156 import sys
157 import traceback
158 import types
159 import weakref
160 import gc
161 import logging
162 from importlib import import_module, reload
163 from importlib.util import source_from_cache
164
165 # ------------------------------------------------------------------------------
166 # Autoreload functionality
167 # ------------------------------------------------------------------------------
168
169
170 class ModuleReloader:
171 enabled = False
172 """Whether this reloader is enabled"""
173
174 check_all = True
175 """Autoreload all modules, not just those listed in 'modules'"""
176
177 autoload_obj = False
178 """Autoreload all modules AND autoload all new objects"""
179
180 def __init__(self, shell=None):
181 # Modules that failed to reload: {module: mtime-on-failed-reload, ...}
182 self.failed = {}
183 # Modules specially marked as autoreloadable.
184 self.modules = {}
185 # Modules specially marked as not autoreloadable.
186 self.skip_modules = {}
187 # (module-name, name) -> weakref, for replacing old code objects
188 self.old_objects = {}
189 # Module modification timestamps
190 self.modules_mtimes = {}
191 self.shell = shell
192
193 # Reporting callable for verbosity
194 self._report = lambda msg: None # by default, be quiet.
195
196 # Deduper reloader
197 self.deduper_reloader = DeduperReloader()
198
199 # Persistent import tracker for from-imports
200 self.import_from_tracker = ImportFromTracker({}, {})
201
202 # Cache module modification times
203 self.check(check_all=True, do_reload=False)
204
205 # To hide autoreload errors
206 self.hide_errors = False
207
208 def mark_module_skipped(self, module_name):
209 """Skip reloading the named module in the future"""
210 try:
211 del self.modules[module_name]
212 except KeyError:
213 pass
214 self.skip_modules[module_name] = True
215
216 def mark_module_reloadable(self, module_name):
217 """Reload the named module in the future (if it is imported)"""
218 try:
219 del self.skip_modules[module_name]
220 except KeyError:
221 pass
222 self.modules[module_name] = True
223
224 def clear_import_tracker(self):
225 """Clear the persistent import tracker state"""
226 self.import_from_tracker = ImportFromTracker({}, {})
227
228 def aimport_module(self, module_name):
229 """Import a module, and mark it reloadable
230
231 Returns
232 -------
233 top_module : module
234 The imported module if it is top-level, or the top-level
235 top_name : module
236 Name of top_module
237
238 """
239 self.mark_module_reloadable(module_name)
240
241 import_module(module_name)
242 top_name = module_name.split(".")[0]
243 top_module = sys.modules[top_name]
244 return top_module, top_name
245
246 def filename_and_mtime(self, module):
247 if not hasattr(module, "__file__") or module.__file__ is None:
248 return None, None
249
250 if getattr(module, "__name__", None) in [None, "__mp_main__", "__main__"]:
251 # we cannot reload(__main__) or reload(__mp_main__)
252 return None, None
253
254 filename = module.__file__
255 path, ext = os.path.splitext(filename)
256
257 if ext.lower() == ".py":
258 py_filename = filename
259 else:
260 try:
261 py_filename = source_from_cache(filename)
262 except ValueError:
263 return None, None
264
265 try:
266 pymtime = os.stat(py_filename).st_mtime
267 except OSError:
268 return None, None
269
270 return py_filename, pymtime
271
272 def check(self, check_all=False, do_reload=True, execution_info=None):
273 """Check whether some modules need to be reloaded."""
274
275 if not self.enabled and not check_all:
276 return
277
278 if check_all or self.check_all:
279 modules = list(sys.modules.keys())
280 else:
281 modules = list(self.modules.keys())
282
283 # Use the persistent import_from_tracker
284 import_from_tracker = (
285 self.import_from_tracker if self.import_from_tracker.imports_froms else None
286 )
287 for modname in modules:
288 m = sys.modules.get(modname, None)
289
290 if modname in self.skip_modules:
291 continue
292
293 py_filename, pymtime = self.filename_and_mtime(m)
294 if py_filename is None:
295 continue
296
297 try:
298 if pymtime <= self.modules_mtimes[modname]:
299 continue
300 except KeyError:
301 self.modules_mtimes[modname] = pymtime
302 continue
303 else:
304 if self.failed.get(py_filename, None) == pymtime:
305 continue
306
307 self.modules_mtimes[modname] = pymtime
308
309 # If we've reached this point, we should try to reload the module
310 if do_reload:
311 self._report(f"Reloading '{modname}'.")
312 try:
313 if self.autoload_obj:
314 superreload(
315 m,
316 reload,
317 self.old_objects,
318 self.shell,
319 import_from_tracker=import_from_tracker,
320 )
321 # if not using autoload, check if deduperreload is viable for this module
322 elif self.deduper_reloader.maybe_reload_module(m):
323 pass
324 else:
325 superreload(m, reload, self.old_objects)
326 if py_filename in self.failed:
327 del self.failed[py_filename]
328 except:
329 if not self.hide_errors:
330 logger = logging.getLogger("autoreload")
331 logger.exception(
332 f"Failed to reload module '{modname}' from file '{py_filename}'"
333 )
334 print(
335 "[autoreload of {} failed: {}]".format(
336 modname, traceback.format_exc(10)
337 ),
338 file=sys.stderr,
339 )
340 self.failed[py_filename] = pymtime
341 self.deduper_reloader.update_sources()
342
343
344 # ------------------------------------------------------------------------------
345 # superreload
346 # ------------------------------------------------------------------------------
347
348
349 func_attrs = [
350 "__code__",
351 "__defaults__",
352 "__doc__",
353 "__closure__",
354 "__globals__",
355 "__dict__",
356 ]
357
358
359 def update_function(old, new):
360 """Upgrade the code object of a function"""
361 for name in func_attrs:
362 try:
363 setattr(old, name, getattr(new, name))
364 except (AttributeError, TypeError):
365 pass
366
367
368 def update_instances(old, new):
369 """Use garbage collector to find all instances that refer to the old
370 class definition and update their __class__ to point to the new class
371 definition"""
372
373 refs = gc.get_referrers(old)
374
375 for ref in refs:
376 if type(ref) is old:
377 object.__setattr__(ref, "__class__", new)
378
379
380 def update_class(old, new):
381 """Replace stuff in the __dict__ of a class, and upgrade
382 method code objects, and add new methods, if any"""
383 for key in list(old.__dict__.keys()):
384 old_obj = getattr(old, key)
385 try:
386 new_obj = getattr(new, key)
387 # explicitly checking that comparison returns True to handle
388 # cases where `==` doesn't return a boolean.
389 if (old_obj == new_obj) is True:
390 continue
391 except AttributeError:
392 # obsolete attribute: remove it
393 try:
394 delattr(old, key)
395 except (AttributeError, TypeError):
396 pass
397 continue
398 except ValueError:
399 # can't compare nested structures containing
400 # numpy arrays using `==`
401 pass
402
403 if update_generic(old_obj, new_obj):
404 continue
405
406 try:
407 setattr(old, key, getattr(new, key))
408 except (AttributeError, TypeError):
409 pass # skip non-writable attributes
410
411 for key in list(new.__dict__.keys()):
412 if key not in list(old.__dict__.keys()):
413 try:
414 setattr(old, key, getattr(new, key))
415 except (AttributeError, TypeError):
416 pass # skip non-writable attributes
417
418 # update all instances of class
419 update_instances(old, new)
420
421
422 def update_property(old, new):
423 """Replace get/set/del functions of a property"""
424 update_generic(old.fdel, new.fdel)
425 update_generic(old.fget, new.fget)
426 update_generic(old.fset, new.fset)
427
428
429 def isinstance2(a, b, typ):
430 return isinstance(a, typ) and isinstance(b, typ)
431
432
433 UPDATE_RULES = [
434 (lambda a, b: isinstance2(a, b, type), update_class),
435 (lambda a, b: isinstance2(a, b, types.FunctionType), update_function),
436 (lambda a, b: isinstance2(a, b, property), update_property),
437 ]
438 UPDATE_RULES.extend(
439 [
440 (
441 lambda a, b: isinstance2(a, b, types.MethodType),
442 lambda a, b: update_function(a.__func__, b.__func__),
443 ),
444 ]
445 )
446
447
448 def update_generic(a, b):
449 for type_check, update in UPDATE_RULES:
450 if type_check(a, b):
451 update(a, b)
452 return True
453 return False
454
455
456 class StrongRef:
457 def __init__(self, obj):
458 self.obj = obj
459
460 def __call__(self):
461 return self.obj
462
463
464 mod_attrs = [
465 "__name__",
466 "__doc__",
467 "__package__",
468 "__loader__",
469 "__spec__",
470 "__file__",
471 "__cached__",
472 "__builtins__",
473 ]
474
475
476 class ImportFromTracker:
477 def __init__(self, imports_froms: dict, symbol_map: dict):
478 self.imports_froms = imports_froms
479 # symbol_map maps original_name -> list of resolved_names
480 self.symbol_map = {}
481 if symbol_map:
482 for module_name, mappings in symbol_map.items():
483 self.symbol_map[module_name] = {}
484 for original_name, resolved_names in mappings.items():
485 if isinstance(resolved_names, list):
486 self.symbol_map[module_name][original_name] = resolved_names[:]
487 else:
488 self.symbol_map[module_name][original_name] = [resolved_names]
489 else:
490 self.symbol_map = symbol_map or {}
491
492 def add_import(
493 self, module_name: str, original_name: str, resolved_name: str
494 ) -> None:
495 """Add an import, handling conflicts with existing imports.
496
497 This method is called after successful code execution, so we know the import is valid.
498 """
499 if module_name not in self.imports_froms:
500 self.imports_froms[module_name] = []
501 if module_name not in self.symbol_map:
502 self.symbol_map[module_name] = {}
503
504 # Check if there's already a different mapping for the same resolved_name from a different original_name
505 # We need to remove any conflicting mappings
506 for orig_name, res_names in list(self.symbol_map[module_name].items()):
507 if resolved_name in res_names and orig_name != original_name:
508 # Remove the conflicting resolved_name from the other original_name's list
509 res_names.remove(resolved_name)
510 if (
511 not res_names
512 ): # If the list is now empty, remove the original_name entirely
513 if orig_name in self.imports_froms[module_name]:
514 self.imports_froms[module_name].remove(orig_name)
515 del self.symbol_map[module_name][orig_name]
516
517 # Add the new mapping
518 if original_name not in self.imports_froms[module_name]:
519 self.imports_froms[module_name].append(original_name)
520
521 if original_name not in self.symbol_map[module_name]:
522 self.symbol_map[module_name][original_name] = []
523
524 # Add the resolved_name if it's not already in the list
525 if resolved_name not in self.symbol_map[module_name][original_name]:
526 self.symbol_map[module_name][original_name].append(resolved_name)
527
528
529 def append_obj(module, d, name, obj, autoload=False):
530 in_module = hasattr(obj, "__module__") and obj.__module__ == module.__name__
531 if autoload:
532 # check needed for module global built-ins
533 if not in_module and name in mod_attrs:
534 return False
535 else:
536 if not in_module:
537 return False
538
539 key = (module.__name__, name)
540 try:
541 d.setdefault(key, []).append(weakref.ref(obj))
542 except TypeError:
543 pass
544 return True
545
546
547 def superreload(
548 module, reload=reload, old_objects=None, shell=None, import_from_tracker=None
549 ):
550 """Enhanced version of the builtin reload function.
551
552 superreload remembers objects previously in the module, and
553
554 - upgrades the class dictionary of every old class in the module
555 - upgrades the code object of every old function and method
556 - clears the module's namespace before reloading
557
558 """
559 if old_objects is None:
560 old_objects = {}
561
562 # collect old objects in the module
563 for name, obj in list(module.__dict__.items()):
564 if not append_obj(module, old_objects, name, obj):
565 continue
566 key = (module.__name__, name)
567 try:
568 old_objects.setdefault(key, []).append(weakref.ref(obj))
569 except TypeError:
570 pass
571
572 # reload module
573 try:
574 # clear namespace first from old cruft
575 old_dict = module.__dict__.copy()
576 old_name = module.__name__
577 module.__dict__.clear()
578 module.__dict__["__name__"] = old_name
579 module.__dict__["__loader__"] = old_dict["__loader__"]
580 except (TypeError, AttributeError, KeyError):
581 pass
582
583 try:
584 module = reload(module)
585 except:
586 # restore module dictionary on failed reload
587 module.__dict__.update(old_dict)
588 raise
589
590 for name, new_obj in list(module.__dict__.items()):
591 key = (module.__name__, name)
592 if key not in old_objects:
593 # here 'shell' acts both as a flag and as an output var
594 imports_froms = (
595 import_from_tracker.imports_froms if import_from_tracker else None
596 )
597 symbol_map = import_from_tracker.symbol_map if import_from_tracker else None
598 if (
599 shell is None
600 or name == "Enum"
601 or not append_obj(module, old_objects, name, new_obj, True)
602 or (
603 imports_froms
604 and module.__name__ in imports_froms
605 and "*" not in imports_froms[module.__name__]
606 and name not in imports_froms[module.__name__]
607 )
608 ):
609 continue
610
611 # Handle symbol mapping - now supporting multiple resolved names per original name
612 if symbol_map and name in symbol_map.get(module.__name__, {}):
613 resolved_names = symbol_map.get(module.__name__, {})[name]
614 for resolved_name in resolved_names:
615 shell.user_ns[resolved_name] = new_obj
616 else:
617 shell.user_ns[name] = new_obj
618
619 new_refs = []
620 for old_ref in old_objects[key]:
621 old_obj = old_ref()
622 if old_obj is None:
623 continue
624 new_refs.append(old_ref)
625 update_generic(old_obj, new_obj)
626
627 if new_refs:
628 old_objects[key] = new_refs
629 else:
630 del old_objects[key]
631
632 return module
633
634
635 # ------------------------------------------------------------------------------
636 # IPython connectivity
637 # ------------------------------------------------------------------------------
638
639
640 @magics_class
641 class AutoreloadMagics(Magics):
642 def __init__(self, *a, **kw):
643 super().__init__(*a, **kw)
644 self._reloader = ModuleReloader(self.shell)
645 self._reloader.check_all = False
646 self._reloader.autoload_obj = False
647 self.loaded_modules = set(sys.modules)
648
649 @line_magic
650 @magic_arguments.magic_arguments()
651 @magic_arguments.argument(
652 "mode",
653 type=str,
654 default="now",
655 nargs="?",
656 help="""blank or 'now' - Reload all modules (except those excluded by %%aimport)
657 automatically now.
658
659 '0' or 'off' - Disable automatic reloading.
660
661 '1' or 'explicit' - Reload only modules imported with %%aimport every
662 time before executing the Python code typed.
663
664 '2' or 'all' - Reload all modules (except those excluded by %%aimport)
665 every time before executing the Python code typed.
666
667 '3' or 'complete' - Same as 2/all, but also adds any new
668 objects in the module.
669
670 By default, a newer autoreload algorithm that diffs the module's source code
671 with the previous version and only reloads changed parts is applied for modes
672 2 and below. To use the original algorithm, add the `-` suffix to the mode,
673 e.g. '%autoreload 2-', or pass in --full.
674 """,
675 )
676 @magic_arguments.argument(
677 "-p",
678 "--print",
679 action="store_true",
680 default=False,
681 help="Show autoreload activity using `print` statements",
682 )
683 @magic_arguments.argument(
684 "-l",
685 "--log",
686 action="store_true",
687 default=False,
688 help="Show autoreload activity using the logger",
689 )
690 @magic_arguments.argument(
691 "--hide-errors",
692 action="store_true",
693 default=False,
694 help="Hide autoreload errors",
695 )
696 @magic_arguments.argument(
697 "--full",
698 action="store_true",
699 default=False,
700 help="Don't ever use new diffing algorithm",
701 )
702 def autoreload(self, line=""):
703 r"""%autoreload => Reload modules automatically
704
705 %autoreload or %autoreload now
706 Reload all modules (except those excluded by %aimport) automatically
707 now.
708
709 %autoreload 0 or %autoreload off
710 Disable automatic reloading.
711
712 %autoreload 1 or %autoreload explicit
713 Reload only modules imported with %aimport every time before executing
714 the Python code typed.
715
716 %autoreload 2 or %autoreload all
717 Reload all modules (except those excluded by %aimport) every time
718 before executing the Python code typed.
719
720 %autoreload 3 or %autoreload complete
721 Same as 2/all, but also but also adds any new objects in the module. See
722 unit test at IPython/extensions/tests/test_autoreload.py::test_autoload_newly_added_objects
723
724 The optional arguments --print and --log control display of autoreload activity. The default
725 is to act silently; --print (or -p) will print out the names of modules that are being
726 reloaded, and --log (or -l) outputs them to the log at INFO level.
727
728 The optional argument --hide-errors hides any errors that can happen when trying to
729 reload code.
730
731 Reloading Python modules in a reliable way is in general
732 difficult, and unexpected things may occur. %autoreload tries to
733 work around common pitfalls by replacing function code objects and
734 parts of classes previously in the module with new versions. This
735 makes the following things to work:
736
737 - Functions and classes imported via 'from xxx import foo' are upgraded
738 to new versions when 'xxx' is reloaded.
739
740 - Methods and properties of classes are upgraded on reload, so that
741 calling 'c.foo()' on an object 'c' created before the reload causes
742 the new code for 'foo' to be executed.
743
744 Some of the known remaining caveats are:
745
746 - Replacing code objects does not always succeed: changing a @property
747 in a class to an ordinary method or a method to a member variable
748 can cause problems (but in old objects only).
749
750 - Functions that are removed (eg. via monkey-patching) from a module
751 before it is reloaded are not upgraded.
752
753 - C extension modules cannot be reloaded, and so cannot be
754 autoreloaded.
755
756 """
757 args = magic_arguments.parse_argstring(self.autoreload, line)
758 mode = args.mode.lower()
759
760 enable_deduperreload = not args.full
761 if mode.endswith("-"):
762 enable_deduperreload = False
763 mode = mode[:-1]
764 self._reloader.deduper_reloader.enabled = enable_deduperreload
765
766 p = print
767
768 logger = logging.getLogger("autoreload")
769
770 l = logger.info
771
772 def pl(msg):
773 p(msg)
774 l(msg)
775
776 if args.print is False and args.log is False:
777 self._reloader._report = lambda msg: None
778 elif args.print is True:
779 if args.log is True:
780 self._reloader._report = pl
781 else:
782 self._reloader._report = p
783 elif args.log is True:
784 self._reloader._report = l
785
786 self._reloader.hide_errors = args.hide_errors
787
788 if mode == "" or mode == "now":
789 self._reloader.check(True)
790 elif mode == "0" or mode == "off":
791 self._reloader.enabled = False
792 elif mode == "1" or mode == "explicit":
793 self._reloader.enabled = True
794 self._reloader.check_all = False
795 self._reloader.autoload_obj = False
796 elif mode == "2" or mode == "all":
797 self._reloader.enabled = True
798 self._reloader.check_all = True
799 self._reloader.autoload_obj = False
800 elif mode == "3" or mode == "complete":
801 self._reloader.enabled = True
802 self._reloader.check_all = True
803 self._reloader.autoload_obj = True
804 else:
805 raise ValueError(f'Unrecognized autoreload mode "{mode}".')
806
807 @line_magic
808 def aimport(self, parameter_s="", stream=None):
809 """%aimport => Import modules for automatic reloading.
810
811 %aimport
812 List modules to automatically import and not to import.
813
814 %aimport foo
815 Import module 'foo' and mark it to be autoreloaded for %autoreload explicit
816
817 %aimport foo, bar
818 Import modules 'foo', 'bar' and mark them to be autoreloaded for %autoreload explicit
819
820 %aimport -foo, bar
821 Mark module 'foo' to not be autoreloaded for %autoreload explicit, all, or complete, and 'bar'
822 to be autoreloaded for mode explicit.
823 """
824 modname = parameter_s
825 if not modname:
826 to_reload = sorted(self._reloader.modules.keys())
827 to_skip = sorted(self._reloader.skip_modules.keys())
828 if stream is None:
829 stream = sys.stdout
830 if self._reloader.check_all:
831 stream.write("Modules to reload:\nall-except-skipped\n")
832 else:
833 stream.write("Modules to reload:\n%s\n" % " ".join(to_reload))
834 stream.write("\nModules to skip:\n%s\n" % " ".join(to_skip))
835 else:
836 for _module in [_.strip() for _ in modname.split(",")]:
837 if _module.startswith("-"):
838 _module = _module[1:].strip()
839 self._reloader.mark_module_skipped(_module)
840 else:
841 top_module, top_name = self._reloader.aimport_module(_module)
842
843 # Inject module to user namespace
844 self.shell.push({top_name: top_module})
845
846 def pre_run_cell(self, info):
847 # Store the execution info for later use in post_execute_hook
848 self._last_execution_info = info
849
850 if self._reloader.enabled:
851 try:
852 self._reloader.check()
853 except:
854 pass
855
856 def post_execute_hook(self):
857 """Cache the modification times of any modules imported in this execution and track imports"""
858
859 # Track imports from the recently executed code if autoreload 3 is enabled
860 if self._reloader.enabled and self._reloader.autoload_obj:
861 # Use the stored execution info
862 if (
863 hasattr(self, "_last_execution_info")
864 and self._last_execution_info
865 and self._last_execution_info.transformed_cell
866 ):
867 self._track_imports_from_code(
868 self._last_execution_info.transformed_cell
869 )
870
871 newly_loaded_modules = set(sys.modules) - self.loaded_modules
872 for modname in newly_loaded_modules:
873 _, pymtime = self._reloader.filename_and_mtime(sys.modules[modname])
874 if pymtime is not None:
875 self._reloader.modules_mtimes[modname] = pymtime
876
877 self.loaded_modules.update(newly_loaded_modules)
878
879 def _track_imports_from_code(self, code: str) -> None:
880 """Track import statements from executed code"""
881 try:
882 tree = ast.parse(code)
883
884 for node in ast.walk(tree):
885 # Handle "from X import Y" style imports
886 if isinstance(node, ast.ImportFrom):
887 mod = node.module
888
889 # Skip relative imports that don't have a module name
890 if mod is None:
891 continue
892
893 for name in node.names:
894 # name.name is going to be actual name that we want to import from module
895 # name.asname is Z in the case of from X import Y as Z
896 # we should update Z in the shell in this situation, so track it too.
897 original_name = name.name
898 resolved_name = name.asname if name.asname else name.name
899
900 # Since the code executed successfully, we know this import is valid
901 self._reloader.import_from_tracker.add_import(
902 mod, original_name, resolved_name
903 )
904 except (SyntaxError, ValueError):
905 # If there's a syntax error, skip import tracking
906 # (though this shouldn't happen since the code already executed successfully)
907 pass
908
909
910 def load_ipython_extension(ip):
911 """Load the extension in IPython."""
912 auto_reload = AutoreloadMagics(ip)
913 ip.register_magics(auto_reload)
914 ip.events.register("pre_run_cell", auto_reload.pre_run_cell)
915 ip.events.register("post_execute", auto_reload.post_execute_hook)