Skip to content

Support converting parsed classes back to mail-like strings #54

@jwodder

Description

@jwodder

Post #52:

Give Field et alii optional encoder parameters for specifying how to stringify attribute values when dumping with dump(parsable, fp) etc. functions.

  • Should this functionality be called "dumping" or "encoding" or something else?

    • Arguably, the opposite of scanning is printing, but defining a function named "print()" isn't such a good idea.
  • encoders are callables with the following signatures:

    • For Field and MultiField: (name: str, value: Any) -> Any
    • For ExtraFields and MultiExtraFields: (value: Any) -> Sequence[tuple[str, Any]] | Mapping[str, Sequence[Any] | Any]
    • For BodyField: (value: Any) -> Any
  • Encoders must return one of the following:

    • For any field:
      • None — no value will be written
    • For Field and MultiField:
      • Sequence[Any] — will be used as multiple field values
      • Any — will be stringified to be used as the field value
    • For body fields:
      • Any — will be stringified
    • For extra fields:
      • Sequence[tuple[str, Any]]
      • Mapping[str, Sequence[Any] | Any]
  • This will require also adding a name_encoder parameter to @parsable

    • Named fields will also need some argument for specifying the spelling of their encoded name.
  • Functions for "dumping":

    • dump(parseable, fp) -> None
    • dump_stream(fields: Iterable[Tuple[Optional[str], str]], fp: TextIO) -> None
    • dump_stanzas_stream(fields: Iterable[Iterable[Tuple[str, str]]], fp: TextIO) -> None
    • dumps*() functions that return strings
  • Give the "dumping" functions keyword options for the following:

    • separator
    • folding indentation (indent)
    • auto_indent: bool = False (Rethink name) — when True, field values in which all lines after the first are already indented (i.e., folded) are not indented again
  • The string-returning dump functions should be the "core" ones that the others are implemented in terms of, as we don't want to write anything to a file until we're sure that all the return values of the decoders are valid.

  • Line wrapping fields is the caller's job (but maybe add a helper function for that?).

  • None (after serializing/encoding) field values are always skipped when dumping; if the user doesn't want that, they need to set a dumper that serializes Nones to something else.

  • Fields with aliases are dumped using the decoded aliases.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions