I made an svg diagram from a stim circuit:

import stim
circuit = stim.Circuit("""
    H 0
    CX 0 1
    M 0 1
diagram = circuit.diagram("timeline-svg")

enter image description here

I tried to write the diagram to a file, but I got an error:

with open('diagram.svg', 'w') as f:
TypeError: write() argument must be str, not stim._DiagramHelper

How do I save the diagram to an SVG image file?

  • 1
    $\begingroup$ Got asked this outside of QCSE. Copying it here for posterity. $\endgroup$ Dec 1, 2023 at 6:36

1 Answer 1


Do this:

with open('diagram.svg', 'w') as f:
    print(diagram, file=f)

Or this:

with open('diagram.svg', 'w') as f:

The stim._DiagramHelper class has a __str__ method that returns the contents of the SVG file. The diagram method could just return a string... but then tools like Jupyter notebook wouldn't display it as an image.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.