Skip to content

Commit 4a4b203

Browse files
authored
Merge pull request #202 from skogsbaer/sw/fixUtilsImport
fix imports of internal wypp modules
2 parents 595093b + f0d3498 commit 4a4b203

5 files changed

Lines changed: 37 additions & 1 deletion

File tree

python/code/wypp/runCode.py

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import runpy
55
from dataclasses import dataclass
66
from typing import Optional
7+
from contextlib import contextmanager
78

89
# local imports
910
from constants import *
@@ -86,6 +87,35 @@ def debugModule(name):
8687
print("Origin:", spec.origin)
8788
print("Loader:", type(spec.loader).__name__)
8889

90+
import sys
91+
import os
92+
import contextlib
93+
94+
@contextlib.contextmanager
95+
def freshModules():
96+
original_modules = sys.modules.copy()
97+
stdlib_path = os.path.dirname(os.__file__)
98+
whitelist = ('sys', 'os', 'contextlib', 'runpy', 'wypp', '__main__', '__wypp__')
99+
def is_core(name, module):
100+
if name in sys.stdlib_module_names or name in sys.builtin_module_names:
101+
return True
102+
module_file = getattr(module, '__file__', None)
103+
if module_file and module_file.startswith(stdlib_path):
104+
return True
105+
if name in whitelist:
106+
return True
107+
return False
108+
109+
try:
110+
for mod_name in list(sys.modules.keys()):
111+
if not is_core(mod_name, sys.modules[mod_name]):
112+
del sys.modules[mod_name]
113+
yield
114+
finally:
115+
# 4. Restore everything
116+
sys.modules.clear()
117+
sys.modules.update(original_modules)
118+
89119
def runCode(fileToRun, globals, doTypecheck=True, extraDirs=None) -> dict:
90120
if not extraDirs:
91121
extraDirs = []
@@ -94,7 +124,8 @@ def runCode(fileToRun, globals, doTypecheck=True, extraDirs=None) -> dict:
94124
sys.dont_write_bytecode = True
95125
if DEBUG:
96126
debugModule(modName)
97-
res = runpy.run_module(modName, init_globals=globals, run_name='__wypp__', alter_sys=False)
127+
with freshModules():
128+
res = runpy.run_module(modName, init_globals=globals, run_name='__wypp__', alter_sys=False)
98129
return res
99130

100131
def runStudentCode(fileToRun, globals, onlyCheckRunnable, doTypecheck=True, extraDirs=None) -> dict:

python/file-test-data/extras/testUtilsImport_ok.err

Whitespace-only changes.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
stefan
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
import utils
2+
print(utils.hi)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# WYPP_TEST_CONFIG: {"exitCode": 0}
2+
hi = 'stefan'

0 commit comments

Comments
 (0)