Skip to content

Commit

Permalink
Function to load from a path or string a python mod
Browse files Browse the repository at this point in the history
  • Loading branch information
lbiaggi committed Mar 14, 2024
1 parent f34c454 commit 07e4a3e
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions doorstop/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@
import os
import re
import shutil
from importlib.abc import Loader
from importlib.machinery import ModuleSpec
from importlib.util import module_from_spec, spec_from_file_location
from pathlib import Path
from types import ModuleType
from typing import Union, cast

import frontmatter
import yaml
Expand Down Expand Up @@ -346,3 +352,12 @@ def dump_markdown(data, textattr):
frontmatter.Post(content, **data), Dumper=yaml.dumper.Dumper
)
return text


def import_path_as_module(path: Union[Path, str]) -> ModuleType:
name = Path(path).stem
spec = cast(ModuleSpec, spec_from_file_location(name, path))
module = cast(ModuleType, module_from_spec(spec))
loader = cast(Loader, spec.loader)
loader.exec_module(module)
return module

0 comments on commit 07e4a3e

Please sign in to comment.