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:
objectA plain IRI, local (
#id) or external.elementis the referenced element when the IRI was made from one; it lets documents put unplaced definitions into<defs>automatically.- Parameters:
See also
FuncIRIThe
url(...)form.
Examples
>>> from svgwriter.model.attributes import IRI >>> str(IRI.local("grad")) '#grad'
- 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
#, orNonewhen 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'
- 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:
KeywordAlignment values of
preserveAspectRatio.CENTERis an alias ofX_MID_Y_MID, the default.See also
PreserveAspectRatioCombines 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:
See also
LengthAttrAttribute 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¶
- class FuncIRI(target: str, element: Element | None = None)[source]¶
Bases:
IRIA functional IRI,
url(...), as used by paint and filter.Takes the same parameters as IRI.
See also
parse_func_iriParse
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:
KeywordWhether the viewBox is scaled to fit entirely or to cover the viewport.
See also
PreserveAspectRatioUses 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:
objectHow 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
deferkeyword (only meaningful onimage). Defaults to False.
See also
ViewBoxThe rectangle being fitted.
Examples
>>> from svgwriter.model.attributes import Align, MeetOrSlice, PreserveAspectRatio >>> str(PreserveAspectRatio(Align.X_MIN_Y_MIN, MeetOrSlice.SLICE)) 'xMinYMin slice'
- meet_or_slice: MeetOrSlice = 'meet'¶
- classmethod parse(text: str) PreserveAspectRatio[source]¶
Parse
preserveAspectRatiotext.- 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;
meetis 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
styleattribute.Keys accept Python spelling (
stroke_width) or CSS spelling (stroke-width). AssigningNoneremoves a declaration. It is a mutable mapping that keeps insertion order.- Parameters:
See also
StyleSheetBuilder 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
styleattribute.- 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:
objectBuilder for the text of a
<style>element.- Parameters:
rules (iterable of tuple, optional) – Initial
(selector, declarations)pairs. Defaults to none.
See also
StyleA 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:
- 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:
ProtocolAnything that knows how to render itself as an attribute value.
A runtime-checkable protocol: any object with an
svg_valuemethod matches.See also
format_valueUses the protocol to serialize values.
Examples
>>> from svgwriter.model.attributes import SupportsSVG >>> from svgwriter.model.units import Length >>> isinstance(Length(1), SupportsSVG) True
- class TextSink(*args, **kwargs)[source]¶
Bases:
ProtocolA writable text stream.
A runtime-checkable protocol: any object with a
writemethod matches, such as an open text file or io.StringIO.Examples
>>> import io >>> from svgwriter.model.attributes import TextSink >>> isinstance(io.StringIO(), TextSink) True
- class ViewBox(min_x: float, min_y: float, width: float, height: float)[source]¶
Bases:
NamedTupleThe
viewBoxrectangle in user units.A named tuple, so it unpacks as
min_x, min_y, width, height.- Parameters:
See also
PreserveAspectRatioHow 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'
- classmethod parse(text: str) ViewBox[source]¶
Parse
viewBoxtext.- 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 (withx,ypairs for nested ones), NumPy arrays are flattened, enums use their value, and objects with ansvg_valuemethod render themselves. Other types use str.- Parameters:
- Returns:
str – The attribute text.
See also
svgwriter.model.attributes.SupportsSVGProtocol 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
Nonewhen the text is not aurl(...)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_nameThe 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_andxml_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_nameThe 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:
- 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
inheritdefers 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
specifiedThe 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'
- 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:
- 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'}
- matches(element: Element, selector: str) bool[source]¶
Return whether an element matches a CSS selector.
Supports type,
*,#id,.class, attribute selectors,:first-childand the descendant, child (>), adjacent (+) and general (~) sibling combinators.- Parameters:
- 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
- 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
stylevalues are written as attributes and thestyleattribute 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-onlymarkershorthand becomesmarker-start,marker-midandmarker-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'
- 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
stylefirst, then matching style rules, then the presentation attribute. Nothing is inherited.- Parameters:
- Returns:
object or None – The specified value, or
Nonewhen the element does not set it.
See also
computedThe 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:
objectOne selector with its declarations.
- Parameters:
See also
parse_cssProduces 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),))
- class RuleSet(rules: Iterable[Rule] = ())[source]¶
-
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:
See also
rule_setThe 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')]
- 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:
- 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
- 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
!importantis recorded per declaration.- Parameters:
- Returns:
list of Rule – The parsed rules in source order.
See also
rules_ofCollect 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_cssParse 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']
- 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:
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'