Skip to content

Instantly share code, notes, and snippets.

@frodo821
Last active May 1, 2023 02:21
Show Gist options
  • Save frodo821/ab99dcc4152ae207b7c980a2cd52b327 to your computer and use it in GitHub Desktop.
Save frodo821/ab99dcc4152ae207b7c980a2cd52b327 to your computer and use it in GitHub Desktop.
同階層、あるいはサブディレクトリにある `.json` ファイルを `import` できるようにする `__init__.py`
"""{description_for_this_resources_module}"""
import os
from os.path import join, dirname, relpath, isdir, splitext
from glob import iglob
import sys
from types import ModuleType
from typing import Any
from warnings import warn
from json import load
def initialize(base: str | None = None, key: str = __name__):
base = base or dirname(__file__)
this = sys.modules.get(key, ModuleType(key, None))
for json in iglob(join(base, "*.json"), recursive=False):
rp, _ = splitext(relpath(json, base))
with open(json) as f:
data: dict[str, Any] = load(f)
if not isinstance(data, dict):
warn(f"Invalid data in {json}, expected '{dict}', but got '{type(json)}'", RuntimeWarning)
continue
if data is None:
continue
key_path = f"{key}.{rp}"
sys.modules[key_path] = mod = ModuleType(key_path, data.get('__doc__', None))
setattr(this, rp, mod)
for k, v in data.items():
setattr(mod, k, v)
for d in (f for f in os.listdir(base) if isdir(join(base, f))):
initialize(join(base, d), f"{key}.{d}")
sys.modules[__name__] = ModuleType(__name__, __doc__)
initialize()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment