Skip to content

Instantly share code, notes, and snippets.

@3vorp
Last active February 28, 2024 22:47
Show Gist options
  • Save 3vorp/b1f73c0c0d38bcb58b98e73d5497876c to your computer and use it in GitHub Desktop.
Save 3vorp/b1f73c0c0d38bcb58b98e73d5497876c to your computer and use it in GitHub Desktop.
CommonJS styled require() for modules in Python. Supports JSON and implicit extensions.
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