{"record":{"id":"ab64769be7640e7b","repo":"matplotlib/matplotlib","slug":"invalid-type-for-key-metadata-expected-str-not","errorCode":null,"errorMessage":"Invalid type for {key} metadata. Expected str, not {type(info)}.","messagePattern":"Invalid type for (.+?) metadata\\. Expected str, not (.+?)\\.","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"lib/matplotlib/backends/backend_svg.py","lineNumber":287,"sourceCode":"                or type == 'rotate' and value == (0,)):\n            continue\n        if type == 'matrix' and isinstance(value, Affine2DBase):\n            value = value.to_values()\n        parts.append('{}({})'.format(\n            type, ' '.join(_short_float_fmt(x) for x in value)))\n    return ' '.join(parts)\n\n\ndef _generate_css(attrib):\n    return \"; \".join(f\"{k}: {v}\" for k, v in attrib.items())\n\n\n_capstyle_d = {'projecting': 'square', 'butt': 'butt', 'round': 'round'}\n\n\ndef _check_is_str(info, key):\n    if not isinstance(info, str):\n        raise TypeError(f'Invalid type for {key} metadata. Expected str, not '\n                        f'{type(info)}.')\n\n\ndef _check_is_iterable_of_str(infos, key):\n    if np.iterable(infos):\n        for info in infos:\n            if not isinstance(info, str):\n                raise TypeError(f'Invalid type for {key} metadata. Expected '\n                                f'iterable of str, not {type(info)}.')\n    else:\n        raise TypeError(f'Invalid type for {key} metadata. Expected str or '\n                        f'iterable of str, not {type(infos)}.')\n\n\nclass RendererSVG(RendererBase):\n    def __init__(self, width, height, svgwriter, basename=None, image_dpi=72,\n                 *, metadata=None):\n        self.width = width","sourceCodeStart":269,"sourceCodeEnd":305,"githubUrl":"https://github.com/matplotlib/matplotlib/blob/b379c1b69e012b142c0f496a52bcb30513802d72/lib/matplotlib/backends/backend_svg.py#L269-L305","documentation":"The SVG writer validates Dublin-Core metadata fields that must be a single string (Title, Coverage, Description, Format, Identifier, Language, Relation, Source, and the already-normalized Date) via _check_is_str. If the value is not a str instance it raises this TypeError naming the offending key and the actual type.","triggerScenarios":"Passing metadata={...} to fig.savefig(..., format='svg') where one of the single-string keys holds a non-string, e.g. metadata={'Title': 42}, {'Description': None} handled elsewhere but {'Format': ('svg',)} or {'Identifier': 123}.","commonSituations":"Feeding metadata pulled from JSON config or a database where numbers appear (e.g. Title stored as numeric ID); passing a list where a single string is expected; copy-pasting metadata dicts written for the PDF backend whose value conventions differ.","solutions":["Coerce the value to str before saving: str(value)","Use a single string for single-value keys: metadata={'Title': 'My plot'}","Validate the metadata dict against the SVG schema (str for these keys) before calling savefig"],"exampleFix":"# before\nfig.savefig('out.svg', metadata={'Title': 42})\n\n# after\nfig.savefig('out.svg', metadata={'Title': str(42)})","handlingStrategy":"validation","validationCode":"STR_KEYS = {'Title', 'Coverage', 'Description', 'Format',\n             'Identifier', 'Language', 'Relation', 'Source'}\n\ndef validate_svg_metadata(md):\n    for k in STR_KEYS:\n        if k in md and not isinstance(md[k], str):\n            md[k] = str(md[k])\n    return md\n\n# fig.savefig('out.svg', metadata=validate_svg_metadata(md))","typeGuard":"def is_str_metadata(v: object) -> bool:\n    return isinstance(v, str)","tryCatchPattern":"try:\n    fig.savefig('out.svg', metadata=md)\nexcept TypeError as e:\n    if 'metadata' in str(e):\n        md = {k: str(v) for k, v in md.items()}\n        fig.savefig('out.svg', metadata=md)\n    else:\n        raise","preventionTips":["Type metadata dicts in code as dict[str, object] and normalize to str at the boundary","Write a unit test that saves a sample SVG with your production metadata dict","Keep metadata construction in one helper so validation lives in one place"],"tags":["matplotlib","svg","metadata","type-validation"],"backgroundTag":"metadata-type-validation","analyzedSha":"b379c1b69e012b142c0f496a52bcb30513802d72","analyzedAt":"2026-08-21T23:31:55.468Z","schemaVersion":2},"datasetVersion":"2026-08-22T04:17:13.399Z"}