Skip to content

Commit

Permalink
Merge pull request #7 from iafisher/local-overwrite
Browse files Browse the repository at this point in the history
Fix local variable overwrite bug
  • Loading branch information
julvo authored Nov 4, 2019
2 parents 133383f + 384b71a commit 88e911a
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 14 deletions.
23 changes: 9 additions & 14 deletions reloading/reloading.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import sys
import ast
import traceback
from itertools import chain


def find_loop(tree):
Expand Down Expand Up @@ -40,19 +41,16 @@ def visit(node):
return min(starts), min(ends)


def unique_name(used):
return max(used, key=len) + "0"


def reloading(seq):
frame = inspect.currentframe()

# copy caller's globals into this module's namespace
caller_globals = frame.f_back.f_globals
for k, v in caller_globals.items():
globals()[k] = v

# copy caller's locals into this module's namespace
caller_locals = frame.f_back.f_locals
for k, v in caller_locals.items():
exec('{} = caller_locals["{}"]'.format(k, k))

unique = unique_name(chain(caller_locals.keys(), caller_globals.keys()))
for j in seq:
fpath = inspect.stack()[1][1]
with open(fpath, 'r') as f:
Expand All @@ -77,20 +75,17 @@ def reloading(seq):
indent = re.search('([ \t]*)\S', body_lines[0])
body = '\n'.join([ line[len(indent.group(1)):] for line in body_lines ])

exec(itervars + ' = j')
caller_locals[unique] = j
exec(itervars + ' = ' + unique, caller_globals, caller_locals)

try:
# run main loop body
exec(body)
exec(body, caller_globals, caller_locals)
except Exception:
exc = traceback.format_exc()
exc = exc.replace('File "<string>"', 'File "{}"'.format(fpath))
sys.stderr.write(exc + '\n')
print('Edit the file and press return to continue with the next iteration')
sys.stdin.readline()

# copy locals back into the caller's locals
for k, v in locals().items():
frame.f_back.f_locals[k] = v

return []
5 changes: 5 additions & 0 deletions reloading/test_reloading.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ def test_changing_source(self):
self.assertTrue('INITIAL_FILE_CONTENTS' in stdout and
'CHANGED_FILE_CONTENTS' in stdout)

def test_local_vars_are_not_overwritten(self):
fpath = "test"
for _ in reloading(range(1)):
self.assertEqual(fpath, "test")

def tearDown(self):
if os.path.isfile(SRC_FILE_NAME):
os.remove(SRC_FILE_NAME)
Expand Down

0 comments on commit 88e911a

Please sign in to comment.