Attribute values and styles

viewBox, styles, CSS cascade and attribute names. Lengths and angles are in Units.

Attribute value types: view boxes, styles, references, names. Lengths and angles are in svgwriter.model.units.

class IRI(target: str, element: Element | None = None)[source]

Bases: object

A plain IRI, local (#id) or external.

element is the referenced element when the IRI was made from one; it lets documents put unplaced definitions into <defs> automatically.

Parameters:
  • target (str) – The reference text, such as "#grad" or "image.svg#icon".

  • element (Element, optional) – The referenced element, if known; ignored when comparing. Defaults to None.

See also

FuncIRI

The url(...) form.

Examples

>>> from svgwriter.model.attributes import IRI
>>> str(IRI.local("grad"))
'#grad'
target: str
element: Element | None = None
classmethod local(element_id: str) → IRI[source]

Return a reference to an element of the same document.

Parameters:

element_id (str) – The target’s id, without #.

Returns:

IRI – An IRI of the form #id.

Examples

>>> from svgwriter.model.attributes import IRI
>>> IRI.local("a").target
'#a'
property fragment: str | None

The part after #, or None when there is no fragment.

Examples

>>> from svgwriter.model.attributes import IRI
>>> IRI("image.svg#icon").fragment
'icon'
>>> IRI("image.svg").fragment is None
True
property current: str

The target text, following the referenced element’s id when it has changed since.

Examples

>>> import svgwriter as svg
>>> dot = svg.circle(0, 0, 1, id="a")
>>> ref = dot.iri
>>> dot.id = "b"
>>> ref.current
'#b'
What the code above draws
svg_value(precision: int = 4) → str[source]

Serialize the reference as attribute text.

Parameters:

precision (int, optional) – Unused; accepted for a uniform interface. Defaults to the library default precision.

Returns:

str – The IRI text.

Examples

>>> from svgwriter.model.attributes import IRI
>>> IRI.local("a").svg_value()
'#a'
class Align(*values)[source]

Bases: Keyword

Alignment values of preserveAspectRatio.

CENTER is an alias of X_MID_Y_MID, the default.

See also

PreserveAspectRatio

Combines an alignment with meet or slice.

Examples

>>> from svgwriter.model.attributes import Align
>>> Align.X_MIN_Y_MAX.value
'xMinYMax'
NONE = 'none'
X_MIN_Y_MIN = 'xMinYMin'
X_MID_Y_MIN = 'xMidYMin'
X_MAX_Y_MIN = 'xMaxYMin'
X_MIN_Y_MID = 'xMinYMid'
X_MID_Y_MID = 'xMidYMid'
X_MAX_Y_MID = 'xMaxYMid'
X_MIN_Y_MAX = 'xMinYMax'
X_MID_Y_MAX = 'xMidYMax'
X_MAX_Y_MAX = 'xMaxYMax'
CENTER = 'xMidYMid'
class Attr(name: str | None = None, *, convert: Callable[[Any], T] | None = None, default: T | None = None)[source]

Bases: Generic[T]

Expose one SVG attribute as a Python attribute.

Parameters:
  • name (str, optional) – SVG attribute name; derived from the Python name when omitted.

  • convert (callable, optional) – Applied to raw strings (for instance values read by the parser).

  • default (object, optional) – Returned when the attribute is not set. Defaults to None.

See also

LengthAttr

Attribute that reads lengths.

Examples

>>> import svgwriter as svg
>>> svg.Rect.width.key
'width'
>>> svg.Rect(width=3, height=1).width
3.0
svg
name
convert
default
property key: str

The SVG attribute name this descriptor reads and writes.

Examples

>>> import svgwriter as svg
>>> svg.Rect.stroke_width.key
'stroke-width'
class FuncIRI(target: str, element: Element | None = None)[source]

Bases: IRI

A functional IRI, url(...), as used by paint and filter.

Takes the same parameters as IRI.

See also

parse_func_iri

Parse url(...) text.

Examples

>>> from svgwriter.model.attributes import FuncIRI
>>> str(FuncIRI("#grad"))
'url(#grad)'
svg_value(precision: int = 4) → str[source]

Serialize the reference as url(...) text.

Parameters:

precision (int, optional) – Unused; accepted for a uniform interface. Defaults to the library default precision.

Returns:

str – The IRI wrapped in url().

Examples

>>> from svgwriter.model.attributes import FuncIRI
>>> FuncIRI("#grad").svg_value()
'url(#grad)'
class MeetOrSlice(*values)[source]

Bases: Keyword

Whether the viewBox is scaled to fit entirely or to cover the viewport.

See also

PreserveAspectRatio

Uses this setting.

Examples

>>> from svgwriter.model.attributes import MeetOrSlice
>>> MeetOrSlice.SLICE.value
'slice'
MEET = 'meet'
SLICE = 'slice'
class PreserveAspectRatio(align: Align = Align.X_MID_Y_MID, meet_or_slice: MeetOrSlice = MeetOrSlice.MEET, defer: bool = False)[source]

Bases: object

How a viewBox is fitted into its viewport.

Parameters:
  • align (Align, optional) – Which point of the viewBox lines up with the viewport. Defaults to Align.X_MID_Y_MID.

  • meet_or_slice (MeetOrSlice, optional) – Scale to fit entirely (meet) or to cover (slice). Defaults to MeetOrSlice.MEET.

  • defer (bool, optional) – Emit the defer keyword (only meaningful on image). Defaults to False.

See also

ViewBox

The rectangle being fitted.

Examples

>>> from svgwriter.model.attributes import Align, MeetOrSlice, PreserveAspectRatio
>>> str(PreserveAspectRatio(Align.X_MIN_Y_MIN, MeetOrSlice.SLICE))
'xMinYMin slice'
align: Align = 'xMidYMid'
meet_or_slice: MeetOrSlice = 'meet'
defer: bool = False
classmethod parse(text: str) → PreserveAspectRatio[source]

Parse preserveAspectRatio text.

Parameters:

text (str) – Text such as "defer xMinYMax slice".

Returns:

PreserveAspectRatio – The parsed value.

Raises:

ValueError – If the text is empty, too long, or contains an unknown keyword.

Examples

>>> from svgwriter.model.attributes import PreserveAspectRatio
>>> str(PreserveAspectRatio.parse("none"))
'none'
svg_value(precision: int = 4) → str[source]

Serialize as attribute text.

Parameters:

precision (int, optional) – Unused; accepted for a uniform interface. Defaults to the library default precision.

Returns:

str – The keywords; meet is omitted because it is the default.

Examples

>>> from svgwriter.model.attributes import PreserveAspectRatio
>>> PreserveAspectRatio().svg_value()
'xMidYMid'
class Style(declarations: Style | Mapping[str, object] | str | None = None, /, **properties: object)[source]

Bases: MutableMapping[str, object]

Ordered CSS declarations for a style attribute.

Keys accept Python spelling (stroke_width) or CSS spelling (stroke-width). Assigning None removes a declaration. It is a mutable mapping that keeps insertion order.

Parameters:
  • declarations (Style or mapping or str, optional) – Initial declarations, or CSS text such as "fill:red;stroke:blue". Defaults to None.

  • **properties – More declarations as keywords.

See also

StyleSheet

Builder for <style> element text.

Examples

>>> from svgwriter.model.attributes import Style
>>> str(Style(fill="red", stroke_width=2))
'fill:red;stroke-width:2'
static parse(text: str) → dict[str, str][source]

Split CSS declaration text into a dict.

Parameters:

text (str) – Declarations separated by semicolons, such as "a:b; c:d".

Returns:

dict of str to str – Property names mapped to values; malformed items are skipped.

Examples

>>> from svgwriter.model.attributes import Style
>>> Style.parse("a:b; c:d")
{'a': 'b', 'c': 'd'}
presentation_only() → Style[source]

Return the declarations that are SVG presentation properties.

Returns:

Style – A new style holding only presentation properties such as fill.

Examples

>>> from svgwriter.model.attributes import Style
>>> str(Style(fill="red", custom="x").presentation_only())
'fill:red'
svg_value(precision: int = 4) → str[source]

Serialize as the text of a style attribute.

Parameters:

precision (int, optional) – Maximum number of decimal places for numbers. Defaults to the library default precision.

Returns:

str – Declarations joined by semicolons.

Examples

>>> from svgwriter.model.attributes import Style
>>> Style(fill="red", stroke_width=1.5).svg_value()
'fill:red;stroke-width:1.5'
class StyleSheet(rules: Iterable[tuple[str, Style | Mapping[str, object] | str]] = ())[source]

Bases: object

Builder for the text of a <style> element.

Parameters:

rules (iterable of tuple, optional) – Initial (selector, declarations) pairs. Defaults to none.

See also

Style

A single declaration block.

Examples

>>> from svgwriter.model.attributes import StyleSheet
>>> sheet = StyleSheet().rule(".accent", fill="tomato")
>>> sheet.css()
'.accent { fill:tomato }'
rule(selector: str, declarations: Style | Mapping[str, object] | str | None = None, /, **properties: object) → StyleSheet[source]

Append a rule.

Parameters:
  • selector (str) – CSS selector.

  • declarations (Style or mapping or str, optional) – Declarations as accepted by Style. Defaults to None.

  • **properties – More declarations as keywords.

Returns:

StyleSheet – The sheet itself, for chaining.

Examples

>>> from svgwriter.model.attributes import StyleSheet
>>> StyleSheet().rule("rect", {"stroke": "blue"}).rule(".a", fill="red").css(" ")
'rect { stroke:blue } .a { fill:red }'
css(separator: str = '\n') → str[source]

Render the sheet as CSS text.

Parameters:

separator (str, optional) – Text placed between rules. Defaults to a newline.

Returns:

str – One selector { declarations } entry per rule.

Examples

>>> from svgwriter.model.attributes import StyleSheet
>>> StyleSheet().rule(".a", fill="red").css()
'.a { fill:red }'
class SupportsSVG(*args, **kwargs)[source]

Bases: Protocol

Anything that knows how to render itself as an attribute value.

A runtime-checkable protocol: any object with an svg_value method matches.

See also

format_value

Uses the protocol to serialize values.

Examples

>>> from svgwriter.model.attributes import SupportsSVG
>>> from svgwriter.model.units import Length
>>> isinstance(Length(1), SupportsSVG)
True
svg_value(precision: int = Ellipsis) → str[source]

Return the text to write into the SVG attribute.

Parameters:

precision (int, optional) – Maximum number of decimal places for numbers. Implementations default to the library default precision.

Returns:

str – The attribute value as SVG text.

class TextSink(*args, **kwargs)[source]

Bases: Protocol

A writable text stream.

A runtime-checkable protocol: any object with a write method matches, such as an open text file or io.StringIO.

Examples

>>> import io
>>> from svgwriter.model.attributes import TextSink
>>> isinstance(io.StringIO(), TextSink)
True
write(text: str, /) → object[source]

Write text to the stream.

Parameters:

text (str) – The text to write.

Returns:

object – Ignored; streams usually return the number of characters written.

class ViewBox(min_x: float, min_y: float, width: float, height: float)[source]

Bases: NamedTuple

The viewBox rectangle in user units.

A named tuple, so it unpacks as min_x, min_y, width, height.

Parameters:
  • min_x (float) – Top-left corner of the visible region.

  • min_y (float) – Top-left corner of the visible region.

  • width (float) – Size of the visible region.

  • height (float) – Size of the visible region.

See also

PreserveAspectRatio

How the box is fitted into the viewport.

Examples

>>> from svgwriter.model.attributes import ViewBox
>>> ViewBox(0, 0, 100, 50).svg_value()
'0 0 100 50'
min_x: float

Alias for field number 0

min_y: float

Alias for field number 1

width: float

Alias for field number 2

height: float

Alias for field number 3

classmethod parse(text: str) → ViewBox[source]

Parse viewBox text.

Parameters:

text (str) – Four numbers separated by spaces and/or commas.

Returns:

ViewBox – The parsed box.

Raises:

ValueError – If there are not four numbers, or the width or height is negative.

Examples

>>> from svgwriter.model.attributes import ViewBox
>>> ViewBox.parse("0,0 100 50")
ViewBox(min_x=0.0, min_y=0.0, width=100.0, height=50.0)
property aspect_ratio: float

Width divided by height; 0 when the height is zero.

Examples

>>> from svgwriter.model.attributes import ViewBox
>>> ViewBox(0, 0, 100, 50).aspect_ratio
2.0
svg_value(precision: int = 4) → str[source]

Serialize as attribute text.

Parameters:

precision (int, optional) – Maximum number of decimal places. Defaults to the library default precision.

Returns:

str – The four numbers separated by spaces.

Examples

>>> from svgwriter.model.attributes import ViewBox
>>> ViewBox(0, 0, 100.5, 50).svg_value()
'0 0 100.5 50'
format_value(value: object, precision: int = 4) → str[source]
format_value(value: str, precision: int = 4) → str
format_value(value: bool, precision: int = 4) → str
format_value(value: int, precision: int = 4) → str
format_value(value: float, precision: int = 4) → str
format_value(value: Enum, precision: int = 4) → str
format_value(value: tuple[object, ...] | list[object], precision: int = 4) → str
format_value(value: tuple[object, ...] | list[object], precision: int = 4) → str
format_value(value: ndarray, precision: int = 4) → str
format_value(value: generic, precision: int = 4) → str
format_value(value: Mapping[str, object], precision: int = 4) → str
format_value(value: Element, precision: int = 4) → str

Render a value as the text of an SVG attribute.

Dispatches on type: strings pass through, booleans become true/false, floats use the shortest form, sequences are space-separated (with x,y pairs for nested ones), NumPy arrays are flattened, enums use their value, and objects with an svg_value method render themselves. Other types use str.

Parameters:
  • value (object) – The value to render.

  • precision (int, optional) – Maximum number of decimal places for floats. Defaults to the library default precision.

Returns:

str – The attribute text.

See also

svgwriter.model.attributes.SupportsSVG

Protocol for self-rendering objects.

Examples

>>> from svgwriter.model.attributes import format_value
>>> format_value(1.5), format_value(True), format_value([1, 2.5])
('1.5', 'true', '1 2.5')
>>> format_value([(1, 2), (3, 4)])
'1,2 3,4'
parse_func_iri(text: str) → FuncIRI | None[source]

Parse url(...) text into a FuncIRI.

Parameters:

text (str) – Text such as "url(#grad)"; quotes inside the parentheses are removed.

Returns:

FuncIRI or None – The reference, or None when the text is not a url(...) value.

Examples

>>> from svgwriter.model.attributes import parse_func_iri
>>> parse_func_iri("url(#a)")
FuncIRI(target='#a')
>>> parse_func_iri("red") is None
True
py_name(name: str) → str[source]

Translate an SVG attribute name into a Python keyword.

Parameters:

name (str) – SVG attribute name.

Returns:

str – A valid Python identifier; reserved words get a trailing underscore.

See also

svg_name

The inverse mapping.

Examples

>>> from svgwriter.model.attributes import py_name
>>> py_name("viewBox")
'view_box'
>>> py_name("xlink:href")
'xlink_href'
>>> py_name("class")
'class_'
svg_name(name: str) → str[source]

Translate a Python keyword (stroke_width) into an SVG name.

Trailing underscores are dropped (class_, in_), xlink_ and xml_ become namespace prefixes, known camelCase attributes are restored, and remaining underscores become hyphens.

Parameters:

name (str) – Python keyword name.

Returns:

str – The SVG attribute name.

See also

py_name

The inverse mapping.

Examples

>>> from svgwriter.model.attributes import svg_name
>>> svg_name("stroke_width")
'stroke-width'
>>> svg_name("view_box")
'viewBox'
>>> svg_name("xlink_href")
'xlink:href'
>>> svg_name("class_")
'class'

Checking that a value’s dimension (length, angle, number) fits the attribute it is set on.

check_dimension(name: str, value: object) → None[source]

Refuse a value whose dimension does not fit the attribute name.

Lengths may not go where SVG wants an angle and angles not where it wants a length; a Quantity (an area, a length per angle, …) fits no attribute.

Parameters:
  • name (str) – The SVG attribute name.

  • value (object) – The value about to be stored.

Raises:

TypeError – If the dimension does not fit, naming the attribute and the dimension.

Examples

>>> import svgwriter as svg
>>> check_dimension("width", svg.mm(3) * svg.mm(2))
Traceback (most recent call last):
...
TypeError: width needs a length, got length²

CSS style sheets and computed values: parsing, selector matching and inheritance.

INHERITED: Final = frozenset({'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cursor', 'direction', 'fill', 'fill-opacity', 'fill-rule', 'font', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'image-rendering', 'kerning', 'letter-spacing', 'marker', 'marker-end', 'marker-mid', 'marker-start', 'pointer-events', 'shape-rendering', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-rendering', 'visibility', 'word-spacing', 'writing-mode'})

Properties that inherit by default (SVG 1.1, appendix N).

computed(element: Element, name: str, default: object = None, rules: Iterable[Rule] | None = None) → object[source]

Return the computed value of a property.

The value is the one specified on the element, else inherited from the nearest ancestor if the property inherits, else the default. The keyword inherit defers to the parent for any property.

Parameters:
  • element (Element) – The element to inspect.

  • name (str) – CSS property name, such as "fill".

  • default (object, optional) – Returned when no value applies. Defaults to None.

  • rules (iterable of Rule, optional) – Style rules to consult; collected from the element’s document when omitted. Defaults to None.

Returns:

object – The computed value.

See also

specified

The value set on the element itself.

Examples

>>> import svgwriter as svg
>>> from svgwriter.model.attributes.cascade import computed
>>> g = svg.Group(fill="green", opacity=0.5)
>>> rect = g.append(svg.Rect(width=1, height=1))
>>> computed(rect, "fill")
'green'
>>> computed(rect, "opacity", "1")
'1'
What the code above draws
css_declarations(element: Element, rules: Iterable[Rule]) → dict[str, str][source]

Return the declarations from style rules that apply to an element.

Conflicts are resolved by !important, then specificity, then source order.

Parameters:
  • element (Element) – The element to style.

  • rules (iterable of Rule) – Candidate rules, as from rules_of.

Returns:

dict of str to str – The winning value for each property.

Examples

>>> import svgwriter as svg
>>> from svgwriter.model.attributes.cascade import css_declarations
>>> from svgwriter.model.attributes.rules import parse_css
>>> rect = svg.Rect(0, 0, 1, 1, class_="a", id="r")
>>> rules = parse_css(".a { fill: red } #r { fill: blue }")
>>> css_declarations(rect, rules)
{'fill': 'blue'}
What the code above draws
matches(element: Element, selector: str) → bool[source]

Return whether an element matches a CSS selector.

Supports type, *, #id, .class, attribute selectors, :first-child and the descendant, child (>), adjacent (+) and general (~) sibling combinators.

Parameters:
  • element (Element) – The element to test.

  • selector (str) – A single selector, without commas.

Returns:

bool – True if the element matches.

Examples

>>> import svgwriter as svg
>>> from svgwriter.model.attributes.cascade import matches
>>> g = svg.Group(class_="icon")
>>> rect = g.append(svg.Rect(width=1, height=1))
>>> matches(rect, "g.icon > rect")
True
>>> matches(rect, ".other rect")
False
What the code above draws
resolve_styles(root: Element) → None[source]

Rewrite a tree so CSS and inline styles become presentation attributes.

The tree is modified in place: matching rule declarations and inline style values are written as attributes and the style attribute is removed; <style> sheets, now folded in, are removed too, so later lookups do not apply their rules a second time over inline values. Renderers that ignore CSS then see the same result. The CSS-only marker shorthand becomes marker-start, marker-mid and marker-end, and CSS units, which are case-insensitive (20PX), are written in the lower case attributes require.

Parameters:

root (Element) – The root of the tree to rewrite.

Examples

>>> import svgwriter as svg
>>> from svgwriter.model.attributes.cascade import resolve_styles
>>> doc = svg.parse('<svg xmlns="http://www.w3.org/2000/svg"><rect style="fill:red"/></svg>')
>>> resolve_styles(doc)
>>> next(doc.iter("rect")).attributes["fill"]
'red'
What the code above draws
specified(element: Element, name: str, rules: Iterable[Rule] | None = None) → object | None[source]

Return the value set directly on an element.

Looks at the inline style first, then matching style rules, then the presentation attribute. Nothing is inherited.

Parameters:
  • element (Element) – The element to inspect.

  • name (str) – CSS property name, such as "fill".

  • rules (iterable of Rule, optional) – Style rules to consult; collected from the element’s document when omitted. Defaults to None.

Returns:

object or None – The specified value, or None when the element does not set it.

See also

computed

The value after inheritance.

Examples

>>> import svgwriter as svg
>>> from svgwriter.model.attributes.cascade import specified
>>> specified(svg.Rect(0, 0, 1, 1, fill="red", style="opacity:.5"), "opacity")
'.5'
>>> specified(svg.Rect(0, 0, 1, 1), "fill") is None
True

Style rules: parsing CSS sheets and collecting the rules a tree’s <style> elements and theme carry.

class Rule(selector: str, specificity: tuple[int, int, int], order: int, declarations: tuple[tuple[str, str, bool], ...])[source]

Bases: object

One selector with its declarations.

Parameters:
  • selector (str) – A single CSS selector (no commas).

  • specificity (tuple of int) – (ids, classes, types) counts used to rank competing rules.

  • order (int) – Position in the style sheet; later rules win ties.

  • declarations (tuple of tuple) – (name, value, important) triples.

See also

parse_css

Produces rules from CSS text.

Examples

>>> from svgwriter.model.attributes.rules import parse_css
>>> rule = parse_css(".a { fill: red }")[0]
>>> rule.selector, rule.specificity, rule.declarations
('.a', (0, 1, 0), (('fill', 'red', False),))
selector: str
specificity: tuple[int, int, int]
order: int
declarations: tuple[tuple[str, str, bool], ...]
class RuleSet(rules: Iterable[Rule] = ())[source]

Bases: list[Rule]

Rules in cascade order, indexed by the rightmost compound selector of each, as browsers do.

Parameters:

rules (iterable of Rule) – The rules, in the order ties are broken.

Variables:
  • buckets (dict) – Candidates by (kind, name): the rightmost compound’s id, first class or tag, else universal.

  • attribute_names (tuple of str) – Every attribute an attribute selector of the set tests.

See also

rule_set

The shared set for some rules.

Examples

>>> from svgwriter.model.attributes.rules import RuleSet, parse_css
>>> rules = RuleSet(parse_css("rect { fill: red } .a > .b { fill: blue } :hover { fill: none }"))
>>> sorted(rules.buckets)
[('.', 'b'), ('tag', 'rect')]
buckets: dict[tuple[str, str], list[tuple[int, Rule, Selector]]]
candidates(tag: str, ident: str | None, classes: Iterable[str]) → list[tuple[int, Rule, Selector]][source]

The rules that can match an element, by its tag, id and classes, in set order.

Parameters:
  • tag (str) – The element’s tag.

  • ident (str or None) – Its id.

  • classes (iterable of str) – Its distinct class names.

Returns:

list of Candidate – (position, rule, selector) triples, by position.

Examples

>>> from svgwriter.model.attributes.rules import RuleSet, parse_css
>>> rules = RuleSet(parse_css("rect { fill: red } .a { fill: blue } #x { fill: none }"))
>>> [rule.selector for _, rule, _ in rules.candidates("rect", None, ["a"])]
['rect', '.a']
frozen_rules() → Generator[None, None, None][source]

Collect each tree’s style rules once for the block, for many lookups while no <style> changes.

Joins an enclosing block, so nesting is free.

Yields:

None

Examples

>>> import svgwriter as svg
>>> from svgwriter.model.attributes.rules import frozen_rules, rules_of
>>> doc = svg.parse('<svg xmlns="http://www.w3.org/2000/svg"><style>.a{fill:red}</style></svg>')
>>> with frozen_rules():
...     rules_of(doc) is rules_of(doc)
True
What the code above draws
parse_css(text: str, start: int = 0) → list[Rule][source]

Parse a style sheet into rules; @ blocks are skipped.

A rule with several comma-separated selectors becomes one Rule per selector. Comments are removed and !important is recorded per declaration.

Parameters:
  • text (str) – CSS text.

  • start (int, optional) – Order number given to the first rule, so rules from several sheets stay ordered. Defaults to 0.

Returns:

list of Rule – The parsed rules in source order.

See also

rules_of

Collect the rules of every <style> element.

Examples

>>> from svgwriter.model.attributes.rules import parse_css
>>> [r.selector for r in parse_css("rect, .a { fill: red } /* x */ #b{stroke:blue}")]
['rect', '.a', '#b']
rule_set(rules: Iterable[Rule]) → RuleSet[source]

The shared, indexed set for some rules: equal rules give the same set, so per-element memos stay valid.

Parameters:

rules (iterable of Rule) – The rules, in cascade order; a RuleSet is returned as is.

Returns:

RuleSet – The indexed rules.

Examples

>>> from svgwriter.model.attributes.rules import parse_css, rule_set
>>> rule_set(parse_css(".a { fill: red }")) is rule_set(parse_css(".a { fill: red }"))
True
rules_of(root: Element) → RuleSet[source]

Collect the rules of every <style> element under an element.

Rules a document attaches to its root by class name (its theme’s role styles) come first, for the classes the tree uses, so measuring before output sees the same styles as the output.

Parameters:

root (Element) – The element to search, including itself.

Returns:

RuleSet – The rules in document order, indexed; equal rules give the same shared set.

See also

parse_css

Parse a single sheet.

Examples

>>> import svgwriter as svg
>>> from svgwriter.model.attributes.rules import rules_of
>>> doc = svg.parse('<svg xmlns="http://www.w3.org/2000/svg"><style>.a{fill:red}</style></svg>')
>>> [rule.selector for rule in rules_of(doc)]
['.a']
What the code above draws
set_class_rules(root: Element, rules: dict[str, list[Rule]]) → None[source]

Attach rules by class name to root; rules_of() puts them first for the classes in use.

Parameters:
  • root (Element) – The root of a tree.

  • rules (dict of str to list of Rule) – The rules of each class name, such as a theme’s role styles.

Examples

>>> import svgwriter as svg
>>> from svgwriter.model.attributes.cascade import computed
>>> from svgwriter.model.attributes.rules import parse_css, set_class_rules
>>> root = svg.Svg(svg.rect(0, 0, 1, 1, class_="a"))
>>> set_class_rules(root, {"a": parse_css(".a { fill: red }")})
>>> computed(root[0], "fill")
'red'
What the code above draws