Reading and writing SVG¶
Serialization options, writers and the parser.
Reading and writing SVG text, files and streams.
The writer is imported eagerly; the parser and async helpers load on first attribute access.
- class SerializeOptions(*, pretty: dataclasses.InitVar[bool] = True, indent: str = ' ', precision: int = 4, xml_declaration: bool = True, doctype: bool = False, encoding: str = 'utf-8', compact_paths: bool = False, namespaces: dict[str, str]=<factory>)[source]¶
Bases:
objectOutput settings for serialization.
All fields are keyword-only. They control layout, number formatting and the prolog written before the root element.
- Parameters:
pretty (bool, optional) – Indent and break lines;
Falsewrites everything on one line. Defaults to True.indent (str, optional) – One level of indentation when pretty. Defaults to two spaces.
precision (int, optional) – Maximum decimals for numbers. Defaults to 4.
xml_declaration (bool, optional) – Emit
<?xml ...?>. Defaults to True.doctype (bool, optional) – Emit the SVG 1.1 DOCTYPE. Defaults to False.
encoding (str, optional) – Declared and used when writing files. Defaults to
"utf-8".compact_paths (bool, optional) – Write path data in its shortest form. Defaults to False.
namespaces (dict, optional) – Namespace declarations put on a root
<svg>. Defaults to the SVG and XLink namespaces. Other prefixes in use (inkscape:,sodipodi:, prefixes declared by a parsed file) are declared once on the root too.
Examples
>>> from svgwriter.formats.io import SerializeOptions >>> options = SerializeOptions(pretty=False, precision=2) >>> options.indent, options.precision ('', 2)
- pretty: dataclasses.InitVar[bool] = True¶
- class Writer(options: SerializeOptions | None = None, **kwargs: Any)[source]¶
Bases:
objectTurn an element tree into text, honoring
SerializeOptions.- Parameters:
options (SerializeOptions, optional) – Pre-built options. Defaults to None, in which case kwargs build one.
**kwargs – Fields of
SerializeOptions, used when options is None.
Examples
>>> from svgwriter import Circle >>> from svgwriter.formats.io import Writer >>> Writer(pretty=False, xml_declaration=False).to_string(Circle(5, 5, 2)) '<circle cx="5" cy="5" r="2"/>'
- iter_chunks(element: Element, *, xml_declaration: bool | MissingType = MISSING) Iterator[str][source]¶
Yield the document in pieces (useful for streaming).
Joining the chunks gives the same text as
to_string().- Parameters:
- Yields:
str – Consecutive fragments of the document.
See also
to_stringJoin the chunks into one string.
Examples
>>> from svgwriter import Circle >>> from svgwriter.formats.io import Writer >>> list(Writer(pretty=False, xml_declaration=False).iter_chunks(Circle(5, 5, 2))) ['<circle cx="5" cy="5" r="2"', '/>']
- to_string(element: Element, **kwargs: Any) str[source]¶
Serialize element to a string.
- Parameters:
element (Element) – Root of the tree to write.
**kwargs – Forwarded to
iter_chunks()(xml_declaration).
- Returns:
str – The complete document.
See also
writeWrite to a path or stream instead.
Examples
>>> from svgwriter import Circle >>> from svgwriter.formats.io import Writer >>> Writer(pretty=False).to_string(Circle(5, 5, 2), xml_declaration=False) '<circle cx="5" cy="5" r="2"/>'
- write(element: Element, target: AnyPath | TextSink, **kwargs: Any) None[source]¶
Write to a filesystem path or any object with
write(str).- Parameters:
element (Element) – Root of the tree to write.
target (str, os.PathLike or TextSink) – Destination path (written with the configured encoding) or text stream.
**kwargs – Forwarded to
iter_chunks()(xml_declaration).
- Raises:
TypeError – If target is neither a path nor a text stream.
See also
to_stringReturn the text instead.
Examples
>>> import io >>> from svgwriter import Circle >>> from svgwriter.formats.io import Writer >>> stream = io.StringIO() >>> Writer(pretty=False, xml_declaration=False).write(Circle(5, 5, 2), stream) >>> stream.getvalue() '<circle cx="5" cy="5" r="2"/>'
- iter_chunks(element: Element, **kwargs: Any) Iterator[str][source]¶
Yield the serialized document in pieces.
Module-level shortcut for
Writer.iter_chunks().- Parameters:
element (Element) – Root of the tree to write.
**kwargs – Fields of
SerializeOptions, plusxml_declarationto override the prolog for this call.
- Yields:
str – Consecutive fragments of the document.
See also
to_stringJoin the chunks into one string.
Examples
>>> from svgwriter import Circle >>> from svgwriter.formats.io import iter_chunks >>> list(iter_chunks(Circle(5, 5, 2), pretty=False, xml_declaration=False)) ['<circle cx="5" cy="5" r="2"', '/>']
- to_string(element: Element, *, options: SerializeOptions | None = None, **kwargs: Any) str[source]¶
Serialize element to a string.
Builds a
Writerfrom the options and returns its output in one piece.- Parameters:
element (Element) – Root of the tree to write.
options (SerializeOptions, optional) – Pre-built options; otherwise keywords build one. Defaults to None.
**kwargs – Fields of
SerializeOptions(pretty,precision…).
- Returns:
str – The complete document.
See also
writeWrite to a path or stream.
iter_chunksStream the text in pieces.
Examples
>>> from svgwriter import Circle >>> to_string(Circle(5, 5, 2), xml_declaration=False, pretty=False) '<circle cx="5" cy="5" r="2"/>'
- write(element: Element, target: AnyPath | TextSink, **kwargs: Any) None[source]¶
Write element to a path or text stream.
Keywords are the same as in
to_string().- Parameters:
element (Element) – Root of the tree to write.
target (str, os.PathLike or TextSink) – Destination path or any object with
write(str).**kwargs –
optionsor fields ofSerializeOptions.
- Raises:
TypeError – If target is neither a path nor a text stream.
See also
to_stringReturn the text instead.
svgwriter.formats.io.write_asyncWrite to a path in a worker thread.
Examples
>>> import io >>> from svgwriter import Circle >>> from svgwriter.formats.io import write >>> stream = io.StringIO() >>> write(Circle(5, 5, 2), stream, pretty=False, xml_declaration=False) >>> stream.getvalue() '<circle cx="5" cy="5" r="2"/>'
- async write_async(element: Element, path: AnyPath, **kwargs: Any) None[source]¶
Write element to path in a worker thread.
- Parameters:
element (Element) – Root of the tree to write.
path (str or os.PathLike) – Destination file.
**kwargs –
optionsor fields ofSerializeOptions.
See also
write_many_asyncWrite several documents concurrently.
Examples
>>> import asyncio, tempfile, pathlib >>> from svgwriter import Circle >>> from svgwriter.formats.io import write_async >>> with tempfile.TemporaryDirectory() as folder: ... path = pathlib.Path(folder) / "a.svg" ... asyncio.run(write_async(Circle(5, 5, 2), path)) ... print(path.read_text(encoding="utf-8").count("<circle")) 1