From d0bac63fb30b92458c4db547913563daf8b9861a Mon Sep 17 00:00:00 2001 From: Martinez Date: Thu, 16 Feb 2017 11:14:16 +0100 Subject: [PATCH] - adds over.misc.update_dict - fixes #4 over.misc.console is too hard to use --- over/misc.py | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/over/misc.py b/over/misc.py index 4c59b23..c7ff740 100644 --- a/over/misc.py +++ b/over/misc.py @@ -54,22 +54,42 @@ def batch_gen(data, batch_size): # -------------------------------------------------- -def console(locals, globals=None, tab_completion=True): +def update_dict(A, B, overwrite=False): + """ + Shallow-copies items from B to A. + + Iff `overwrite`, keys that already exist in A will be overwritten. + Otherwise, only keys that aren't in A will be set. + """ + + for key, value in B.items(): + if key not in A: + A[key] = value + +# -------------------------------------------------- + +def console(override_environment=None, tab_completion=True): """ Opens up a Python console. + + If no `override_environment` is passed, the environment of the calling stack frame (and all parent stack frames) will be used. """ import code import copy + import inspect import readline import rlcompleter - environment = copy.copy(locals) - - if globals: - for key, value in globals.items(): - if key not in environment: - environment[key] = value + if override_environment: + environment = override_environment + else: + environment = {} + frame = inspect.currentframe() + + while frame: + update_dict(environment, frame.f_locals) + frame = frame.f_back if tab_completion: readline.parse_and_bind("tab: complete")