Rework style loading - #164
Conversation
| def get(self, names): | ||
| if isinstance(names, str): | ||
| names = [names] | ||
|
|
||
| # Update dictionary of styles - plt.style.library | ||
| plt.style.core.update_nested_dict(plt.style.library, stylesheets) | ||
| # Update `plt.style.available`, copy-paste from: | ||
| # https://github.com/matplotlib/matplotlib/blob/a170539a421623bb2967a45a24bb7926e2feb542/lib/matplotlib/style/core.py#L266 # noqa: E501 | ||
| plt.style.core.available[:] = sorted(plt.style.library.keys()) | ||
| for name in names: | ||
| if name not in self.stylesheets: | ||
| raise ValueError(f"'{name}' is not a known SciencePlots style") | ||
|
|
||
| return [self.stylesheets[name] for name in names] |
There was a problem hiding this comment.
This currently throws a hard error on unrecognized styles, so we can't do something like
plt.style.use(scienceplots.styles(["dark_background", "science"]))
| # register the bundled stylesheets in the matplotlib style library | ||
| scienceplots_path = scienceplots.__path__[0] | ||
| styles_path = os.path.join(scienceplots_path, "styles") | ||
| class StyleRegistry: |
There was a problem hiding this comment.
This class is intentionally pretty empty. We can try to mirror some of the matplotlib API to shorten some calls, i.e. add some
scienceplots.styles.use([...])
scienceplots.styles.context([...])Personally, I set the styles at the start of my scripts, so it doesn't matter much if it's a bit more verbose.
|
|
|
Thanks for the PR. May I know if any of it was generated with AI? It doesn't look like it but I prefer to know it so I can focus on what must be double-checked. In any case, I may pursue a more opinionated path. |
Nope, no AI, but it was only tested on Arch with matplotlib 3.11 and Python 3.14, so it would definitely need some careful checks on that side. |
This implements the changes discussed in #163. Namely,
read_styles_in_foldersto just useimportlib.resourcesto find the styles and make a dict of them.StyleRegistrything that users can call to load style usingscienceplotsessentially no longer depends onmatplotlibdirectly!As expected, this is completely breaking, since it no longer automatically loads the styles and adds them to
matplotlib's registry. Unfortunately, the public style API doesn't offer any way to "register" new styles by name, so this seems to be the most "future proof" option.Fixes #163