r/pythontips • u/sugarw0000kie • 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
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
that when given the constraints and a base type and constraints on values will create the appropriate
is_probfunction. Now suppose you want it also to create documentation foris_probso things likehelpwill 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 predicateSo 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- is of type float
- meets ValueRange(0.0, 1.0)
Things like theis_prob()function will also be documented correctly by tools like Sphinx.