You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I need to write a very small markdown extension specific to my documentation project, so I do not want the source code of that extension to be something I install through pip or anything, it has to live in the same source tree as my doc.
How can I specify in mkdoc's config a path to add to the where Python looks for modules so that when resolving markdown_extensions it finds the one that is in extensions/foo.py next to my mkdocs.yml? Just need a config option to add something to Python's sys.path basically.
PS: Playing with PYTHONPATH is not an option as it is a hell to document and maintain custom command lines; I want the end user to just run a standard mkdocs serve without any additional clutter.
There's no such setting, but you can maybe try writing a simple hook to add a folder to sys.path.
In hooks.py:
defon_startup(*args, **kwargs):
sys.path.insert(0, os.getcwd())
# use something more robust than the current directory, it's just an example
In mkdocs.yml:
hooks:
- hooks.py
The on startup event will be triggered only once, even when serving. If you need to use another event, you'll have to make sure not to insert the folder multiple times.
I think this will allow Markdown to get the extension with its import path, as I believe it will do that after the on startup event.
Sorry for the terseness, I'm on mobile.
(@mkdocs/core care to move this to Q/A? I can't from the app)
I would kindly as the maintainers to consider this for implementation, not moving it to Q/A. Material for MkDocs, for instance, provides several settings where behavior can be customized. This does not work without explicitly setting PYTHONPATH (see https://github.com/mkdocs-material/create-blog/issues/2), which the OP already mentioned is cumbersome to maintain, as it's an environment setting. IMHO, creating a hook is a hack. Examples where users can reference custom python functions:
The issue is that the path needs to be set before we even read the config since YAML will try and load the objects. Therefore we can't add a config option for this. What's left? A command-line flag?
In the other issue you mention that MkDocs could add the parent directory of the config file to sys.path. That's an idea worth considering. This will need discussion with monorepo-like plugin authors, probably. Also, config inheritance could be annoying again here ^^
In the other issue you mention that MkDocs could add the parent directory of the config file to sys.path. That's an idea worth considering. This will need discussion with monorepo-like plugin authors, probably. Also, config inheritance could be annoying again here ^^
Jup, exactly. It's currently really annoying to provide custom functions because of the extra hoops you need to jump through. If there's another way than PYTHONPATH to make those functions more easily discoverable, perfect!
Note that the original request is an upstream issue. The extension loading code is part of the Markdown library, not part of MkDocs. All MkDocs does is accept a bunch of config options and pass those on to the Markdown library. Resolving paths and loading extensions all happens in the Markdown library. As first I was going to suggest this be closed as an upstream issue or moved to a discussion as a way to document workarounds to the upstream library's restrictions. That said, as maintainer of the upstream library, I can say that I have no plans to alter the extension loading mechanism, so if MkDocs wants to address this, then by all means, keep this open.
I will note that the Markdown library does not have this issue as it is a Python library and any direct user of the library can just use Python code to import an extension and pass the Python object directly to Markdown. Obviously, that doesn't work so easily for MkDocs, where the users are typically not working in a Python environment. So, does MkDocs want to provide a mechanism for users to provide their own Python code which is importable (on the PYTHONPATH)? And if so, how? I guess that has been the general question asked here.
MkDocs could add the parent directory of the config file to sys.path.
This is an interesting suggestion. If you were to hardcode this, I wonder if it would make more sense to use a subdir to avoid weird issues. In other words, a directory that is a sibling of the config file. This subdir would not contain another other resources and therefore there should be no weird issues with the paths of various other resources that MkDocs uses.
I will also note that this could be user definable from the config file. As a reminder, the config file is processed in three steps. When validating the config, MkDocs steps through each option 3 times. The first time it handles pre_validation, the second time it handles validation and the third time it handles post_validation. In other words, the pre_validation for all options is run before any option's validation is run. It would be pretty simple to define a new config option which used pre_validation to allow the user to point to a dir and/or file which should be added to the PYTHONPATH. Then, when the markdown_extensions option's validation is run, the path would be available and anything on that path would be loadable. I would suggest allowing the option to define a list of locations relative to the config file location.
The one issue with using a config option to add locations to the PYTHONPATH is that those locations are only available after the YAML parser has passed the parsed data to MkDocs for validation. Therefore, any YAML specific paths would not benefit from this (as the path will not have been added yet). However, in the case of markdown_extensions that is not a problem as the extension paths can be strings which are converted to paths by the upstream library much later. Hardcoding a location would allow MkDocs to add the location to PYTHONPATH before calling the YAML parser. I suppose an environment variable or a command line option could allow the location to be user configurable if that is deemed necessary.
Thanks @waylan for the thorough answer. I was going to suggest too that, instead of relying on the (controversial IMO) feature of PyYAML, plugins and extensions could accept strings instead of objects (loaded thanks to !!python:name and similar). But that means duplicating import logic in many third party stuff 🤔 Fortunately and as you pointed, it's already supported by Python-Markdown for loading extensions.
Also, yeah, adding the parent directory of the config file to sys.path must be done carefully. The src-layout came to be for a reason. From what I saw in the MkDocs, this shouldn't cause issues, but we can't be sure without doing some assessment.
All MkDocs does is accept a bunch of config options and pass those on to the Markdown library. Resolving paths and loading extensions all happens in the Markdown library.
[...]
The Markdown library does not have this issue as it is a Python library and any direct user of the library can just use Python code to import an extension and pass the Python object directly to Markdown.
As you self-answer, the problem does not lie in the upstream library but the (limited) way it is exposed to the end-user by mkdocs, so it is a mkdocs issue.
The issue is that the path needs to be set before we even read the config since YAML will try and load the objects.
Not sure how the tech stack works in this very case, but as far as I know the YAML standard says nothing about loading Python modules, so there should be a way to parse the file as a pure function (without triggering any side effect). May be needed to parse it twice, once ahead of time just to get the custom sys.path and then a second time "for real".
Sure, ReadTheDocs has been using such techniques in the past for security reasons. That just means reimplementing YAML's Python objet loading feature directly in MkDocs. That's an option too.
as far as I know the YAML standard says nothing about loading Python modules,
True, but the Python implementation (PyYAML) adds some features on top of the standard YAML spec which are supported by default. Specifically, users have been referencing Python objects directly from their YAML config files for some time now. Of course, for this to work, those objects need to already be on the PYTHONPATH when the config file is parsed by PyYAML. This conversation has been taking place with this understanding in mind; although none of us have explicitly explained that.
After giving this some more thought, I have a proposal:
My Proposal
Add a --scripts (or --scripts-dir or --user-scripts?) command line option to the build and serve commands. By default, the value would be an empty string (or maybe None?) and do nothing. Alternatively, a MKDOCS_USER_SCRIPTS_DIR (or whatever name we choose) environment variable could define a default value, which the --scripts command line option would override if both were defined. Pointing to a nonexistent directory would fail with an error.
When the option is set, it would point at a directory where user provided Python code could exist without the code needing to be "installed." The value assigned to the option would be resolved to a local path and added to PYTHONPATH (for that Python instance only) prior to loading the config file.
The actual directory that the option points to would need to contain importable Python files possibly including an empty __init__.py file. Note that MkDocs does not import anything in this directory. It simply adds the directory to the list of Python's importable locations. A plugin, extension, or YAML Python object reference would need to import and run the code. Therefore, if a user included the option on a default MkDocs project, nothing would actually get imported. Some customizations would need to be configured first.
Questions
Here are a few things I'm not sure about. How do you think we should proceed?
Should we allow the option to point at a file or only allow a directory? It is possible that some users will not want to mess with creating an importable directory (__init__.py etc) and will only need a single file. Additionally, users can point at specific objects within a single file with the colon notation (path.to.module:MyObject) so long as the relevant plugin or extension supports that syntax (it is not universal). Therefore, users could conceivably include multiple unrelated functions and classes in a single file.
How do we make the user provided directory available from within Python? Do we include the dir at the root of the PYTHONPATH (so that scripts_dir/myscript.py is importable as import myscript) or do we 'mount' the contents of the dir as a submodule of some predetermined location (so that scripts_dir/myscript.py is importable as from mkdocs.user_scripts import myscript)? The later avoids naming conflicts with existing Python libs, but may be less intuitive to users.
Pros of this proposal
Users can provide their own Python code without needing to package it and install it (resolving this issue).
Plugins now have a predetermine location to allow users to provide their own scripts. Each plugin no longer needs to provide their own config option and handle adding their own locations to PYTHONPATH or otherwise manually importing modules using Python's lower level APIs.
All user provided code is also available via PyYAML's default mechanisms for referencing Python objects, which means that in many cases, plugins and extensions need to do nothing to provide support.
Cons of this proposal
No support is provided for a config option, which means that the option must be defined for each system (via env var) or each run (via cli option). Fortunately, CI config files and Python envs provide options for defining env vars, so this should not be a big hurdle for most people. And quite frankly, if a user is writing their own Python code, then it does not seem unreasonable to expect them to be able to define an env var. However, it could be annoying that one could not simply clone an existing repo to a new machine and immediately run build without remembering to explicitly reference the scripts dir.
While support for a config option could be added (as I detailed in an earlier comment), I am not including that in this proposal as such a solution would not be available to PyYAML's native Python object references. My proposal is intended to provide consistent behavior everywhere. But, if it was deemed necessary, such an option could always be added. If so, then the env var and/or cli option would override whatever value is set in the config. However, an unset config option (value of None) would not override the env var or cli option.
Another pro of my proposal is that users would have the freedom to put their scripts dir wherever they want it. It could be a sibling of the config file or it could be a subdir of the docs dir, or somewhere else that they choose. And by allowing them to name it, there is no concern over using some preexisting name of a directory would serves another purpose in their repo.
One matter regarding my proposal that I haven't mentioned is that by default all relative paths would be relative to the CWD. When using the cli, this would be sensible to the user as the path would be relative to their current location on the system (a pro). However, this could be an issue for the env var. A globally defined env var can't assume the command is being run from a specific location (a con). As a reminder, the build and serve commands can be run with the --config option which points as a config file not in the CWD. What if we resolved a relative path relative to the location of the config file? In the common case that would be the CWD anyway, but in the uncommon case it would result in consistent behavior (no need to assign different values to the cli option than to the env var). Thoughts?
The more I think about it, the more uncomfortable I am with the idea that the script dir path would be relative to the config file. That would be very unintuitive to users. Additionally, MkDocs has never officially supported PyYAML's Python object references. We have simply never explicitly disallowed them. The thing is, with official support for user provided code, we are providing an alternative which eliminates the need for them. So maybe we just add a config option to the config file and skip all the cli and env var options. Then we could officially deprecate support for PyYAML's python object references with the end-goal of eventually explicitly not supporting them.
But, then how would users reference existing Python objects? They can import the existing installed object into their scripts and reference that from their config file. As an example, suppose a user wants to use a different slug function for Markdown's toc extension. The extensions config option expects a Python callable object and does no importing of its own. So then the user can create their instance of the extension and reference that from the config.
Markdown already supports parsing and importing the object using the colon syntax, so there is no need for the YAML parser to know or understand that the script is referencing a Python object. That said, it certainly is easier for the user now with the following (no user scripts necessary).
Instead of only supporting mkdocs.yml, allow configuration to be provided by an export in mkdocs.py. This is common practice among many (if not all) JavaScript build tools. If you don't need scripting, mkdocs.yml is enough, but if you do, you can build your own MkDocs configuration within mkdocs.py programatically. The exported configuration would then be read by MkDocs and validated as usual. The user could now explicitly import functions (or define them inline in this configuration file) to solve everything mentioned in #3772 (comment) and more.
DIsclaimer: I haven't thought this through yet, but from my experience talking to users, allowing to script configuration would make many things simpler. Configuration composition, environment-specific settings, custom slugs, etc.
Should we allow the option to point at a file or only allow a directory?
Directory only. And only as a Python search path, not as a package, i.e. the directory must not contain an __init__.py module.
Question 2:
How do we make the user provided directory available from within Python? Do we include the dir at the root of the PYTHONPATH [...]
Yes. I think that's the most reasonable thing to do, and will be intuitive to users.
Regarding how the path is computed: if it is not absolute, the path should definitely be computed as relative to the config file directory. This is what many plugins do (and MkDocs as well for a few things IIRC), and is the only way to make it work with the -f option. For these reasons I don't think it would be unintuitive for users.
Also I think it is super important that both the environment variable and the CLI flag behave the same way.
If we want to eventually stop supporting PyYAML's loading features, I agree that MkDocs should immediately start with a config option, and not a CLI flag and environment variable. At the same time, MkDocs should provide reusable code to load objects given their dotted-path, with or without support for colons separating modules/filepaths from attributes, so that plugins and extensions can start migrating. Then MkDocs could start emitting messages (debug, then info, then warning level) when !!-Python-tags are used (can be done by simply iterating on the loaded contents to find non-builtin objects), advertising again its own API to load objects from their paths. Finally, we would properly deprecate support for !!-tags and eventually remove support.
Or should MkDocs provide utilities/helpers/classes to make this code less verbose and better typed?
The YAML version is 185 lines long, the Python version is 285 lines long.
A few remarks:
it looks like Sphinx config 🙈
it goes in the opposite direction of pyproject.toml: config files become dynamic instead of static (even though they are already a bit dynamic with things like !!-tags and !ENV etc.)
that means we need Python to read them, so a working Python environment, and maybe even some dependencies installed
that could complicate things for third-party projects, especially if they're written in another language than Python
@humitos what would RTD think of a Python config file?
My first opinion is that this would have too many disadvantages so I wouldn't vote for supporting Python config files in addition to YAML ones. But I'm open to discussing it more.
Now, speaking just as a developer related to the documentation world.
Add a --scripts (or --scripts-dir or --user-scripts?) command line option to the build and serve commands. By default, the value would be an empty string (or maybe None?) and do nothing. Alternatively, a MKDOCS_USER_SCRIPTS_DIR (or whatever name we choose) environment variable could define a default value, which the --scripts command line option would override if both were defined. Pointing to a nonexistent directory would fail with an error.
@waylan I'm not sure to understand what would be the benefits for this approach compared with just defining the same directory as PYTHONPATH environment variable at runtime. Could you expand on that?
Instead of only supporting mkdocs.yml, allow configuration to be provided by an export in mkdocs.py.
There is a lot of discussion about YAML vs TOML vs Python files in Sphinx in this issue sphinx-doc/sphinx#9040 that I remember discussing some time ago and may worth to keep in mind for this topic.
My first opinion is that this would have too many disadvantages so I wouldn't vote for supporting Python config files in addition to YAML ones. But I'm open to discussing it more.
@pawamoy I agree with you. I think it will bring a lot more disadvantages than benefits at this point.
Reacted by Timothée Mazzucotelli and Martin Donath
I'm not sure to understand what would be the benefits for this approach compared with just defining the same directory as PYTHONPATH environment variable at runtime. Could you expand on that?
OP explicitly stated that using PYTHONPATH is not ergonomic (different CLI commands or environment setup depending on the system and user). Also PYTHONPATH requires absolute paths, while MkDocs could allow paths relative to the config file, making things easier again for writing docs across different systems/environments.
It looks like the conversation in Sphinx's issue tracker gravitates towards "static config by default, allow customization with dynamic config", which is exactly what we can get with hooks, as mentioned in my first comment here 🙂 By the way, hooks even allow dynamically adding extensions or plugins to the config, so I think this is solved. People interested in static vs. dynamic are free to open a new discussion 🙂 Lets try to answer the initial question here.
@eliemichel can you tell us what you think of using hooks? Write them once, and your contributors can run mkdocs serve as usual.
To be clear, I mean altering sys.path in on_startup if you need to pass the path of an object as a string, and altering the config in on_config if you need to configure extensions that only accept objects as values, not strings.
@squidfunk Sphinx does this already by using a conf.py and this comes with lot of flexibility but lot of disadvantages as well. In fact, on of the features people appreciate the most from Jupyter Book is they built a layer on top of Sphinx that uses a _config.yml file
Good point 😅 It boils down to how much additional logic one wants to add to a standard format like YAML, TOML, JSON that needs extra care instead of saying: you can always do it programmatically, if you need more control. JS is closer to JSON, essentially scriptable JSON, which might explain the gravitation towards this approach in this ecosystem.
By the way, hooks even allow dynamically adding extensions or plugins to the config, so I think this is solved. People interested in static vs. dynamic are free to open a new discussion 🙂 Lets try to answer the initial question here.
AFAIK, hooks, specifically on_config, are executed post-config validation. This might be too late for some cases.
@pawamoy my goal was to try thinking outside the box and to pull in adjacent problems that often help me (at least) to think about the bigger picture here. I'm not sure what Tom, the new lead maintainer of this project, has in mind for the future, but configuration is a frequent topic that is still unsolved, so I think we should discuss it. MkDocs has no programmatic API and only allows for very limited dynamic interaction with configuration files. Configuration inheritance and YAML tags (which @waylan vouches for removing) only solves a fraction of known problems.
A hook can be assigned a priority via event_priority, but the config is parsed before any of the hooks is invoked.
... except for on_startup, which only discerns the mode of invocation, nothing more.
Correct. As a reminder, we need to have already parsed the config to know which extensions to load. As hooks are implemented by extensions, there would be no way to use hooks to alter the config parser's behavior. Even the on_startup hook runs after loading the config (despite what the docs indicate... that might need looking into; did the code change and no longer matches the docs, or have the docs always been wrong?) Therefore, I do not see hooks as a viable solution.
allow configuration to be provided by an export in mkdocs.py
This is an interesting suggestion and something that I considered briefly. I have had a desire for this from time to time over the years. Ultimately, however, I don't think it makes sense for MkDocs. MkDocs is used to document a lot of non-Python projects and based on some reports we've received over the years, some users don't realize that it is implemented in Python and have never used Python before. Moving to a Python config would be a drastic change in the scope of what MkDocs is. Personally, I would be happy to use that tool, but that is not what most of MkDocs' users signed up for. Of course, supporting both types of config files reduces that concern, but also complicates things with additional documentation, support and maintenance. I'm not sure the cost justifies the gains. Various other concerns have already been addressed in other comments so I'm not going to comment further on this.
I'm not sure to understand what would be the benefits for this approach compared with just defining the same directory as PYTHONPATH environment variable at runtime. Could you expand on that?
OP explicitly stated that using PYTHONPATH is not ergonomic (different CLI commands or environment setup depending on the system and user). Also PYTHONPATH requires absolute paths, while MkDocs could allow paths relative to the config file, making things easier again for writing docs across different systems/environments.
Thanks @pawamoy, you covered that well. Also, thanks for the clear answers (in this comment) to the questions I raised. You made good points and raised a few concerns I hadn't considered. I agree with your assessment.
To be clear, I am not advocating for dropping support. However, there have been comments from some individuals over the years who have taken this position. Personally I have been neutral on this issue. I was simply saying that if that was the way McDocs wanted to go, then this would be a potential path to do that. However, I am in no way saying that I think MkDocs should move in that direction. In fact, that is why I proposed a solution which continues to support them.
Reacted by Timothée Mazzucotelli and Martin Donath
To be clear, I mean altering sys.path in on_startup if you need to pass the path of an object as a string, and altering the config in on_config if you need to configure extensions that only accept objects as values, not strings.
To be more clear, I meant to use on_startup to add your scripts folder to sys.path when the target extension/plugin supports loading objects given a string identifying them (such as Python-Markdown supporting extension paths as strings). Even if the hook is executed after the config is loaded, I believe Markdown extensions passed as strings are loaded after the config validation, so at that time Python-Markdown will be able to find your Python modules because sys.path was altered.
I also meant to use on_config to programmatically add extensions and their configuration to the main config when they don't support loading objects from strings. For this you'd completely remove the extension/plugin that doesn't support loading objects given strings from mkdocs.yml, and add it from a hook instead. Something like this (probably not 100% correct):
This way you can effectively declare most of your config statically, and use hooks to declare the rest dynamically. To me it even looks like we could declare almost all config through hooks, allowing config dependent on the environment, system, etc. Could be interesting to actually try that and report back.
site_name: Dynamic site helloooohooks:
- mkdocs_config.py
# mkdocs_config.pydefon_startup(...):
# alter sys.path or whateverdefon_config(...):
# alter theme, extensions, plugins, ...
Ideally MkDocs would provide a friendly API to configure everything.
Activity
pawamoy commentedon Jul 19, 2024
There's no such setting, but you can maybe try writing a simple hook to add a folder to
sys.path.In hooks.py:
In mkdocs.yml:
The on startup event will be triggered only once, even when serving. If you need to use another event, you'll have to make sure not to insert the folder multiple times.
I think this will allow Markdown to get the extension with its import path, as I believe it will do that after the on startup event.
Sorry for the terseness, I'm on mobile.
(@mkdocs/core care to move this to Q/A? I can't from the app)
squidfunk commentedon Jul 19, 2024
I would kindly as the maintainers to consider this for implementation, not moving it to Q/A. Material for MkDocs, for instance, provides several settings where behavior can be customized. This does not work without explicitly setting
PYTHONPATH(see https://github.com/mkdocs-material/create-blog/issues/2), which the OP already mentioned is cumbersome to maintain, as it's an environment setting. IMHO, creating a hook is a hack. Examples where users can reference custom python functions:Plugins
blog.config.post_slugifyblog.config.categories_slugifyprojects.config.projects_config_transformtags.config.tags_slugifyExtensions
toc.slugifypymdownx.emoji.emoji_indexpymdownx.emoji.emoji_generatorpymdownx.tabbed.slugifypawamoy commentedon Jul 19, 2024
The issue is that the path needs to be set before we even read the config since YAML will try and load the objects. Therefore we can't add a config option for this. What's left? A command-line flag?
pawamoy commentedon Jul 19, 2024
In the other issue you mention that MkDocs could add the parent directory of the config file to sys.path. That's an idea worth considering. This will need discussion with monorepo-like plugin authors, probably. Also, config inheritance could be annoying again here ^^
squidfunk commentedon Jul 19, 2024
Jup, exactly. It's currently really annoying to provide custom functions because of the extra hoops you need to jump through. If there's another way than
PYTHONPATHto make those functions more easily discoverable, perfect!waylan commentedon Jul 19, 2024
Note that the original request is an upstream issue. The extension loading code is part of the Markdown library, not part of MkDocs. All MkDocs does is accept a bunch of config options and pass those on to the Markdown library. Resolving paths and loading extensions all happens in the Markdown library. As first I was going to suggest this be closed as an upstream issue or moved to a discussion as a way to document workarounds to the upstream library's restrictions. That said, as maintainer of the upstream library, I can say that I have no plans to alter the extension loading mechanism, so if MkDocs wants to address this, then by all means, keep this open.
I will note that the Markdown library does not have this issue as it is a Python library and any direct user of the library can just use Python code to import an extension and pass the Python object directly to Markdown. Obviously, that doesn't work so easily for MkDocs, where the users are typically not working in a Python environment. So, does MkDocs want to provide a mechanism for users to provide their own Python code which is importable (on the PYTHONPATH)? And if so, how? I guess that has been the general question asked here.
This is an interesting suggestion. If you were to hardcode this, I wonder if it would make more sense to use a subdir to avoid weird issues. In other words, a directory that is a sibling of the config file. This subdir would not contain another other resources and therefore there should be no weird issues with the paths of various other resources that MkDocs uses.
I will also note that this could be user definable from the config file. As a reminder, the config file is processed in three steps. When validating the config, MkDocs steps through each option 3 times. The first time it handles
pre_validation, the second time it handlesvalidationand the third time it handlespost_validation. In other words, thepre_validationfor all options is run before any option'svalidationis run. It would be pretty simple to define a new config option which usedpre_validationto allow the user to point to a dir and/or file which should be added to the PYTHONPATH. Then, when themarkdown_extensionsoption'svalidationis run, the path would be available and anything on that path would be loadable. I would suggest allowing the option to define a list of locations relative to the config file location.The one issue with using a config option to add locations to the PYTHONPATH is that those locations are only available after the YAML parser has passed the parsed data to MkDocs for validation. Therefore, any YAML specific paths would not benefit from this (as the path will not have been added yet). However, in the case of
markdown_extensionsthat is not a problem as the extension paths can be strings which are converted to paths by the upstream library much later. Hardcoding a location would allow MkDocs to add the location to PYTHONPATH before calling the YAML parser. I suppose an environment variable or a command line option could allow the location to be user configurable if that is deemed necessary.pawamoy commentedon Jul 19, 2024
Thanks @waylan for the thorough answer. I was going to suggest too that, instead of relying on the (controversial IMO) feature of PyYAML, plugins and extensions could accept strings instead of objects (loaded thanks to
!!python:nameand similar). But that means duplicating import logic in many third party stuff 🤔 Fortunately and as you pointed, it's already supported by Python-Markdown for loading extensions.pawamoy commentedon Jul 19, 2024
Also, yeah, adding the parent directory of the config file to sys.path must be done carefully. The src-layout came to be for a reason. From what I saw in the MkDocs, this shouldn't cause issues, but we can't be sure without doing some assessment.
eliemichel commentedon Jul 19, 2024
Thanks everyone for the quick reaction!
As you self-answer, the problem does not lie in the upstream library but the (limited) way it is exposed to the end-user by mkdocs, so it is a mkdocs issue.
Not sure how the tech stack works in this very case, but as far as I know the YAML standard says nothing about loading Python modules, so there should be a way to parse the file as a pure function (without triggering any side effect). May be needed to parse it twice, once ahead of time just to get the custom sys.path and then a second time "for real".
pawamoy commentedon Jul 19, 2024
Sure, ReadTheDocs has been using such techniques in the past for security reasons. That just means reimplementing YAML's Python objet loading feature directly in MkDocs. That's an option too.
waylan commentedon Jul 22, 2024
True, but the Python implementation (PyYAML) adds some features on top of the standard YAML spec which are supported by default. Specifically, users have been referencing Python objects directly from their YAML config files for some time now. Of course, for this to work, those objects need to already be on the PYTHONPATH when the config file is parsed by PyYAML. This conversation has been taking place with this understanding in mind; although none of us have explicitly explained that.
waylan commentedon Jul 24, 2024
After giving this some more thought, I have a proposal:
My Proposal
Add a
--scripts(or--scripts-diror--user-scripts?) command line option to thebuildandservecommands. By default, the value would be an empty string (or maybeNone?) and do nothing. Alternatively, aMKDOCS_USER_SCRIPTS_DIR(or whatever name we choose) environment variable could define a default value, which the--scriptscommand line option would override if both were defined. Pointing to a nonexistent directory would fail with an error.When the option is set, it would point at a directory where user provided Python code could exist without the code needing to be "installed." The value assigned to the option would be resolved to a local path and added to PYTHONPATH (for that Python instance only) prior to loading the config file.
The actual directory that the option points to would need to contain importable Python files possibly including an empty
__init__.pyfile. Note that MkDocs does not import anything in this directory. It simply adds the directory to the list of Python's importable locations. A plugin, extension, or YAML Python object reference would need to import and run the code. Therefore, if a user included the option on a default MkDocs project, nothing would actually get imported. Some customizations would need to be configured first.Questions
Here are a few things I'm not sure about. How do you think we should proceed?
__init__.pyetc) and will only need a single file. Additionally, users can point at specific objects within a single file with the colon notation (path.to.module:MyObject) so long as the relevant plugin or extension supports that syntax (it is not universal). Therefore, users could conceivably include multiple unrelated functions and classes in a single file.scripts_dir/myscript.pyis importable asimport myscript) or do we 'mount' the contents of the dir as a submodule of some predetermined location (so thatscripts_dir/myscript.pyis importable asfrom mkdocs.user_scripts import myscript)? The later avoids naming conflicts with existing Python libs, but may be less intuitive to users.Pros of this proposal
Cons of this proposal
No support is provided for a config option, which means that the option must be defined for each system (via env var) or each run (via cli option). Fortunately, CI config files and Python envs provide options for defining env vars, so this should not be a big hurdle for most people. And quite frankly, if a user is writing their own Python code, then it does not seem unreasonable to expect them to be able to define an env var. However, it could be annoying that one could not simply clone an existing repo to a new machine and immediately run
buildwithout remembering to explicitly reference the scripts dir.While support for a config option could be added (as I detailed in an earlier comment), I am not including that in this proposal as such a solution would not be available to PyYAML's native Python object references. My proposal is intended to provide consistent behavior everywhere. But, if it was deemed necessary, such an option could always be added. If so, then the env var and/or cli option would override whatever value is set in the config. However, an unset config option (value of
None) would not override the env var or cli option.Any and all feedback is welcome.
waylan commentedon Jul 24, 2024
Another pro of my proposal is that users would have the freedom to put their scripts dir wherever they want it. It could be a sibling of the config file or it could be a subdir of the
docsdir, or somewhere else that they choose. And by allowing them to name it, there is no concern over using some preexisting name of a directory would serves another purpose in their repo.One matter regarding my proposal that I haven't mentioned is that by default all relative paths would be relative to the CWD. When using the cli, this would be sensible to the user as the path would be relative to their current location on the system (a pro). However, this could be an issue for the env var. A globally defined env var can't assume the command is being run from a specific location (a con). As a reminder, the
buildandservecommands can be run with the--configoption which points as a config file not in the CWD. What if we resolved a relative path relative to the location of the config file? In the common case that would be the CWD anyway, but in the uncommon case it would result in consistent behavior (no need to assign different values to the cli option than to the env var). Thoughts?waylan commentedon Jul 24, 2024
The more I think about it, the more uncomfortable I am with the idea that the script dir path would be relative to the config file. That would be very unintuitive to users. Additionally, MkDocs has never officially supported PyYAML's Python object references. We have simply never explicitly disallowed them. The thing is, with official support for user provided code, we are providing an alternative which eliminates the need for them. So maybe we just add a config option to the config file and skip all the cli and env var options. Then we could officially deprecate support for PyYAML's python object references with the end-goal of eventually explicitly not supporting them.
But, then how would users reference existing Python objects? They can import the existing installed object into their
scriptsand reference that from their config file. As an example, suppose a user wants to use a different slug function for Markdown'stocextension. The extensions config option expects a Python callable object and does no importing of its own. So then the user can create their instance of the extension and reference that from the config.custom_toc.pymkdocs.yamlMarkdown already supports parsing and importing the object using the colon syntax, so there is no need for the YAML parser to know or understand that the script is referencing a Python object. That said, it certainly is easier for the user now with the following (no user scripts necessary).
mkdocs.yamlAnd that is why I am trying to develop a solution which works with PyYAML's features.
squidfunk commentedon Jul 25, 2024
Here's an idea from the JavaScript world:
Instead of only supporting
mkdocs.yml, allow configuration to be provided by an export inmkdocs.py. This is common practice among many (if not all) JavaScript build tools. If you don't need scripting,mkdocs.ymlis enough, but if you do, you can build your own MkDocs configuration withinmkdocs.pyprogramatically. The exported configuration would then be read by MkDocs and validated as usual. The user could now explicitly import functions (or define them inline in this configuration file) to solve everything mentioned in #3772 (comment) and more.DIsclaimer: I haven't thought this through yet, but from my experience talking to users, allowing to script configuration would make many things simpler. Configuration composition, environment-specific settings, custom slugs, etc.
Examples:
All very, very popular tools.
pawamoy commentedon Jul 25, 2024
@waylan
Question 1:
Directory only. And only as a Python search path, not as a package, i.e. the directory must not contain an
__init__.pymodule.Question 2:
Yes. I think that's the most reasonable thing to do, and will be intuitive to users.
Regarding how the path is computed: if it is not absolute, the path should definitely be computed as relative to the config file directory. This is what many plugins do (and MkDocs as well for a few things IIRC), and is the only way to make it work with the
-foption. For these reasons I don't think it would be unintuitive for users.Also I think it is super important that both the environment variable and the CLI flag behave the same way.
If we want to eventually stop supporting PyYAML's loading features, I agree that MkDocs should immediately start with a config option, and not a CLI flag and environment variable. At the same time, MkDocs should provide reusable code to load objects given their dotted-path, with or without support for colons separating modules/filepaths from attributes, so that plugins and extensions can start migrating. Then MkDocs could start emitting messages (debug, then info, then warning level) when
!!-Python-tags are used (can be done by simply iterating on the loaded contents to find non-builtin objects), advertising again its own API to load objects from their paths. Finally, we would properly deprecate support for!!-tags and eventually remove support.This would be a long process though.
pawamoy commentedon Jul 25, 2024
@squidfunk so basically, a Python file defining a few variables with expected names? Something like this?
mkdocstrings config in Python, converted by ChatGPT
Or should MkDocs provide utilities/helpers/classes to make this code less verbose and better typed?
The YAML version is 185 lines long, the Python version is 285 lines long.
A few remarks:
!!-tags and!ENVetc.)@humitos what would RTD think of a Python config file?
My first opinion is that this would have too many disadvantages so I wouldn't vote for supporting Python config files in addition to YAML ones. But I'm open to discussing it more.
humitos commentedon Jul 25, 2024
Speaking as a Read the Docs developer, using a YAML or a Python file for MkDocs configuration would be the same for the Read the Docs build process. We are now doing nothing regarding the MkDocs configuration behind the scenes since April, 2024: https://about.readthedocs.com/blog/2024/03/mkdocs-yaml-manipulation/
humitos commentedon Jul 25, 2024
Now, speaking just as a developer related to the documentation world.
@waylan I'm not sure to understand what would be the benefits for this approach compared with just defining the same directory as
PYTHONPATHenvironment variable at runtime. Could you expand on that?@squidfunk Sphinx does this already by using a
conf.pyand this comes with lot of flexibility but lot of disadvantages as well. In fact, on of the features people appreciate the most from Jupyter Book is they built a layer on top of Sphinx that uses a_config.ymlfile 😄 : https://jupyterbook.org/en/stable/customize/config.htmlThere is a lot of discussion about YAML vs TOML vs Python files in Sphinx in this issue sphinx-doc/sphinx#9040 that I remember discussing some time ago and may worth to keep in mind for this topic.
@pawamoy I agree with you. I think it will bring a lot more disadvantages than benefits at this point.
pawamoy commentedon Jul 25, 2024
OP explicitly stated that using
PYTHONPATHis not ergonomic (different CLI commands or environment setup depending on the system and user). AlsoPYTHONPATHrequires absolute paths, while MkDocs could allow paths relative to the config file, making things easier again for writing docs across different systems/environments.pawamoy commentedon Jul 25, 2024
It looks like the conversation in Sphinx's issue tracker gravitates towards "static config by default, allow customization with dynamic config", which is exactly what we can get with hooks, as mentioned in my first comment here 🙂 By the way, hooks even allow dynamically adding extensions or plugins to the config, so I think this is solved. People interested in static vs. dynamic are free to open a new discussion 🙂 Lets try to answer the initial question here.
pawamoy commentedon Jul 25, 2024
@eliemichel can you tell us what you think of using hooks? Write them once, and your contributors can run
mkdocs serveas usual.To be clear, I mean altering
sys.pathinon_startupif you need to pass the path of an object as a string, and altering the config inon_configif you need to configure extensions that only accept objects as values, not strings.squidfunk commentedon Jul 25, 2024
Good point 😅 It boils down to how much additional logic one wants to add to a standard format like YAML, TOML, JSON that needs extra care instead of saying: you can always do it programmatically, if you need more control. JS is closer to JSON, essentially scriptable JSON, which might explain the gravitation towards this approach in this ecosystem.
squidfunk commentedon Jul 25, 2024
AFAIK, hooks, specifically
on_config, are executed post-config validation. This might be too late for some cases.humitos commentedon Jul 25, 2024
Would it be enough to add a new hook that is
pre_on_config(or similar) to solve this?Another approach could be to add
priority=to these hook. Sphinx follows this pattern, so you can doapp.connect("config-inited", first, priority=10)andapp.connect("config-inited", second, priority=50). This will result in callingfirstand thensecondcallbacks in order: https://www.sphinx-doc.org/en/master/extdev/appapi.html#sphinx.application.Sphinx.connectsquidfunk commentedon Jul 25, 2024
A hook can be assigned a priority via
event_priority, but the config is parsed before any of the hooks is invoked.mkdocs/mkdocs/__main__.py
Lines 281 to 286 in 62a4e3c
... except for
on_startup, which only discerns the mode of invocation, nothing more.squidfunk commentedon Jul 25, 2024
@pawamoy my goal was to try thinking outside the box and to pull in adjacent problems that often help me (at least) to think about the bigger picture here. I'm not sure what Tom, the new lead maintainer of this project, has in mind for the future, but configuration is a frequent topic that is still unsolved, so I think we should discuss it. MkDocs has no programmatic API and only allows for very limited dynamic interaction with configuration files. Configuration inheritance and YAML tags (which @waylan vouches for removing) only solves a fraction of known problems.
waylan commentedon Jul 26, 2024
Correct. As a reminder, we need to have already parsed the config to know which extensions to load. As hooks are implemented by extensions, there would be no way to use hooks to alter the config parser's behavior. Even the
on_startuphook runs after loading the config (despite what the docs indicate... that might need looking into; did the code change and no longer matches the docs, or have the docs always been wrong?) Therefore, I do not see hooks as a viable solution.This is an interesting suggestion and something that I considered briefly. I have had a desire for this from time to time over the years. Ultimately, however, I don't think it makes sense for MkDocs. MkDocs is used to document a lot of non-Python projects and based on some reports we've received over the years, some users don't realize that it is implemented in Python and have never used Python before. Moving to a Python config would be a drastic change in the scope of what MkDocs is. Personally, I would be happy to use that tool, but that is not what most of MkDocs' users signed up for. Of course, supporting both types of config files reduces that concern, but also complicates things with additional documentation, support and maintenance. I'm not sure the cost justifies the gains. Various other concerns have already been addressed in other comments so I'm not going to comment further on this.
Thanks @pawamoy, you covered that well. Also, thanks for the clear answers (in this comment) to the questions I raised. You made good points and raised a few concerns I hadn't considered. I agree with your assessment.
To be clear, I am not advocating for dropping support. However, there have been comments from some individuals over the years who have taken this position. Personally I have been neutral on this issue. I was simply saying that if that was the way McDocs wanted to go, then this would be a potential path to do that. However, I am in no way saying that I think MkDocs should move in that direction. In fact, that is why I proposed a solution which continues to support them.
pawamoy commentedon Jul 28, 2024
To be more clear, I meant to use
on_startupto add your scripts folder tosys.pathwhen the target extension/plugin supports loading objects given a string identifying them (such as Python-Markdown supporting extension paths as strings). Even if the hook is executed after the config is loaded, I believe Markdown extensions passed as strings are loaded after the config validation, so at that time Python-Markdown will be able to find your Python modules becausesys.pathwas altered.I also meant to use
on_configto programmatically add extensions and their configuration to the main config when they don't support loading objects from strings. For this you'd completely remove the extension/plugin that doesn't support loading objects given strings frommkdocs.yml, and add it from a hook instead. Something like this (probably not 100% correct):This way you can effectively declare most of your config statically, and use hooks to declare the rest dynamically. To me it even looks like we could declare almost all config through hooks, allowing config dependent on the environment, system, etc. Could be interesting to actually try that and report back.
Ideally MkDocs would provide a friendly API to configure everything.