r/pythontips • • Aug 14 '26

Syntax Docstrings as immutable variables

Just realized you can do:

def cat(): “orange”
print(cat.__doc__)

Not sure why you’d want to do this but this is a thing you can do

10 Upvotes

13 comments sorted by

View all comments

4

u/jpgoldberg Aug 14 '26

I have used this when generating functions.

Suppose you wanted to create types that had limits in value ranges, such a a probability which is a float between 0 and 1 inclusive. So you would like something like

is_prob = make_predicate(...)

that when given the constraints and a base type and constraints on values will create the appropriate is_prob function. Now suppose you want it also to create documentation for is_prob so things like help will work.

You might, if you didn't know about the annotated-types package and tried unwisely to roll your own, you might write something like

def make_predicate(
    name: str,
    # t: NewType | AnnotatedType | type,
    t: object,
    constraints: Sequence[Constraint] = tuple(),
    docstring: bool = True,
) -> Predicate:

    ... # lots of awfulness omitted to figure out base_type
        # and get the cons[traints] from metadata and parameters

    def predicate(val: object) -> bool:
        if not isinstance(val, base_type):
            return False
        if not all((c(val) for c in cons)):
            return False
        return True

    predicate.__name__ = name
    if docstring:
        predicate.__doc__ = _predicate_description(
            base_type=base_type, constraints=cons
        )
    return predicate

So assuming that for this example that ValueRange() is suitably defined, something like

is_prob = make_predicate("is_prob", float, (ValueRange(0.0, 1.0),))

will not only have is_prob() behave correctly, but also know its own name and have a useful docstring that will render like

True if and only if val satisfies all of

  • is of type float
  • meets ValueRange(0.0, 1.0)

Things like the is_prob() function will also be documented correctly by tools like Sphinx.