Get the last Doc() in an annotated type or the docstring of an object.
(obj: Any)
| 76 | |
| 77 | |
| 78 | def get_doc(obj: Any) -> str | None: |
| 79 | """Get the last Doc() in an annotated type or the docstring of an object.""" |
| 80 | if annotated := get_meta(obj, typing_extensions.Doc): |
| 81 | return annotated.documentation |
| 82 | |
| 83 | # Avoid getting docs from builtins. |
| 84 | # We're only interested in things we decorate. |
| 85 | if inspect.getmodule(obj) == builtins or ( |
| 86 | not inspect.isclass(obj) and not inspect.isroutine(obj) |
| 87 | ): |
| 88 | return None |
| 89 | |
| 90 | # Don't look in base classes (otherwise just use inspect.get_doc). |
| 91 | try: |
| 92 | doc = obj.__doc__ |
| 93 | except AttributeError: |
| 94 | return None |
| 95 | if not isinstance(doc, str): |
| 96 | return None |
| 97 | |
| 98 | # By default, a dataclass's __doc__ will be the signature of the class, |
| 99 | # not None. |
| 100 | if ( |
| 101 | doc |
| 102 | and dataclasses.is_dataclass(obj) |
| 103 | and doc.startswith(f"{obj.__name__}(") |
| 104 | and doc.endswith(")") |
| 105 | ): |
| 106 | return None |
| 107 | |
| 108 | return inspect.cleandoc(doc) |
| 109 | |
| 110 | |
| 111 | def get_ignore(obj: Any) -> list[str] | None: |