matplotlib/matplotlib · error · TypeError

Invalid type for {key} metadata. Expected str, not {type(inf

Error message

Invalid type for {key} metadata. Expected str, not {type(info)}.

What it means

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.

Source

Thrown at lib/matplotlib/backends/backend_svg.py:287

                or type == 'rotate' and value == (0,)):
            continue
        if type == 'matrix' and isinstance(value, Affine2DBase):
            value = value.to_values()
        parts.append('{}({})'.format(
            type, ' '.join(_short_float_fmt(x) for x in value)))
    return ' '.join(parts)


def _generate_css(attrib):
    return "; ".join(f"{k}: {v}" for k, v in attrib.items())


_capstyle_d = {'projecting': 'square', 'butt': 'butt', 'round': 'round'}


def _check_is_str(info, key):
    if not isinstance(info, str):
        raise TypeError(f'Invalid type for {key} metadata. Expected str, not '
                        f'{type(info)}.')


def _check_is_iterable_of_str(infos, key):
    if np.iterable(infos):
        for info in infos:
            if not isinstance(info, str):
                raise TypeError(f'Invalid type for {key} metadata. Expected '
                                f'iterable of str, not {type(info)}.')
    else:
        raise TypeError(f'Invalid type for {key} metadata. Expected str or '
                        f'iterable of str, not {type(infos)}.')


class RendererSVG(RendererBase):
    def __init__(self, width, height, svgwriter, basename=None, image_dpi=72,
                 *, metadata=None):
        self.width = width

View on GitHub (pinned to b379c1b69e)

Solutions

  1. Coerce the value to str before saving: str(value)
  2. Use a single string for single-value keys: metadata={'Title': 'My plot'}
  3. Validate the metadata dict against the SVG schema (str for these keys) before calling savefig

Example fix

# before
fig.savefig('out.svg', metadata={'Title': 42})

# after
fig.savefig('out.svg', metadata={'Title': str(42)})
Defensive patterns

Strategy: validation

Validate before calling

STR_KEYS = {'Title', 'Coverage', 'Description', 'Format',
             'Identifier', 'Language', 'Relation', 'Source'}

def validate_svg_metadata(md):
    for k in STR_KEYS:
        if k in md and not isinstance(md[k], str):
            md[k] = str(md[k])
    return md

# fig.savefig('out.svg', metadata=validate_svg_metadata(md))

Type guard

def is_str_metadata(v: object) -> bool:
    return isinstance(v, str)

Try / catch

try:
    fig.savefig('out.svg', metadata=md)
except TypeError as e:
    if 'metadata' in str(e):
        md = {k: str(v) for k, v in md.items()}
        fig.savefig('out.svg', metadata=md)
    else:
        raise

Prevention

When it happens

Trigger: 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}.

Common situations: 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.

Related errors


AI-assisted analysis of matplotlib/matplotlib@b379c1b69e (2026-08-21). Data as JSON: /api/errors/ab64769be7640e7b. Report an issue: GitHub.