-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
0603723
commit 62e6e0b
Showing
2 changed files
with
22 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import importlib.util | ||
import tempfile | ||
|
||
def validate_code(*, path=None, code=None): | ||
""" | ||
Ensure that code written in `path` or in `code` str is importable. | ||
""" | ||
assert (path is None) != (code is None), "Must pass either path to code or code as a str." | ||
|
||
if path: | ||
_try_code_import(path) | ||
return | ||
with tempfile.NamedTemporaryFile(suffix=".py", mode='w+t') as temp: | ||
temp.write(code) | ||
_try_code_import(temp.name) | ||
|
||
def _try_code_import(path): | ||
spec = importlib.util.spec_from_file_location("output_code", path) | ||
module = importlib.util.module_from_spec(spec) | ||
spec.loader.exec_module(module) |