Skip to content

TypeError exception on style class name with dash character (inkex python module)

Summary:

Here is the python script that show the bug and the solution:

# I dont use inkscape but i use inkex as a python module for my mathmml project
from sys import path

path.append("/usr/share/inkscape/extensions")

# load the document svg with style sheets having class name with dash character
from inkex.elements._base import load_svg

dom = load_svg(
    rb"""
<svg xmlns:xlink="http://www.w3.org/1999/xlink" class="mjx-svg-math" xmlns="http://www.w3.org/2000/svg" >
	<style type="text/css">
		.mjx-svg-mo {fill:#0066CC}
		.mjx-svg-mi {fill:#FF3300;stroke:none}
		.mjx-svg-mfrac {fill:#FFCC00}
		.mjx-svg-mn {fill:#333366}
		.mjx-svg-mtext {fill:#3e9ade}
		.mjx-svg-menclose line {stroke:grey}
		.mjx-svg-mrow {fill:brown}
    </style>
	<g class="mjx-svg-mi mjx-svg-mn" id="deg"></g>
</svg>"""
)
# dom.getroot().root.stylesheets will parse the style elements and produce error
try:
    for x in dom.getroot().root.stylesheets.lookup("deg"):
        break
except Exception as ex:
    print("ERROR", ex)  # 'float' object is not iterable (TypeError)

# The solution is to modify ConditionalRule.step_to_xpath entry with '\.(\w+)' to '\.([-\w]+)'
from inkex.styles import ConditionalRule
from re import compile as regex

a = ConditionalRule.step_to_xpath
for i, v in enumerate(a):
    if r"\.(\w+)" == v[0].pattern:
        a[i] = (regex(r"\.([-\w]+)"), v[1])
        break

# Now there is no error
for x in dom.getroot().root.stylesheets.lookup("deg"):
    print("OK", x)
Edited by biojet1
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information