Skip to content

fix: preserve align label groups during pickling (swev-id: matplotlib__matplotlib-25332)#61

Open
casey-brooks wants to merge 1 commit intomatplotlib__matplotlib-25332from
fix-align-labels-pickle-278
Open

fix: preserve align label groups during pickling (swev-id: matplotlib__matplotlib-25332)#61
casey-brooks wants to merge 1 commit intomatplotlib__matplotlib-25332from
fix-align-labels-pickle-278

Conversation

@casey-brooks
Copy link

Summary

  • serialize _align_label_groups as axis indices during pickling and rebuild Grouper instances when unpickled
  • drop weakref-backed groupers from the stored state and seed empty groupers when no serialized data is present
  • add a regression test that exercises fig.align_labels() across a pickle round-trip

Reproduction Script

import matplotlib.pyplot as plt
import pickle

fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

time = [0, 1, 2, 3, 4]
speed = [40000, 4300, 4500, 4700, 4800]
acc = [10, 11, 12, 13, 14]
ax1.plot(time, speed)
ax1.set_ylabel('speed')
ax2.plot(time, acc)
ax2.set_ylabel('acc')

fig.align_labels()

pickle.dumps(fig)

Observed Failure (pre-fix)

Traceback (most recent call last):
  File "<stdin>", line 19, in <module>
TypeError: cannot pickle 'weakref.ReferenceType' object

Fix Details

  • map each aligned label group to the integer indices of the axes in Figure.axes
  • persist the serialized mapping in Figure.__getstate__ while omitting the unpicklable groupers
  • reconstruct fresh cbook.Grouper instances in Figure.__setstate__ and join axes according to the serialized indices
  • ensure the serialization logic tolerates missing data for old pickles by seeding empty groupers
  • add a pickle round-trip test validating the alignment metadata is retained

Files Touched

  • lib/matplotlib/figure.py
  • lib/matplotlib/tests/test_figure.py

References

@casey-brooks casey-brooks requested a review from a team December 25, 2025 12:47
@casey-brooks
Copy link
Author

Test & Lint Summary

  • MPLBACKEND=Agg PYTHONPATH=/workspace/matplotlib/lib PYTEST_ADDOPTS='-W ignore::DeprecationWarning' .venv/bin/pytest lib/matplotlib/tests/test_figure.py --maxfail=1 → 114 passed, 14 skipped
  • .venv/bin/ruff check lib/matplotlib/figure.py lib/matplotlib/tests/test_figure.py → no issues

Copy link

@noa-lucent noa-lucent left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks solid. getstate/setstate now serialise the alignment groups as axis indices and rebuild groupers on load, so pickle no longer trips over weakrefs. Regression test covers the round-trip and preserves group membership.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants