Skip to content

Instantly share code, notes, and snippets.

@RhetTbull
Last active April 18, 2023 23:50
Show Gist options
  • Save RhetTbull/47366e42fd593762e7d28db2ca160b07 to your computer and use it in GitHub Desktop.
Save RhetTbull/47366e42fd593762e7d28db2ca160b07 to your computer and use it in GitHub Desktop.
Python decorator to allow use of f-strings in docstrings (something not normally supported by Python)
"""Simple decorator that applies f-string formatting to docstrings
To use, simply apply `@fmydocstring` to your function
Only global variables are accessible for interpolation.
"""
import functools
def fmydocstring(func):
"""Simple decorator to treat docstrings as f-strings"""
func.__doc__ = eval(f'f"""{func.__doc__}"""',
globals()) if func.__doc__ is not None else None
@functools.wraps(func)
def func_wrapper(*args, **kwargs):
return func(*args, **kwargs)
return func_wrapper
# Try it out!
DESCRIPTION = "great!"
@fmydocstring
def my_cool_docstring():
"""My docstring is {DESCRIPTION}, also, {2+2=}
Args: None
Returns: None
"""
...
@fmydocstring
def no_docstring():
# works correctly if there is no docstring
...
@fmydocstring
def empty_docstring():
""""""
# works fine on empty docstrings too
...
@fmydocstring
class Foo:
"""My class docstrings is {DESCRIPTION}
Applying @fmydocstring to the class does not automatically decorate all class methods...yet
"""
@fmydocstring
def bar(self):
"""This is a {DESCRIPTION} class method"""
if __name__ == "__main__":
print(my_cool_docstring.__doc__)
assert (no_docstring.__doc__ is None)
assert (empty_docstring.__doc__ == "")
print(Foo.__doc__)
print(Foo.bar.__doc__)
@RhetTbull
Copy link
Author

Play with this code in repl.it here

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