Skip to content

fix: cache flush_only_netcdf_file class to fix pickling (GH#11323)#11414

Closed
C1-BA-B1-F3 wants to merge 1 commit into
pydata:mainfrom
C1-BA-B1-F3:fix-11323-scipy-pickle
Closed

fix: cache flush_only_netcdf_file class to fix pickling (GH#11323)#11414
C1-BA-B1-F3 wants to merge 1 commit into
pydata:mainfrom
C1-BA-B1-F3:fix-11323-scipy-pickle

Conversation

@C1-BA-B1-F3

Copy link
Copy Markdown

What this fixes

Fixes #11323 - Opening multiple scipy-backed datasets from file-like objects breaks pickling of previously-opened datasets.

Root cause

The _PickleWorkaround pattern in scipy_.py created a new flush_only_netcdf_file class on each call to _open_scipy_netcdf(). When a second dataset was opened:

  1. A new class C2 was created inside _open_scipy_netcdf()
  2. _PickleWorkaround.add_cls() stored C2, overwriting the previous C1
  3. Pickling ds1 (created with C1) failed because pickle found C2 via qualname lookup, not C1
_pickle.PicklingError: Can't pickle <class 'xarray.backends.scipy_._PickleWorkaround.flush_only_netcdf_file'>: 
it's not the same object as xarray.backends.scipy_._PickleWorkaround.flush_only_netcdf_file

Fix

Cache the flush_only_netcdf_file class in a module-level variable so it's created once and reused. This preserves the lazy scipy import while ensuring class identity is stable.

Testing

Added regression test test_scipy_pickle_after_multiple_opens that reproduces the exact scenario from the issue. All existing scipy backend tests pass.

Related

The _PickleWorkaround pattern created a new flush_only_netcdf_file class on
each call to _open_scipy_netcdf(). This broke pickling because subsequent
calls overwrote _PickleWorkaround.flush_only_netcdf_file with a new class
object, making previously-created instances unpicklable.

Fix: Cache the class in a module-level variable _flush_only_class so it's
only created once. This preserves the lazy scipy import while ensuring class
identity is stable across multiple opens.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2026.4.0 breaks pickling with backends.scipy_

1 participant