Skip to content

fmt_docstring: Allow raw curly braces {} to avoid KeyError #3815

Closed

Description

@seisman

Description of the desired feature

The @fmt_docstring decorator is responsible for inserting common docstrings into placeholders. While it works well in general, it currently raises a KeyError when encountering an undefined placeholder. For example, in #3811, we're writing equations in ReST syntax:

:math:`mantissa * 10 ^ {exponent}`

and it reports KeyError: exponent because we don't have exponent defined in COMMON_DOCSTRINGS. This requires us to escape such placeholders by writing the equation like

:math:`mantissa * 10 ^ {{exponent}}`

which is inconvenient, and sometimes we may forget to do it and then see the KeyError exception surprisingly.

Current Behavior:

  • If {exponent} (or any other undefined placeholder) appears in a docstring, fmt_docstring raises a KeyError.
  • To work around this, users must write {{exponent}} to ensure the curly braces are preserved in the final docstring.

Expected Behavior:

  • {exponent} (or any other undefined placeholder) should be treated as a literal string unless it matches a defined common docstring key.
  • When writing docstrings, we don't have to manually escape curly braces unless explicitly required.

Pros

  1. No need to escape curly braces, especially for equations
  2. The raw docstrings, especially math equations, are more readable

Cons

If there are any typos in common placeholder (e.g., projection typed as projecti), then the literal string {projecti} is shown in the HTML documentation. It no longer raises a KeyError exception, and we may miss the typo.

Are you willing to help implement and maintain this feature?

Yes

Activity

  1. added
    discussions
    on Feb 18, 2025
  2. seisman commented on Feb 25, 2025

    @seisman
    MemberAuthor

    @GenericMappingTools/pygmt-maintainers Any comments on this?

  3. weiji14 commented on Mar 2, 2025

    @weiji14
    Member

    Yeah, it would be nice to write LaTeX style math equations directly without the double curly braces {{ }}. It's not just ReST syntax, but also MyST that uses it - https://mystmd.org/guide/math.

    Sphinx does support substitutions via a | | syntax for ReST - https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html#substitutions, that might be coming to MyST in some form - jupyter-book/mystmd#852. Maybe we can consider using this built-in method than complicating the @fmt_docstring decorator function further? But it will involve a lot of rewriting of the docstrings to do { } -> | | for the aliases.

  4. seisman commented on Mar 3, 2025

    @seisman
    MemberAuthor

    Using substitutions | | sounds an interesting idea. As far as I know, substituions don't support multi-paragraph long texts, so it may not work as expected.

  5. added
    maintenance
    and removed
    discussions
    on Nov 15, 2025
  6. added this to the 0.18.0 milestone on Nov 15, 2025
  7. seisman commented on Nov 15, 2025

    @seisman
    MemberAuthor

    I'm working on this issue in PR #4210.

    Initially, I considered using Python's str.format_map, since it supports missing keys via a custom __missing__ method. However, it does not support nested curly braces, which appear frequently in LaTeX equations. For example:

    >>> class _MyDict(dict):
    >>>     def __missing__(self, key):
    >>>        return "{" + key + "}"
    >>> doc1 = "{projection} x^{y+z}"
    >>> doc2 = "{projection} x^{y+z}} x^{y+x^{y+z}}"
    
    >>> doc1.format_map(_MyDict({"projection": "Mercator"}))
    'Mercator x^{y+z}'
    
    >>> doc2.format_map(_MyDict({"projection": "Mercator"}))
    --------------------------------------------------------------------------
    ValueError                               Traceback (most recent call last)
    Cell In[13], line 1
    ----> 1 doc2.format_map(_MyDict({"projection": "Mercator"}))
    
    ValueError: Single '}' encountered in format string

    The second example fails because .format_map() doesn't allow '{' in field name.

    After exploring alternatives, I found that Python's string.Template works well for this use case:

    >>> from string import Template
    
    >>> doc1 = "$projection x^{y+z}"
    >>> doc2 = "$projection x^{y+z}} x^{y+x^{y+z}}"
    
    >>> Template(doc1).safe_substitute({"projection": "Mercator"})
    'Mercator x^{y+z}'
    
    >>> Template(doc2).safe_substitute({"projection": "Mercator"})
    'Mercator x^{y+z}} x^{y+x^{y+z}}'

    In string.Template, $ marks the placeholder, so curly braces (nested or not) remain intact while placeholders can still be safely substituted.

    I think string.Template is the best approach. To adopt it, we need to make two changes:

    1. Convert all placeholders from {projection} to either ${projection} or $projection (I prefer $projection for its simplicity).
    2. Replace all occurrences of {{ and }} in LaTeX equations with plain { and }.

    This ensures that math equations are clean, substitution is safe, and no KeyError or ValueError occurs.

    Comments?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    maintenance

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions