• formatter —- Generic output formatting
    • The Formatter Interface
    • Formatter Implementations
    • The Writer Interface
    • Writer Implementations

    formatter —- Generic output formatting

    3.4 版后已移除: Due to lack of usage, the formatter module has been deprecated.


    This module supports two interface definitions, each with multipleimplementations: The formatter interface, and the writer interface which isrequired by the formatter interface.

    Formatter objects transform an abstract flow of formatting events into specificoutput events on writer objects. Formatters manage several stack structures toallow various properties of a writer object to be changed and restored; writersneed not be able to handle relative changes nor any sort of "change back"operation. Specific writer properties which may be controlled via formatterobjects are horizontal alignment, font, and left margin indentations. Amechanism is provided which supports providing arbitrary, non-exclusive stylesettings to a writer as well. Additional interfaces facilitate formattingevents which are not reversible, such as paragraph separation.

    Writer objects encapsulate device interfaces. Abstract devices, such as fileformats, are supported as well as physical devices. The providedimplementations all work with abstract devices. The interface makes availablemechanisms for setting the properties which formatter objects manage andinserting data into the output.

    The Formatter Interface

    Interfaces to create formatters are dependent on the specific formatter classbeing instantiated. The interfaces described below are the required interfaceswhich all formatters must support once initialized.

    One data element is defined at the module level:

    • formatter.AS_IS
    • Value which can be used in the font specification passed to the push_font()method described below, or as the new value to any other push_property()method. Pushing the AS_IS value allows the corresponding pop_property()method to be called without having to track whether the property was changed.

    The following attributes are defined for formatter instance objects:

    • formatter.writer
    • The writer instance with which the formatter interacts.

    • formatter.endparagraph(_blanklines)

    • Close any open paragraphs and insert at least blanklines before the nextparagraph.

    • formatter.add_line_break()

    • Add a hard line break if one does not already exist. This does not break thelogical paragraph.

    • formatter.addhor_rule(args, *kw_)

    • Insert a horizontal rule in the output. A hard break is inserted if there isdata in the current paragraph, but the logical paragraph is not broken. Thearguments and keywords are passed on to the writer's send_line_break()method.

    • formatter.addflowing_data(_data)

    • Provide data which should be formatted with collapsed whitespace. Whitespacefrom preceding and successive calls to add_flowing_data() is considered aswell when the whitespace collapse is performed. The data which is passed tothis method is expected to be word-wrapped by the output device. Note that anyword-wrapping still must be performed by the writer object due to the need torely on device and font information.

    • formatter.addliteral_data(_data)

    • Provide data which should be passed to the writer unchanged. Whitespace,including newline and tab characters, are considered legal in the value ofdata.

    • formatter.addlabel_data(_format, counter)

    • Insert a label which should be placed to the left of the current left margin.This should be used for constructing bulleted or numbered lists. If theformat value is a string, it is interpreted as a format specification forcounter, which should be an integer. The result of this formatting becomes thevalue of the label; if format is not a string it is used as the label valuedirectly. The label value is passed as the only argument to the writer'ssend_label_data() method. Interpretation of non-string label values isdependent on the associated writer.

    Format specifications are strings which, in combination with a counter value,are used to compute label values. Each character in the format string is copiedto the label value, with some characters recognized to indicate a transform onthe counter value. Specifically, the character '1' represents the countervalue formatter as an Arabic number, the characters 'A' and 'a'represent alphabetic representations of the counter value in upper and lowercase, respectively, and 'I' and 'i' represent the counter value in Romannumerals, in upper and lower case. Note that the alphabetic and romantransforms require that the counter value be greater than zero.

    • formatter.flush_softspace()
    • Send any pending whitespace buffered from a previous call toadd_flowing_data() to the associated writer object. This should be calledbefore any direct manipulation of the writer object.

    • formatter.pushalignment(_align)

    • Push a new alignment setting onto the alignment stack. This may beAS_IS if no change is desired. If the alignment value is changed fromthe previous setting, the writer's newalignment() method is called withthe _align value.

    • formatter.pop_alignment()

    • Restore the previous alignment.

    • formatter.pushfont((size, _italic, bold, teletype))

    • Change some or all font properties of the writer object. Properties which arenot set to AS_IS are set to the values passed in while others aremaintained at their current settings. The writer's new_font() method iscalled with the fully resolved font specification.

    • formatter.pop_font()

    • Restore the previous font.

    • formatter.pushmargin(_margin)

    • Increase the number of left margin indentations by one, associating the logicaltag margin with the new indentation. The initial margin level is 0.Changed values of the logical tag must be true values; false values other thanAS_IS are not sufficient to change the margin.

    • formatter.pop_margin()

    • Restore the previous margin.

    • formatter.pushstyle(*styles_)

    • Push any number of arbitrary style specifications. All styles are pushed ontothe styles stack in order. A tuple representing the entire stack, includingAS_IS values, is passed to the writer's new_styles() method.

    • formatter.popstyle(_n=1)

    • Pop the last n style specifications passed to push_style(). A tuplerepresenting the revised stack, including AS_IS values, is passed tothe writer's new_styles() method.

    • formatter.setspacing(_spacing)

    • Set the spacing style for the writer.

    • formatter.assertline_data(_flag=1)

    • Inform the formatter that data has been added to the current paragraphout-of-band. This should be used when the writer has been manipulateddirectly. The optional flag argument can be set to false if the writermanipulations produced a hard line break at the end of the output.

    Formatter Implementations

    Two implementations of formatter objects are provided by this module. Mostapplications may use one of these classes without modification or subclassing.

    • class formatter.NullFormatter(writer=None)
    • A formatter which does nothing. If writer is omitted, a NullWriterinstance is created. No methods of the writer are called byNullFormatter instances. Implementations should inherit from thisclass if implementing a writer interface but don't need to inherit anyimplementation.

    • class formatter.AbstractFormatter(writer)

    • The standard formatter. This implementation has demonstrated wide applicabilityto many writers, and may be used directly in most circumstances. It has beenused to implement a full-featured World Wide Web browser.

    The Writer Interface

    Interfaces to create writers are dependent on the specific writer class beinginstantiated. The interfaces described below are the required interfaces whichall writers must support once initialized. Note that while most applications canuse the AbstractFormatter class as a formatter, the writer musttypically be provided by the application.

    • writer.flush()
    • Flush any buffered output or device control events.

    • writer.newalignment(_align)

    • Set the alignment style. The align value can be any object, but by conventionis a string or None, where None indicates that the writer's "preferred"alignment should be used. Conventional align values are 'left','center', 'right', and 'justify'.

    • writer.newfont(_font)

    • Set the font style. The value of font will be None, indicating that thedevice's default font should be used, or a tuple of the form (size,italic, bold, teletype). Size will be a string indicating the size offont that should be used; specific strings and their interpretation must bedefined by the application. The italic, bold, and teletype values areBoolean values specifying which of those font attributes should be used.

    • writer.newmargin(_margin, level)

    • Set the margin level to the integer level and the logical tag to margin.Interpretation of the logical tag is at the writer's discretion; the onlyrestriction on the value of the logical tag is that it not be a false value fornon-zero values of level.

    • writer.newspacing(_spacing)

    • Set the spacing style to spacing.

    • writer.newstyles(_styles)

    • Set additional styles. The styles value is a tuple of arbitrary values; thevalue AS_IS should be ignored. The styles tuple may be interpretedeither as a set or as a stack depending on the requirements of the applicationand writer implementation.

    • writer.send_line_break()

    • Break the current line.

    • writer.sendparagraph(_blankline)

    • Produce a paragraph separation of at least blankline blank lines, or theequivalent. The blankline value will be an integer. Note that theimplementation will receive a call to send_line_break() before this callif a line break is needed; this method should not include ending the last lineof the paragraph. It is only responsible for vertical spacing betweenparagraphs.

    • writer.sendhor_rule(args, *kw_)

    • Display a horizontal rule on the output device. The arguments to this methodare entirely application- and writer-specific, and should be interpreted withcare. The method implementation may assume that a line break has already beenissued via send_line_break().

    • writer.sendflowing_data(_data)

    • Output character data which may be word-wrapped and re-flowed as needed. Withinany sequence of calls to this method, the writer may assume that spans ofmultiple whitespace characters have been collapsed to single space characters.

    • writer.sendliteral_data(_data)

    • Output character data which has already been formatted for display. Generally,this should be interpreted to mean that line breaks indicated by newlinecharacters should be preserved and no new line breaks should be introduced. Thedata may contain embedded newline and tab characters, unlike data provided tothe send_formatted_data() interface.

    • writer.sendlabel_data(_data)

    • Set data to the left of the current left margin, if possible. The value ofdata is not restricted; treatment of non-string values is entirelyapplication- and writer-dependent. This method will only be called at thebeginning of a line.

    Writer Implementations

    Three implementations of the writer object interface are provided as examples bythis module. Most applications will need to derive new writer classes from theNullWriter class.

    • class formatter.NullWriter
    • A writer which only provides the interface definition; no actions are taken onany methods. This should be the base class for all writers which do not need toinherit any implementation methods.

    • class formatter.AbstractWriter

    • A writer which can be used in debugging formatters, but not much else. Eachmethod simply announces itself by printing its name and arguments on standardoutput.

    • class formatter.DumbWriter(file=None, maxcol=72)

    • Simple writer class which writes output on the file object passedin as file or, if file is omitted, on standard output. The output issimply word-wrapped to the number of columns specified by maxcol. Thisclass is suitable for reflowing a sequence of paragraphs.