Last active
February 28, 2024 22:47
-
-
Save 3vorp/b1f73c0c0d38bcb58b98e73d5497876c to your computer and use it in GitHub Desktop.
CommonJS styled require() for modules in Python. Supports JSON and implicit extensions.
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
from importlib.util import spec_from_file_location, module_from_spec | |
def require(path: str): | |
""" | |
JavaScript styled require with relative paths and JSON support. | |
""" | |
if (path.endswith(".json")): | |
from json import loads | |
with open(path, "r") as f: | |
return loads(f.read()) | |
if not "." in path.split("/")[-1]: path += ".py" | |
name = path.split("/")[-1].split(".")[0] | |
spec = spec_from_file_location(name, path) | |
module = module_from_spec(spec) | |
spec.loader.exec_module(module) | |
return module |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment