diff --git a/docs/user-guide/configuration.md b/docs/user-guide/configuration.md index 607bcf50..6a7bb581 100644 --- a/docs/user-guide/configuration.md +++ b/docs/user-guide/configuration.md @@ -804,7 +804,7 @@ hooks: - my_hooks.py ``` -Then the file *my_hooks.py* can contain any [plugin event handlers](../dev-guide/plugins.md#events) (without `self`), e.g.: +Then the file `my_hooks.py` can contain any [plugin event handlers](../dev-guide/plugins.md#events) (without `self`), e.g.: ```python def on_page_markdown(markdown, **kwargs): @@ -843,6 +843,12 @@ You might have seen this feature in the [mkdocs-simple-hooks plugin](https://git + - my_hooks.py ``` +> NEW: **New in MkDocs 1.6.** +> +> If a hook file has a file `foo.py` adjacent to it, it can use the normal Python syntax `import foo` to access its functions. +> +> In older versions of MkDocs, a workaround was necessary to make this work - adding the path to `sys.path`. + ### plugins A list of plugins (with optional configuration settings) to use when building diff --git a/mkdocs/config/config_options.py b/mkdocs/config/config_options.py index 3025045f..b5c19d81 100644 --- a/mkdocs/config/config_options.py +++ b/mkdocs/config/config_options.py @@ -1208,7 +1208,14 @@ class Hooks(BaseConfigOption[List[types.ModuleType]]): sys.modules[name] = module if spec.loader is None: raise ValidationError(f"Cannot import path '{path}' as a Python module") - spec.loader.exec_module(module) + + old_sys_path = sys.path.copy() + sys.path.insert(0, os.path.dirname(path)) + try: + spec.loader.exec_module(module) + finally: + sys.path[:] = old_sys_path + return module def post_validation(self, config: Config, key_name: str):