Debian Codegraph @

docs/peps/pep-0258.rst

raw
1 PEP: 258
2 Title: Docutils Design Specification
3 Version: $Revision: 9906 $
4 Last-Modified: $Date: 2024-08-15 10:43:38 +0200 (Do, 15. Aug 2024) $
5 Author: David Goodger <[email protected]>
6 Discussions-To: <[email protected]>
7 Status: Rejected
8 Type: Standards Track
9 Content-Type: text/x-rst
10 Requires: 256, 257
11 Created: 31-May-2001
12 Post-History: 13-Jun-2001
13
14
15 ================
16 Rejection Notice
17 ================
18
19 While this may serve as an interesting design document for the
20 now-independent docutils, it is no longer slated for inclusion in the
21 standard library.
22
23
24 ==========
25 Abstract
26 ==========
27
28 This PEP documents design issues and implementation details for
29 Docutils, a Python Docstring Processing System (DPS). The rationale
30 and high-level concepts of a DPS are documented in PEP 256, "Docstring
31 Processing System Framework" [#PEP-256]_. Also see PEP 256 for a
32 "Road Map to the Docstring PEPs".
33
34 Docutils is being designed modularly so that any of its components can
35 be replaced easily. In addition, Docutils is not limited to the
36 processing of Python docstrings; it processes standalone documents as
37 well, in several contexts.
38
39 No changes to the core Python language are required by this PEP. Its
40 deliverables consist of a package for the standard library and its
41 documentation.
42
43
44 ===============
45 Specification
46 ===============
47
48 Docutils Project Model
49 ======================
50
51 Project components and data flow::
52
53 +---------------------------+
54 | Docutils: |
55 | docutils.core.Publisher, |
56 | docutils.core.publish_*() |
57 +---------------------------+
58 / | \
59 / | \
60 1,3,5 / 6 | \ 7
61 +--------+ +-------------+ +--------+
62 | READER | ----> | TRANSFORMER | ====> | WRITER |
63 +--------+ +-------------+ +--------+
64 / \\ |
65 / \\ |
66 2 / 4 \\ 8 |
67 +-------+ +--------+ +--------+
68 | INPUT | | PARSER | | OUTPUT |
69 +-------+ +--------+ +--------+
70
71 The numbers above each component indicate the path a document's data
72 takes. Double-width lines between Reader & Parser and between
73 Transformer & Writer indicate that data sent along these paths should
74 be standard (pure & unextended) Docutils doc trees. Single-width
75 lines signify that internal tree extensions or completely unrelated
76 representations are possible, but they must be supported at both ends.
77
78
79 Publisher
80 ---------
81
82 The ``docutils.core`` module contains a "Publisher" facade class and
83 several convenience functions: "publish_cmdline()" (for command-line
84 front ends), "publish_file()" (for programmatic use with file-like
85 I/O), and "publish_string()" (for programmatic use with string I/O).
86 The Publisher class encapsulates the high-level logic of a Docutils
87 system. The Publisher class has overall responsibility for
88 processing, controlled by the ``Publisher.publish()`` method:
89
90 1. Set up internal settings (may include config files & command-line
91 options) and I/O objects.
92
93 2. Call the Reader object to read data from the source Input object
94 and parse the data with the Parser object. A document object is
95 returned.
96
97 3. Set up and apply transforms via the Transformer object attached to
98 the document.
99
100 4. Call the Writer object which translates the document to the final
101 output format and writes the formatted data to the destination
102 Output object. Depending on the Output object, the output may be
103 returned from the Writer, and then from the ``publish()`` method.
104
105 Calling the "publish" function (or instantiating a "Publisher" object)
106 with component names will result in default behavior. For custom
107 behavior (customizing component settings), create custom component
108 objects first, and pass *them* to the Publisher or ``publish_*``
109 convenience functions.
110
111
112 Readers
113 -------
114
115 Readers understand the input context (where the data is coming from),
116 send the whole input or discrete "chunks" to the parser, and provide
117 the context to bind the chunks together back into a cohesive whole.
118
119 Each reader is a module or package exporting a "Reader" class with a
120 "read" method. The base "Reader" class can be found in the
121 ``docutils/readers/__init__.py`` module.
122
123 Most Readers will have to be told what parser to use. So far (see the
124 list of examples below), only the Python Source Reader ("PySource";
125 still incomplete) will be able to determine the parser on its own.
126
127 Responsibilities:
128
129 * Get input text from the source I/O.
130
131 * Pass the input text to the parser, along with a fresh `document
132 tree`_ root.
133
134 Examples:
135
136 * Standalone (Raw/Plain): Just read a text file and process it.
137 The reader needs to be told which parser to use.
138
139 The "Standalone Reader" has been implemented in module
140 ``docutils.readers.standalone``.
141
142 * Python Source: See `Python Source Reader`_ below. This Reader is
143 currently in development in the Docutils sandbox.
144
145 * Email: RFC-822 headers, quoted excerpts, signatures, MIME parts.
146
147 * PEP: RFC-822 headers, "PEP xxxx" and "RFC xxxx" conversion to URIs.
148 The "PEP Reader" has been implemented in module
149 ``docutils.readers.pep``; see PEP 287 and PEP 12.
150
151 * Wiki: Global reference lookups of "wiki links" incorporated into
152 transforms. (CamelCase only or unrestricted?) Lazy
153 indentation?
154
155 * Web Page: As standalone, but recognize meta fields as meta tags.
156 Support for templates of some sort? (After ``<body>``, before
157 ``</body>``?)
158
159 * FAQ: Structured "question & answer(s)" constructs.
160
161 * Compound document: Merge chapters into a book. Master manifest
162 file?
163
164
165 Parsers
166 -------
167
168 Parsers analyze their input and produce a Docutils `document tree`_.
169 They don't know or care anything about the source or destination of
170 the data.
171
172 Each input parser is a module or package exporting a "Parser" class
173 with a "parse" method. The base "Parser" class can be found in the
174 ``docutils/parsers/__init__.py`` module.
175
176 Responsibilities: Given raw input text and a doctree root node,
177 populate the doctree by parsing the input text.
178
179 Example: The only parser implemented so far is for the
180 reStructuredText markup. It is implemented in the
181 ``docutils/parsers/rst/`` package.
182
183 The development and integration of other parsers is possible and
184 encouraged.
185
186
187 .. _transforms:
188
189 Transformer
190 -----------
191
192 The Transformer class, in ``docutils/transforms/__init__.py``, stores
193 transforms and applies them to documents. A transformer object is
194 attached to every new document tree. The Publisher_ calls
195 ``Transformer.apply_transforms()`` to apply all stored transforms to
196 the document tree. Transforms change the document tree from one form
197 to another, add to the tree, or prune it. Transforms resolve
198 references and footnote numbers, process interpreted text, and do
199 other context-sensitive processing.
200
201 Some transforms are specific to components (Readers, Parser, Writers,
202 Input, Output). Standard component-specific transforms are specified
203 in the ``default_transforms`` attribute of component classes. After
204 the Reader has finished processing, the Publisher_ calls
205 ``Transformer.populate_from_components()`` with a list of components
206 and all default transforms are stored.
207
208 Each transform is a class in a module in the ``docutils/transforms/``
209 package, a subclass of ``docutils.tranforms.Transform``. Transform
210 classes each have a ``default_priority`` attribute which is used by
211 the Transformer to apply transforms in order (low to high). The
212 default priority can be overridden when adding transforms to the
213 Transformer object.
214
215 Transformer responsibilities:
216
217 * Apply transforms to the document tree, in priority order.
218
219 * Store a mapping of component type name ('reader', 'writer', etc.) to
220 component objects. These are used by certain transforms (such as
221 "components.Filter") to determine suitability.
222
223 Transform responsibilities:
224
225 * Modify a doctree in-place, either purely transforming one structure
226 into another, or adding new structures based on the doctree and/or
227 external data.
228
229 Examples of transforms (in the ``docutils/transforms/`` package):
230
231 * frontmatter.DocInfo: Conversion of document metadata (bibliographic
232 information).
233
234 * references.AnonymousHyperlinks: Resolution of anonymous references
235 to corresponding targets.
236
237 * parts.Contents: Generates a table of contents for a document.
238
239 * document.Merger: Combining multiple populated doctrees into one.
240 (Not yet implemented or fully understood.)
241
242 * document.Splitter: Splits a document into a tree-structure of
243 subdocuments, perhaps by section. It will have to transform
244 references appropriately. (Neither implemented not remotely
245 understood.)
246
247 * components.Filter: Includes or excludes elements which depend on a
248 specific Docutils component.
249
250
251 Writers
252 -------
253
254 Writers produce the final output (HTML, XML, TeX, etc.). Writers
255 translate the internal `document tree`_ structure into the final data
256 format, possibly running Writer-specific transforms_ first.
257
258 By the time the document gets to the Writer, it should be in final
259 form. The Writer's job is simply (and only) to translate from the
260 Docutils doctree structure to the target format. Some small
261 transforms may be required, but they should be local and
262 format-specific.
263
264 Each writer is a module or package exporting a "Writer" class with a
265 "write" method. The base "Writer" class can be found in the
266 ``docutils/writers/__init__.py`` module.
267
268 Responsibilities:
269
270 * Translate doctree(s) into specific output formats.
271
272 - Transform references into format-native forms.
273
274 * Write the translated output to the destination I/O.
275
276 Examples:
277
278 * XML: Various forms, such as:
279
280 - Docutils XML (an expression of the internal document tree,
281 implemented as ``docutils.writers.docutils_xml``).
282
283 - DocBook (being implemented in the Docutils sandbox).
284
285 * HTML (XHTML 1.4 transitional implemented as ``docutils.writers.html4css1``).
286
287 * PDF (a ReportLabs interface is being developed in the Docutils
288 sandbox).
289
290 * LaTeX (implemented as ``docutils.writers.latex2e``).
291
292 * Docutils-native pseudo-XML (implemented as
293 ``docutils.writers.pseudoxml``, used for testing).
294
295 * Plain text
296
297 * reStructuredText?
298
299
300 Input/Output
301 ------------
302
303 I/O classes provide a uniform API for low-level input and output.
304 Subclasses will exist for a variety of input/output mechanisms.
305 However, they can be considered an implementation detail. Most
306 applications should be satisfied using one of the convenience
307 functions associated with the Publisher_.
308
309 I/O classes are currently in the preliminary stages; there's a lot of
310 work yet to be done. Issues:
311
312 * How to represent multi-file input (files & directories) in the API?
313
314 * How to represent multi-file output? Perhaps "Writer" variants, one
315 for each output distribution type? Or Output objects with
316 associated transforms?
317
318 Responsibilities:
319
320 * Read data from the input source (Input objects) or write data to the
321 output destination (Output objects).
322
323 Examples of input sources:
324
325 * A single file on disk or a stream (implemented as
326 ``docutils.io.FileInput``).
327
328 * Multiple files on disk (``MultiFileInput``?).
329
330 * Python source files: modules and packages.
331
332 * Python strings, as received from a client application
333 (implemented as ``docutils.io.StringInput``).
334
335 Examples of output destinations:
336
337 * A single file on disk or a stream (implemented as
338 ``docutils.io.FileOutput``).
339
340 * A tree of directories and files on disk.
341
342 * A Python string, returned to a client application (implemented as
343 ``docutils.io.StringOutput``).
344
345 * No output; useful for programmatic applications where only a portion
346 of the normal output is to be used (implemented as
347 ``docutils.io.NullOutput``).
348
349 * A single tree-shaped data structure in memory.
350
351 * Some other set of data structures in memory.
352
353
354 Docutils Package Structure
355 ==========================
356
357 * Package "docutils".
358
359 - Module "__init__.py" contains: class "Component", a base class for
360 Docutils components; class "SettingsSpec", a base class for
361 specifying runtime settings (used by docutils.frontend); and class
362 "TransformSpec", a base class for specifying transforms.
363
364 - Module "docutils.core" contains facade class "Publisher" and
365 convenience functions. See `Publisher`_ above.
366
367 - Module "docutils.frontend" provides runtime settings support, for
368 programmatic use and front-end tools (including configuration file
369 support, and command-line argument and option processing).
370
371 - Module "docutils.io" provides a uniform API for low-level input
372 and output. See `Input/Output`_ above.
373
374 - Module "docutils.nodes" contains the Docutils document tree
375 element class library plus tree-traversal Visitor pattern base
376 classes. See `Document Tree`_ below.
377
378 - Module "docutils.statemachine" contains a finite state machine
379 specialized for regular-expression-based text filters and parsers.
380 The reStructuredText parser implementation is based on this
381 module.
382
383 - Module "docutils.urischemes" contains a mapping of known URI
384 schemes ("http", "ftp", "mail", etc.).
385
386 - Module "docutils.utils" contains utility functions and classes,
387 including a logger class ("Reporter"; see `Error Handling`_
388 below).
389
390 - Package "docutils.parsers": markup parsers_.
391
392 - Function "get_parser_class(parser_name)" returns a parser module
393 by name. Class "Parser" is the base class of specific parsers.
394 (``docutils/parsers/__init__.py``)
395
396 - Package "docutils.parsers.rst": the reStructuredText parser.
397
398 - Alternate markup parsers may be added.
399
400 See `Parsers`_ above.
401
402 - Package "docutils.readers": context-aware input readers.
403
404 - Function "get_reader_class(reader_name)" returns a reader module
405 by name or alias. Class "Reader" is the base class of specific
406 readers. (``docutils/readers/__init__.py``)
407
408 - Module "docutils.readers.standalone" reads independent document
409 files.
410
411 - Module "docutils.readers.pep" reads PEPs (Python Enhancement
412 Proposals).
413
414 - Module "docutils.readers.doctree" is used to re-read a
415 previously stored document tree for reprocessing.
416
417 - Readers to be added for: Python source code (structure &
418 docstrings), email, FAQ, and perhaps Wiki and others.
419
420 See `Readers`_ above.
421
422 - Package "docutils.writers": output format writers.
423
424 - Function "get_writer_class(writer_name)" returns a writer module
425 by name. Class "Writer" is the base class of specific writers.
426 (``docutils/writers/__init__.py``)
427
428 - Package "docutils.writers.html4css1" is a simple HyperText
429 Markup Language document tree writer for HTML 4.01 and CSS1.
430
431 - Package "docutils.writers.pep_html" generates HTML from
432 reStructuredText PEPs.
433
434 - Package "docutils.writers.s5_html" generates S5/HTML slide
435 shows.
436
437 - Package "docutils.writers.latex2e" writes LaTeX.
438
439 - Package "docutils.writers.newlatex2e" also writes LaTeX; it is a
440 new implementation.
441
442 - Module "docutils.writers.docutils_xml" writes the internal
443 document tree in XML form.
444
445 - Module "docutils.writers.pseudoxml" is a simple internal
446 document tree writer; it writes indented pseudo-XML.
447
448 - Module "docutils.writers.null" is a do-nothing writer; it is
449 used for specialized purposes such as storing the internal
450 document tree.
451
452 - Writers to be added: HTML 3.2 or 4.01-loose, XML (various forms,
453 such as DocBook), PDF, plaintext, reStructuredText, and perhaps
454 others.
455
456 Subpackages of "docutils.writers" contain modules and data files
457 (such as stylesheets) that support the individual writers.
458
459 See `Writers`_ above.
460
461 - Package "docutils.transforms": tree transform classes.
462
463 - Class "Transformer" stores transforms and applies them to
464 document trees. (``docutils/transforms/__init__.py``)
465
466 - Class "Transform" is the base class of specific transforms.
467 (``docutils/transforms/__init__.py``)
468
469 - Each module contains related transform classes.
470
471 See `Transforms`_ above.
472
473 - Package "docutils.languages": Language modules contain
474 language-dependent strings and mappings. They are named for their
475 language identifier (as defined in `Choice of Docstring Format`_
476 below), converting dashes to underscores.
477
478 - Function "get_language(language_code)", returns matching
479 language module. (``docutils/languages/__init__.py``)
480
481 - Modules: en.py (English), de.py (German), fr.py (French), it.py
482 (Italian), sk.py (Slovak), sv.py (Swedish).
483
484 - Other languages to be added.
485
486 * Third-party modules: "extras" directory. These modules are
487 installed only if they're not already present in the Python
488 installation.
489
490 - ``extras/roman.py`` contains Roman numeral conversion routines.
491
492
493 Front-End Tools
494 ===============
495
496 The ``tools/`` directory contains several front ends for common
497 Docutils processing. See `Docutils Front-End Tools`_ for details.
498
499 .. _Docutils Front-End Tools:
500 https://docutils.sourceforge.io/docs/user/tools.html
501
502
503 Document Tree
504 =============
505
506 A single intermediate data structure is used internally by Docutils,
507 in the interfaces between components; it is defined in the
508 ``docutils.nodes`` module. It is not required that this data
509 structure be used *internally* by any of the components, just
510 *between* components as outlined in the diagram in the `Docutils
511 Project Model`_ above.
512
513 Custom node types are allowed, provided that either (a) a transform
514 converts them to standard Docutils nodes before they reach the Writer
515 proper, or (b) the custom node is explicitly supported by certain
516 Writers, and is wrapped in a filtered "pending" node. An example of
517 condition (a) is the `Python Source Reader`_ (see below), where a
518 "stylist" transform converts custom nodes. The HTML ``<meta>`` tag is
519 an example of condition (b); it is supported by the HTML Writer but
520 not by others. The reStructuredText "meta" directive creates a
521 "pending" node, which contains knowledge that the embedded "meta" node
522 can only be handled by HTML-compatible writers. The "pending" node is
523 resolved by the ``docutils.transforms.components.Filter`` transform,
524 which checks that the calling writer supports HTML; if it doesn't, the
525 "pending" node (and enclosed "meta" node) is removed from the
526 document.
527
528 The document tree data structure is similar to a DOM tree, but with
529 specific node names (classes) instead of DOM's generic nodes. The
530 schema is documented in an XML DTD (eXtensible Markup Language
531 Document Type Definition), which comes in two parts:
532
533 * the Docutils Generic DTD, docutils.dtd_, and
534
535 * the OASIS Exchange Table Model, soextbl.dtd_.
536
537 The DTD defines a rich set of elements, suitable for many input and
538 output formats. The DTD retains all information necessary to
539 reconstruct the original input text, or a reasonable facsimile
540 thereof.
541
542 See `The Docutils Document Tree`_ for details (incomplete).
543
544
545 Error Handling
546 ==============
547
548 When the parser encounters an error in markup, it inserts a system
549 message (DTD element "system_message"). There are five levels of
550 system messages:
551
552 * Level-0, "DEBUG": an internal reporting issue. There is no effect
553 on the processing. Level-0 system messages are handled separately
554 from the others.
555
556 * Level-1, "INFO": a minor issue that can be ignored. There is little
557 or no effect on the processing. Typically level-1 system messages
558 are not reported.
559
560 * Level-2, "WARNING": an issue that should be addressed. If ignored,
561 there may be minor problems with the output. Typically level-2
562 system messages are reported but do not halt processing.
563
564 * Level-3, "ERROR": a major issue that should be addressed. If
565 ignored, the output will contain unpredictable errors. Typically
566 level-3 system messages are reported but do not halt processing.
567
568 * Level-4, "SEVERE": a critical error that must be addressed.
569 Typically level-4 system messages are turned into exceptions which
570 do halt processing. If ignored, the output will contain severe
571 errors.
572
573 Although the initial message levels were devised independently, they
574 have a strong correspondence to `VMS error condition severity
575 levels`_; the names in quotes for levels 1 through 4 were borrowed
576 from VMS. Error handling has since been influenced by the `log4j
577 project`_.
578
579
580 Python Source Reader
581 ====================
582
583 The Python Source Reader ("PySource") is the Docutils component that
584 reads Python source files, extracts docstrings in context, then
585 parses, links, and assembles the docstrings into a cohesive whole. It
586 is a major and non-trivial component, currently under experimental
587 development in the Docutils sandbox. High-level design issues are
588 presented here.
589
590
591 Processing Model
592 ----------------
593
594 This model will evolve over time, incorporating experience and
595 discoveries.
596
597 1. The PySource Reader uses an Input class to read in Python packages
598 and modules, into a tree of strings.
599
600 2. The Python modules are parsed, converting the tree of strings into
601 a tree of abstract syntax trees with docstring nodes.
602
603 3. The abstract syntax trees are converted into an internal
604 representation of the packages/modules. Docstrings are extracted,
605 as well as code structure details. See `AST Mining`_ below.
606 Namespaces are constructed for lookup in step 6.
607
608 4. One at a time, the docstrings are parsed, producing standard
609 Docutils doctrees.
610
611 5. PySource assembles all the individual docstrings' doctrees into a
612 Python-specific custom Docutils tree paralleling the
613 package/module/class structure; this is a custom Reader-specific
614 internal representation (see the `Docutils Python Source DTD`_).
615 Namespaces must be merged: Python identifiers, hyperlink targets.
616
617 6. Cross-references from docstrings (interpreted text) to Python
618 identifiers are resolved according to the Python namespace lookup
619 rules. See `Identifier Cross-References`_ below.
620
621 7. A "Stylist" transform is applied to the custom doctree (by the
622 Transformer_), custom nodes are rendered using standard nodes as
623 primitives, and a standard document tree is emitted. See `Stylist
624 Transforms`_ below.
625
626 8. Other transforms are applied to the standard doctree by the
627 Transformer_.
628
629 9. The standard doctree is sent to a Writer, which translates the
630 document into a concrete format (HTML, PDF, etc.).
631
632 10. The Writer uses an Output class to write the resulting data to its
633 destination (disk file, directories and files, etc.).
634
635
636 AST Mining
637 ----------
638
639 Abstract Syntax Tree mining code will be written (or adapted) that
640 scans a parsed Python module, and returns an ordered tree containing
641 the names, docstrings (including attribute and additional docstrings;
642 see below), and additional info (in parentheses below) of all of the
643 following objects:
644
645 * packages
646 * modules
647 * module attributes (+ initial values)
648 * classes (+ inheritance)
649 * class attributes (+ initial values)
650 * instance attributes (+ initial values)
651 * methods (+ parameters & defaults)
652 * functions (+ parameters & defaults)
653
654 (Extract comments too? For example, comments at the start of a module
655 would be a good place for bibliographic field lists.)
656
657 In order to evaluate interpreted text cross-references, namespaces for
658 each of the above will also be required.
659
660 See the python-dev/docstring-develop thread "AST mining", started on
661 2001-08-14.
662
663
664 Docstring Extraction Rules
665 --------------------------
666
667 1. What to examine:
668
669 a) If the "``__all__``" variable is present in the module being
670 documented, only identifiers listed in "``__all__``" are
671 examined for docstrings.
672
673 b) In the absence of "``__all__``", all identifiers are examined,
674 except those whose names are private (names begin with "_" but
675 don't begin and end with "__").
676
677 c) 1a and 1b can be overridden by runtime settings.
678
679 2. Where:
680
681 Docstrings are string literal expressions, and are recognized in
682 the following places within Python modules:
683
684 a) At the beginning of a module, function definition, class
685 definition, or method definition, after any comments. This is
686 the standard for Python ``__doc__`` attributes.
687
688 b) Immediately following a simple assignment at the top level of a
689 module, class definition, or ``__init__`` method definition,
690 after any comments. See `Attribute Docstrings`_ below.
691
692 c) Additional string literals found immediately after the
693 docstrings in (a) and (b) will be recognized, extracted, and
694 concatenated. See `Additional Docstrings`_ below.
695
696 d) @@@ 2.2-style "properties" with attribute docstrings? Wait for
697 syntax?
698
699 3. How:
700
701 Whenever possible, Python modules should be parsed by Docutils, not
702 imported. There are several reasons:
703
704 - Importing untrusted code is inherently insecure.
705
706 - Information from the source is lost when using introspection to
707 examine an imported module, such as comments and the order of
708 definitions.
709
710 - Docstrings are to be recognized in places where the byte-code
711 compiler ignores string literal expressions (2b and 2c above),
712 meaning importing the module will lose these docstrings.
713
714 Of course, standard Python parsing tools such as the "parser"
715 library module should be used.
716
717 When the Python source code for a module is not available
718 (i.e. only the ``.pyc`` file exists) or for C extension modules, to
719 access docstrings the module can only be imported, and any
720 limitations must be lived with.
721
722 Since attribute docstrings and additional docstrings are ignored by
723 the Python byte-code compiler, no namespace pollution or runtime bloat
724 will result from their use. They are not assigned to ``__doc__`` or
725 to any other attribute. The initial parsing of a module may take a
726 slight performance hit.
727
728
729 Attribute Docstrings
730 ''''''''''''''''''''
731
732 (This is a simplified version of PEP 224 [#PEP-224]_.)
733
734 A string literal immediately following an assignment statement is
735 interpreted by the docstring extraction machinery as the docstring of
736 the target of the assignment statement, under the following
737 conditions:
738
739 1. The assignment must be in one of the following contexts:
740
741 a) At the top level of a module (i.e., not nested inside a compound
742 statement such as a loop or conditional): a module attribute.
743
744 b) At the top level of a class definition: a class attribute.
745
746 c) At the top level of the "``__init__``" method definition of a
747 class: an instance attribute. Instance attributes assigned in
748 other methods are assumed to be implementation details. (@@@
749 ``__new__`` methods?)
750
751 d) A function attribute assignment at the top level of a module or
752 class definition.
753
754 Since each of the above contexts are at the top level (i.e., in the
755 outermost suite of a definition), it may be necessary to place
756 dummy assignments for attributes assigned conditionally or in a
757 loop.
758
759 2. The assignment must be to a single target, not to a list or a tuple
760 of targets.
761
762 3. The form of the target:
763
764 a) For contexts 1a and 1b above, the target must be a simple
765 identifier (not a dotted identifier, a subscripted expression,
766 or a sliced expression).
767
768 b) For context 1c above, the target must be of the form
769 "``self.attrib``", where "``self``" matches the "``__init__``"
770 method's first parameter (the instance parameter) and "attrib"
771 is a simple identifier as in 3a.
772
773 c) For context 1d above, the target must be of the form
774 "``name.attrib``", where "``name``" matches an already-defined
775 function or method name and "attrib" is a simple identifier as
776 in 3a.
777
778 Blank lines may be used after attribute docstrings to emphasize the
779 connection between the assignment and the docstring.
780
781 Examples::
782
783 g = 'module attribute (module-global variable)'
784 """This is g's docstring."""
785
786 class AClass:
787
788 c = 'class attribute'
789 """This is AClass.c's docstring."""
790
791 def __init__(self):
792 """Method __init__'s docstring."""
793
794 self.i = 'instance attribute'
795 """This is self.i's docstring."""
796
797 def f(x):
798 """Function f's docstring."""
799 return x**2
800
801 f.a = 1
802 """Function attribute f.a's docstring."""
803
804
805 Additional Docstrings
806 '''''''''''''''''''''
807
808 (This idea was adapted from PEP 216 [#PEP-216]_.)
809
810 Many programmers would like to make extensive use of docstrings for
811 API documentation. However, docstrings do take up space in the
812 running program, so some programmers are reluctant to "bloat up" their
813 code. Also, not all API documentation is applicable to interactive
814 environments, where ``__doc__`` would be displayed.
815
816 Docutils' docstring extraction tools will concatenate all string
817 literal expressions which appear at the beginning of a definition or
818 after a simple assignment. Only the first strings in definitions will
819 be available as ``__doc__``, and can be used for brief usage text
820 suitable for interactive sessions; subsequent string literals and all
821 attribute docstrings are ignored by the Python byte-code compiler and
822 may contain more extensive API information.
823
824 Example::
825
826 def function(arg):
827 """This is __doc__, function's docstring."""
828 """
829 This is an additional docstring, ignored by the byte-code
830 compiler, but extracted by Docutils.
831 """
832 pass
833
834 .. topic:: Issue: ``from __future__ import``
835
836 This would break "``from __future__ import``" statements introduced
837 in Python 2.1 for multiple module docstrings (main docstring plus
838 additional docstring(s)). The Python Reference Manual specifies:
839
840 A future statement must appear near the top of the module. The
841 only lines that can appear before a future statement are:
842
843 * the module docstring (if any),
844 * comments,
845 * blank lines, and
846 * other future statements.
847
848 Resolution?
849
850 1. Should we search for docstrings after a ``__future__``
851 statement? Very ugly.
852
853 2. Redefine ``__future__`` statements to allow multiple preceding
854 string literals?
855
856 3. Or should we not even worry about this? There probably
857 shouldn't be ``__future__`` statements in production code, after
858 all. Perhaps modules with ``__future__`` statements will simply
859 have to put up with the single-docstring limitation.
860
861
862 Choice of Docstring Format
863 --------------------------
864
865 Rather than force everyone to use a single docstring format, multiple
866 input formats are allowed by the processing system. A special
867 variable, ``__docformat__``, may appear at the top level of a module
868 before any function or class definitions. Over time or through
869 decree, a standard format or set of formats should emerge.
870
871 A module's ``__docformat__`` variable only applies to the objects
872 defined in the module's file. In particular, the ``__docformat__``
873 variable in a package's ``__init__.py`` file does not apply to objects
874 defined in subpackages and submodules.
875
876 The ``__docformat__`` variable is a string containing the name of the
877 format being used, a case-insensitive string matching the input
878 parser's module or package name (i.e., the same name as required to
879 "import" the module or package), or a registered alias. If no
880 ``__docformat__`` is specified, the default format is "plaintext" for
881 now; this may be changed to the standard format if one is ever
882 established.
883
884 The ``__docformat__`` string may contain an optional second field,
885 separated from the format name (first field) by a single space: a
886 case-insensitive language identifier as defined in RFC 1766. A
887 typical language identifier consists of a 2-letter language code from
888 `ISO 639`_ (3-letter codes used only if no 2-letter code exists; RFC
889 1766 is currently being revised to allow 3-letter codes). If no
890 language identifier is specified, the default is "en" for English.
891 The language identifier is passed to the parser and can be used for
892 language-dependent markup features.
893
894
895 Identifier Cross-References
896 ---------------------------
897
898 In Python docstrings, interpreted text is used to classify and mark up
899 program identifiers, such as the names of variables, functions,
900 classes, and modules. If the identifier alone is given, its role is
901 inferred implicitly according to the Python namespace lookup rules.
902 For functions and methods (even when dynamically assigned),
903 parentheses ('()') may be included::
904
905 This function uses `another()` to do its work.
906
907 For class, instance and module attributes, dotted identifiers are used
908 when necessary. For example (using reStructuredText markup)::
909
910 class Keeper(Storer):
911
912 """
913 Extend `Storer`. Class attribute `instances` keeps track
914 of the number of `Keeper` objects instantiated.
915 """
916
917 instances = 0
918 """How many `Keeper` objects are there?"""
919
920 def __init__(self):
921 """
922 Extend `Storer.__init__()` to keep track of instances.
923
924 Keep count in `Keeper.instances`, data in `self.data`.
925 """
926 Storer.__init__(self)
927 Keeper.instances += 1
928
929 self.data = []
930 """Store data in a list, most recent last."""
931
932 def store_data(self, data):
933 """
934 Extend `Storer.store_data()`; append new `data` to a
935 list (in `self.data`).
936 """
937 self.data = data
938
939 Each of the identifiers quoted with backquotes ("`") will become
940 references to the definitions of the identifiers themselves.
941
942
943 Stylist Transforms
944 ------------------
945
946 Stylist transforms are specialized transforms specific to the PySource
947 Reader. The PySource Reader doesn't have to make any decisions as to
948 style; it just produces a logically constructed document tree, parsed
949 and linked, including custom node types. Stylist transforms
950 understand the custom nodes created by the Reader and convert them
951 into standard Docutils nodes.
952
953 Multiple Stylist transforms may be implemented and one can be chosen
954 at runtime (through a "--style" or "--stylist" command-line option).
955 Each Stylist transform implements a different layout or style; thus
956 the name. They decouple the context-understanding part of the Reader
957 from the layout-generating part of processing, resulting in a more
958 flexible and robust system. This also serves to "separate style from
959 content", the SGML/XML ideal.
960
961 By keeping the piece of code that does the styling small and modular,
962 it becomes much easier for people to roll their own styles. The
963 "barrier to entry" is too high with existing tools; extracting the
964 stylist code will lower the barrier considerably.
965
966
967 ==========================
968 References and Footnotes
969 ==========================
970
971 .. [#PEP-256] PEP 256, Docstring Processing System Framework, Goodger
972 (http://www.python.org/peps/pep-0256.html)
973
974 .. [#PEP-224] PEP 224, Attribute Docstrings, Lemburg
975 (http://www.python.org/peps/pep-0224.html)
976
977 .. [#PEP-216] PEP 216, Docstring Format, Zadka
978 (http://www.python.org/peps/pep-0216.html)
979
980 .. _docutils.dtd:
981 https://docutils.sourceforge.io/docs/ref/docutils.dtd
982
983 .. _soextbl.dtd:
984 https://docutils.sourceforge.io/docs/ref/soextblx.dtd
985
986 .. _The Docutils Document Tree:
987 https://docutils.sourceforge.io/docs/ref/doctree.html
988
989 .. _VMS error condition severity levels:
990 http://www.openvms.compaq.com:8000/73final/5841/841pro_027.html
991 #error_cond_severity
992
993 .. _log4j project: http://logging.apache.org/log4j/docs/index.html
994
995 .. _Docutils Python Source DTD:
996 https://docutils.sourceforge.io/docs/dev/pysource.dtd
997
998 .. _ISO 639: http://www.loc.gov/standards/iso639-2/englangn.html
999
1000 .. _Python Doc-SIG: http://www.python.org/sigs/doc-sig/
1001
1002
1003
1004 ==================
1005 Project Web Site
1006 ==================
1007
1008 A SourceForge project has been set up for this work at
1009 https://docutils.sourceforge.io/.
1010
1011
1012 ===========
1013 Copyright
1014 ===========
1015
1016 This document has been placed in the public domain.
1017
1018
1019 ==================
1020 Acknowledgements
1021 ==================
1022
1023 This document borrows ideas from the archives of the `Python
1024 Doc-SIG`_. Thanks to all members past & present.
1025
1026
1027 .. Emacs settings
1028
1029 Local Variables:
1030 mode: indented-text
1031 mode: rst
1032 indent-tabs-mode: nil
1033 sentence-end-double-space: t
1034 fill-column: 70
1035 End: