enable.savage.svg.svg_regex module

Small hand-written recursive descent parser for SVG <path> data.

In [1]: from svg_regex import svg_parser

In [3]: svg_parser.parse(‘M 10,20 30,40V50 60 70’) Out[3]: [(‘M’, [(10.0, 20.0), (30.0, 40.0)]), (‘V’, [50.0, 60.0, 70.0])]

In [4]: svg_parser.parse(‘M 0.6051.5’) # An edge case Out[4]: [(‘M’, [(0.60509999999999997, 0.5)])]

In [5]: svg_parser.parse(‘M 100-200’) # Another edge case Out[5]: [(‘M’, [(100.0, -200.0)])]

class enable.savage.svg.svg_regex.Lexer(lexicon)[source]

Bases: object

Break SVG path data into tokens.

The SVG spec requires that tokens are greedy. This lexer relies on Python’s regexes defaulting to greediness.

This style of implementation was inspired by this article:


Yield (token_type, str_data) tokens.

The last token will be (EOF, None) where EOF is the singleton object defined in this module.

class enable.savage.svg.svg_regex.SVGPathParser(lexer=<enable.savage.svg.svg_regex.Lexer object>)[source]

Bases: object

Parse SVG <path> data into a list of commands.

Each distinct command will take the form of a tuple (command, data). The command is just the character string that starts the command group in the <path> data, so ‘M’ for absolute moveto, ‘m’ for relative moveto, ‘Z’ for closepath, etc. The kind of data it carries with it depends on the command. For ‘Z’ (closepath), it’s just None. The others are lists of individual argument groups. Multiple elements in these lists usually mean to repeat the command. The notable exception is ‘M’ (moveto) where only the first element is truly a moveto. The remainder are implicit linetos.

See the SVG documentation for the interpretation of the individual elements for each command.

The main method is parse(text). It can only consume actual strings, not filelike objects or iterators.


Parse a string of SVG <path> data.

rule_closepath(next, token)[source]
rule_coordinate(next, token)[source]
rule_coordinate_pair(next, token)[source]
rule_curveto1(next, token)[source]
rule_curveto2(next, token)[source]
rule_curveto3(next, token)[source]
rule_elliptical_arc(next, token)[source]
rule_moveto_or_lineto(next, token)[source]
rule_orthogonal_lineto(next, token)[source]
rule_svg_path(next, token)[source]