API reference

Everything below is rendered from docshare’s own docstrings, which are NumPy style — the format this library reads.

Composing

docshare.docwrap(obj=None, /, **options)[source]

Compose an object’s documentation from itself and its sources.

The decorator may be used bare, when it only parses and validates the documentation, or called with arguments describing what to inherit. Documentation the object provides for itself is always kept; a source fills only what the object leaves out.

Parameters:
  • obj (object, optional) – The object to document. This is supplied by Python when the decorator is used bare, and may be given directly to compose an object’s documentation outside a decorator expression.

  • format (str, optional) – The format the object’s own docstring is written in. The default detects it, which is not possible for an object that has no docstring of its own.

  • render (str, optional) – The format the composed documentation is written in. The default is format, or the detected format when format was not given, so that a docstring is normally written back in the style it was written in. Giving render on its own says how to write an object that has no docstring to detect a format from; giving both converts a document from one format into the other.

  • inherit (mapping, optional) – The generalized form, mapping a section name to its sources, as in inherit={'Parameters': other}.

  • inheritall (object or sequence, optional) – Inherit every recognized section the sources document, along with their summary and description.

  • inheritsummary (object or sequence, optional) – Inherit the sources’ summary, which is otherwise never inherited. This is implied by inheritall.

  • inheritdescription (object or sequence, optional) – Inherit the sources’ description — the prose between the summary and the first section — which is otherwise never inherited. This is implied by inheritall.

  • inheritother (sequence or bool, optional) – Inherit unrecognized sections, which are never inherited otherwise. Give (source, 'Section Name') pairs, or True alongside inheritall to take every unrecognized section the sources have.

  • extraparam (str or sequence of str, optional) – Parameters documented deliberately although the signature does not name them, typically because they are taken from **kwargs.

  • custom (mapping, iterable of str, or str, optional) –

    Sections this object’s documentation has beyond the ones docshare recognizes. Each title either names the recognized section it resembles, borrowing how its body is read, or is given alone, which recognizes the title as a section and leaves its body uninterpreted. Nothing is registered: what one call declares cannot change how anything else is read.

    A declared section is addressed as inheritcustom and its companions, and, when its title is a Python name, by arguments generated from it exactly as for a recognized section: Inputs offers inheritinputs, ignoreinputs, and inputmap.

  • sourcecustom (bool, object, sequence, or mapping, optional) – Which sources share the declaration. A source named by an argument that names a declared section is read with that section already, since the argument means nothing otherwise; this is for the arguments that name no section, above all inheritall. Give True for every source, one or more sources for all of the declaration, or a mapping from a declared title to the sources it applies to.

  • sourceformat (str or mapping, optional) – The format a source is written in, for a docstring whose format cannot be detected. Give one format for every source, or a mapping from a format to the sources written in it. There is no default: a source’s format is detected, so that inheriting across the two formats keeps working.

  • inheritcustom (mapping, optional) – Inherit declared sections, as {'Inputs': source}. Every declared section can be addressed this way, including one whose title is not a Python name and one declared without a kind.

  • ignorecustom (mapping, optional) – Exclude items of a declared section from inheritance, as {'Inputs': 'x'}. A declared section is driven by its sources, so this names one of theirs.

  • custommap (mapping, optional) – Rename items of a declared section, as {'Inputs': {'data': 'x'}}.

  • **options – Per-section arguments. Every section accepts inherit<short>, and every section holding items also accepts <singular>map and an exclusion. A section documenting the callable’s parameters is driven by the signature, so its exclusion names one of the target’s own parameters and is called drop<short>: inheritparams, dropparams, and parammap. Every other section is driven by its sources, so its exclusion names one of the source’s items and is called ignore<short>: inheritreturns, ignorereturns, and returnmap.

Returns:

object – The object itself, with its __doc__ replaced when anything was composed, or a decorator when obj was not given.

Raises:
  • DocShareError – If an argument is not recognized or is given in two places.

  • DocFormatError – If the format is unsupported, cannot be detected, or is needed for rendering and was not given.

  • DocSignatureError – If the documentation describes a parameter the object does not have.

  • DocInheritanceError – If the requested inheritance is incoherent.

  • DocMappingError – If a mapping or a bound source is invalid.

docshare.doccompose(obj, /, **options)[source]

Compose documentation without decorating anything.

This is docwrap with nothing to install the result on: it reads the documentation given, performs the inheritance the arguments ask for, and returns the composed Document rather than replacing an object’s __doc__. The documentation given is parsed afresh, so nothing is read from or written to the cache; a source is still read through docinfo, as it is for docwrap.

Parameters:
  • obj (str, object, or Document) – The documentation to compose. A string is taken to be documentation rather than to have any; an object is documented by its __doc__, and its signature orders and validates the documentation; an already-parsed Document is composed as it stands. A string or a Document has no signature, so no validation is attempted and a section of parameters is ordered by the documentation itself and its sources.

  • **options – Any argument docwrap accepts, meaning the same thing there. See docwrap for the vocabulary.

Returns:

Document – The composed document: the target’s own documentation, with whatever its sources supplied for what it left out. When no inheritance was asked for, it is the documentation as parsed.

Raises:
docshare.docrender(obj, /, **options)[source]

Compose and render documentation without decorating anything.

This is docwrap with nothing to install the result on: it reads the documentation given, performs the inheritance the arguments ask for, and returns the rendered docstring rather than replacing an object’s __doc__. The result is ordinary documentation text, suitable for assignment to a __doc__ or for any other use.

Rendering normalizes presentation — indentation, the blank lines between sections, and the spelling of a recognized section’s title — so the result is not always identical to the documentation given, even when nothing was inherited. Like doccompose, it parses the documentation afresh and writes nothing to the cache.

Because it assigns nothing, docrender also works on objects whose __doc__ cannot be written — a class, a property, a classmethod — where docwrap reports an error.

Parameters:
  • obj (str, object, or Document) – The documentation to compose and render, as doccompose accepts it. An object’s signature orders and validates the documentation; a string or a Document has no signature, so no validation is attempted and a section of parameters is ordered by the documentation itself and its sources.

  • **options – Any argument docwrap accepts, meaning the same thing there. See docwrap for the vocabulary.

Returns:

str – The composed documentation, rendered in render when that was given, and otherwise in the format the documentation itself is written in.

Raises:
  • DocShareError – If obj is None, or an argument is not recognized or is given in two places.

  • DocFormatError – If the format is unsupported, cannot be detected, or is needed for rendering and was not given.

  • DocInheritanceError – If the requested inheritance is incoherent.

  • DocMappingError – If a mapping or a bound source is invalid.

Reading

docshare.docparse(obj, *, format=None, custom=None)[source]

Parse an object’s current documentation from scratch.

This never consults the cache and never populates it. Use docinfo for the cached form.

Parameters:
  • obj (object) – The documented object, or a docstring to parse directly.

  • format (str, optional) – The format the documentation must be written in. When this is None, the default, the format is detected from the document.

  • custom (mapping, iterable of str, or str, optional) – Sections to recognize beyond the ones docshare knows. A mapping gives each title the recognized section it resembles, whose reading it borrows; a title given without one is recognized as a section and otherwise left uninterpreted.

Returns:

Document – The parsed document. An object whose documentation is None or empty yields an empty document rather than an error.

Raises:
  • DocFormatError – If format is unsupported, if the documentation does not conform to an explicitly requested format, or if the format cannot be detected.

  • DocParseError – If the documentation cannot be read as the format requires.

docshare.docinfo(obj, *, format=None, custom=None)[source]

Return the documentation information associated with an object.

When nothing is recorded for the object’s documentation, it is parsed with docparse and the result is recorded before being returned. When something is recorded, it is returned as it stands.

Parameters:
  • obj (object) – The documented object, or a docstring to parse directly.

  • format (str, optional) – The format to parse with, used only if parsing actually has to happen. It is not a request to convert anything: the document representation does not depend on the format it was written in, and a recorded document is returned whatever this says.

  • custom (mapping, iterable of str, or str, optional) – Sections to recognize beyond the ones docshare knows, as docparse accepts them. Unlike format, this is part of what the record is of: the same text read under two declarations is two different documents, so each is recorded separately.

Returns:

Document – The document associated with obj.

Raises:
docshare.clear_docinfo(obj=None)[source]

Forget recorded documentation.

Parameters:

obj (object, optional) – The object whose documentation should be forgotten, in every format it may have been read as. The default forgets everything, which is chiefly useful in tests.

Returns:

None

The document model

class docshare.Document(summary=None, description=(), sections=(), format=None, meta=FrozenDict({}))[source]

Bases: object

The semantic representation of a parsed docstring.

Variables:
  • summary (str or None) – The one-line summary that opens the document, if there is one.

  • description (tuple of str) – The lines of descriptive prose between the summary and the first section.

  • sections (tuple of Section) – The document’s sections, in document order. Order is significant and is always preserved.

  • format (str or None) – The format the document was parsed from, or None when no format is known, as for a document built entirely from inherited sections.

  • meta (FrozenDict) – Format-specific information retained for faithful rendering.

summary
description
sections
format
meta
property empty

Whether the document has no documentation at all (bool).

section(key)[source]

Return the first section matching key, or None.

Parameters:

key (str) – A section kind such as 'parameters', or a section title such as 'Parameters', 'Args', or 'Efferents'. Recognized titles match by kind, so that a document written in either supported format answers to either spelling; an unrecognized title matches an opaque section by name, ignoring case.

Returns:

Section or None – The first matching section in document order, or None if the document has no such section.

iter_sections(key)[source]

Iterate over every section matching key, in document order.

Parameters:

key (str) – A section kind or title, as accepted by Document.section.

Yields:

Section – Each matching section.

evolve(**changes)[source]

Return a copy of this document with the given fields replaced.

Parameters:

**changes – The fields to replace.

Returns:

Document – The updated copy.

class docshare.Section(name, kind=None, items=(), text=(), meta=FrozenDict({}), custom=None)[source]

Bases: object

A single section of a document.

A section whose title docshare recognizes has a Section.kind and, if that kind is structured, a sequence of Item objects. A section whose title is not recognized is opaque: its body is preserved verbatim in Section.text and is never interpreted.

Variables:
  • name (str) – The section title as it appears in the document, such as 'Parameters', 'Args', or 'Efferents'.

  • kind (str or None) – The normalized kind of the section, such as 'parameters', or None if the section is opaque.

  • items (tuple of Item) – The structured items of the section, in document order.

  • text (tuple of str) – The section’s prose. For an opaque section this is the entire body; for a structured section it is any text preceding the items.

  • meta (FrozenDict) – Format-specific information retained for faithful rendering.

  • custom (SectionKind or None) – The declared kind this section is an instance of, for a section the caller declared rather than one docshare recognizes. The kind travels with the section so that the document remains self-describing: it can be rendered, inherited from and validated without the caller supplying the declaration again.

name
kind
items
text
meta
custom
property spec

The kind this section is an instance of (SectionKind or None).

This is the declared kind for a section the caller declared, the registered one for a section docshare recognizes, and None for an opaque section. Everything that has to know how a section behaves reads it here rather than from the registry, so that a declared section behaves the same way wherever its document travels.

property opaque

Whether this section is preserved uninterpreted (bool).

property structured

Whether this section’s body consists of items (bool).

evolve(**changes)[source]

Return a copy of this section with the given fields replaced.

Parameters:

**changes – The fields to replace.

Returns:

Section – The updated copy.

class docshare.Item(names=(), type=None, description=(), meta=FrozenDict({}))[source]

Bases: object

A single structured documentation item.

An item is one entry in a structured section: a documented parameter, a return value, a raised exception, and so on. An item may document more than one name at once, as in the NumPy declaration x, y : float; such an item is a group, and docshare keeps it intact.

Variables:
  • names (tuple of str) – The names this item documents. This is empty for an item that has no name, such as an unnamed return value.

  • type (str or None) – The documented type, retained verbatim as text. docshare never interprets this as a Python type expression.

  • description (tuple of str) – The lines of the item’s description, with common indentation removed.

  • meta (FrozenDict) – Format-specific information retained so that the item can be rendered faithfully.

names
type
description
meta
property grouped

Whether this item documents more than one name (bool).

property name

The single name of this item (str or None).

This is None for an unnamed item and for a group, which has no single name; use Item.names for those.

evolve(**changes)[source]

Return a copy of this item with the given fields replaced.

Parameters:

**changes – The fields to replace.

Returns:

Item – The updated copy.

class docshare.FrozenDict(data=(), /, **kwargs)[source]

Bases: Mapping

An immutable, hashable mapping.

FrozenDict is used for the metadata attached to the records in this module, so that those records remain immutable and hashable as a whole. It behaves like an ordinary read-only mapping in every other respect.

Parameters:
  • data (mapping or iterable of tuple, optional) – The initial contents, as accepted by dict.

  • **kwargs – Additional entries, as accepted by dict.

Sections

class docshare.SectionKind(name, structured, identity, titles, aliases, merges, placeholder)[source]

Bases: object

A documentation section that docshare understands semantically.

Variables:
  • name (str) – The normalized name of the kind, such as 'parameters'.

  • structured (bool) – Whether the section body consists of discrete documentation items rather than prose.

  • identity (str or None) – How items in this section are identified during inheritance; one of IDENTITY_NAME, IDENTITY_NAME_OR_INDEX, or IDENTITY_TYPE_OR_INDEX. This is None for prose sections.

  • titles (Mapping[str, str]) – The canonical title of this section in each supported format.

  • aliases (tuple of str) – The normalized titles that map onto this kind.

  • merges (Mapping[str, str]) – The kind this one is merged into when rendered in a given format, for formats that have no section of their own for it. Formats absent from this mapping render the section under its own title.

  • placeholder (str or None) – The type to write when an item of this section has a description but no type. NumPy style requires a type for every item of a section identified by position, so one has to be supplied; the least specific type of the relevant hierarchy says no more than the author did. This is None for a section that needs no such type.

name
structured
identity
titles
aliases
merges
placeholder
docshare.section_kind(title)[source]

Return the SectionKind for a section title, if it is recognized.

Parameters:

title (str) – The section title as it appears in a docstring, or a normalized kind name such as 'see_also'.

Returns:

SectionKind or None – The matching kind, or None if the title is not semantically recognized and must therefore be treated as opaque.

docshare.SUPPORTED_FORMATS = ('google', 'numpy')

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable’s items.

If the argument is a tuple, the return value is the same object.

The cache

class docshare.DocCache(maxsize=2048)[source]

Bases: MutableMapping

A bounded cache of parsed documentation.

The cache behaves as an ordinary mutable mapping from a (format, custom, docstring) triple to the Document it parses to, discarding the least recently used entry when it grows past DocCache.maxsize. The format is the one that was asked for, so it is None for a request that let the format be detected, and custom is the normalized declaration of sections the request added, or None.

An instance of this class is exposed as docshare.doccache. It is public so that it can be inspected, cleared, resized, or pre-loaded, all of which have legitimate uses; it is nonetheless the library’s own working state, and putting a document into it that does not correspond to its key will produce documentation that does not correspond to anything.

A key is a (format, custom, documentation) triple, checked on every access. A dictionary would accept a bare docstring as a key without complaint, store it, and never read it again; checking turns that into an error where it happens rather than a cache that is quietly wrong.

Every operation is atomic with respect to other threads. Looking an entry up also marks it as recently used, and discarding entries walks the whole cache, so neither is a single dictionary operation and neither would be safe unsynchronized. Iteration, and the views built on it, work from a snapshot, so another thread may add or discard entries while one is being walked without either interfering with the other.

Parameters:

maxsize (int, optional) – The number of entries to keep; the default is DEFAULT_MAXSIZE. A value of zero disables caching.

property maxsize

The number of entries kept before the oldest is discarded (int).

Lowering this discards the least recently used entries at once.

clear()[source]

Discard every entry.

Returns:

None

items()[source]

Return the cache’s entries as a snapshot.

Returns:

tuple of (str, Document) – The entries at the moment of the call, oldest first.

values()[source]

Return the cached documents as a snapshot.

Returns:

tuple of Document – The documents at the moment of the call, oldest first.

keys()[source]

Return the cached documentation as a snapshot.

Returns:

tuple of str – The keys at the moment of the call, oldest first.

docshare.doccache

A bounded cache of parsed documentation.

The cache behaves as an ordinary mutable mapping from a (format, custom, docstring) triple to the Document it parses to, discarding the least recently used entry when it grows past DocCache.maxsize. The format is the one that was asked for, so it is None for a request that let the format be detected, and custom is the normalized declaration of sections the request added, or None.

An instance of this class is exposed as docshare.doccache. It is public so that it can be inspected, cleared, resized, or pre-loaded, all of which have legitimate uses; it is nonetheless the library’s own working state, and putting a document into it that does not correspond to its key will produce documentation that does not correspond to anything.

A key is a (format, custom, documentation) triple, checked on every access. A dictionary would accept a bare docstring as a key without complaint, store it, and never read it again; checking turns that into an error where it happens rather than a cache that is quietly wrong.

Every operation is atomic with respect to other threads. Looking an entry up also marks it as recently used, and discarding entries walks the whole cache, so neither is a single dictionary operation and neither would be safe unsynchronized. Iteration, and the views built on it, work from a snapshot, so another thread may add or discard entries while one is being walked without either interfering with the other.

Parameters:

maxsize (int, optional) – The number of entries to keep; the default is DEFAULT_MAXSIZE. A value of zero disables caching.

Exceptions

exception docshare.DocShareError[source]

Bases: Exception

Base class for all errors raised deliberately by docshare.

exception docshare.DocParseError[source]

Bases: DocShareError

Raised when a docstring cannot be parsed in the requested format.

exception docshare.DocFormatError[source]

Bases: DocShareError

Raised for an invalid, unsupported, or ambiguous documentation format.

This covers a document that does not conform to an explicitly requested format, a document whose format cannot be detected unambiguously, and a composition that must render a document for which no format is known.

exception docshare.DocInheritanceError[source]

Bases: DocShareError

Raised when a requested inheritance operation is incoherent.

This covers partial replacement of a grouped documentation item and inherited items that cannot be assigned a deterministic position in the target document.

exception docshare.DocMappingError[source]

Bases: DocShareError

Raised when an item mapping is invalid.

The parammap and returnmap options, along with the corresponding mappings for other structured sections, raise this when a mapping is malformed or refers to items that do not exist.

exception docshare.DocSignatureError[source]

Bases: DocShareError

Raised when documented parameters disagree with a callable signature.