Clear all internal namespaces, and attempt to release references to user objects. If new_session is True, a new history session will be opened.
(self, new_session=True, aggressive=False)
| 1456 | [m.__dict__ for m in self._main_mod_cache.values()] |
| 1457 | |
| 1458 | def reset(self, new_session=True, aggressive=False): |
| 1459 | """Clear all internal namespaces, and attempt to release references to |
| 1460 | user objects. |
| 1461 | |
| 1462 | If new_session is True, a new history session will be opened. |
| 1463 | """ |
| 1464 | # Clear histories |
| 1465 | if self.history_manager is not None: |
| 1466 | self.history_manager.reset(new_session) |
| 1467 | # Reset counter used to index all histories |
| 1468 | if new_session: |
| 1469 | self.execution_count = 1 |
| 1470 | |
| 1471 | # Reset last execution result |
| 1472 | self.last_execution_succeeded = True |
| 1473 | self.last_execution_result = None |
| 1474 | |
| 1475 | # Flush cached output items |
| 1476 | if self.displayhook.do_full_cache: |
| 1477 | self.displayhook.flush() |
| 1478 | |
| 1479 | # The main execution namespaces must be cleared very carefully, |
| 1480 | # skipping the deletion of the builtin-related keys, because doing so |
| 1481 | # would cause errors in many object's __del__ methods. |
| 1482 | if self.user_ns is not self.user_global_ns: |
| 1483 | self.user_ns.clear() |
| 1484 | ns = self.user_global_ns |
| 1485 | drop_keys = set(ns.keys()) |
| 1486 | drop_keys.discard('__builtin__') |
| 1487 | drop_keys.discard('__builtins__') |
| 1488 | drop_keys.discard('__name__') |
| 1489 | for k in drop_keys: |
| 1490 | del ns[k] |
| 1491 | |
| 1492 | self.user_ns_hidden.clear() |
| 1493 | |
| 1494 | # Restore the user namespaces to minimal usability |
| 1495 | self.init_user_ns() |
| 1496 | if aggressive and not hasattr(self, "_sys_modules_keys"): |
| 1497 | print("Cannot restore sys.module, no snapshot") |
| 1498 | elif aggressive: |
| 1499 | print("culling sys module...") |
| 1500 | current_keys = set(sys.modules.keys()) |
| 1501 | for k in current_keys - self._sys_modules_keys: |
| 1502 | if k.startswith("multiprocessing"): |
| 1503 | continue |
| 1504 | del sys.modules[k] |
| 1505 | |
| 1506 | # Restore the default and user aliases |
| 1507 | self.alias_manager.clear_aliases() |
| 1508 | self.alias_manager.init_aliases() |
| 1509 | |
| 1510 | # Now define aliases that only make sense on the terminal, because they |
| 1511 | # need direct access to the console in a way that we can't emulate in |
| 1512 | # GUI or web frontend |
| 1513 | if os.name == 'posix': |
| 1514 | for cmd in ('clear', 'more', 'less', 'man'): |
| 1515 | if cmd not in self.magics_manager.magics['line']: |
no test coverage detected