Skip to content

Fix DeprecationWarning when setting header.dtype on NumPy 2.5+#76

Open
McHaillet wants to merge 1 commit into
ccpem:masterfrom
McHaillet:fix-dtype-deprecation-numpy25
Open

Fix DeprecationWarning when setting header.dtype on NumPy 2.5+#76
McHaillet wants to merge 1 commit into
ccpem:masterfrom
McHaillet:fix-dtype-deprecation-numpy25

Conversation

@McHaillet

Copy link
Copy Markdown

@colinpalmer Just a heads up, I thought I would have a fix at solving this issue with claude because it seemed simple enough, but that might not be the case.

Mainly the original code had this comment which this PR exactly changes. From the text it's not immediately clear to me what mrcfile is trying to achieve here specifically with dtype assigning:

# Assigning to .dtype is discouraged but not yet deprecated, and
# none of the other methods (view, astype) achieve quite what we
# need here

but my guess its because of maintaining the original object, which is no longer possible with 2.5, so some fix is definitely needed.


Summary of the fix (closes #75):

  • Replaced all in-place header.dtype = .../arr.dtype = ... mutations with .view(new_dtype) in mrcinterpreter.py and mrcobject.py, since numpy
    2.5 deprecates in-place dtype assignment entirely (confirmed for plain ndarray too, not just recarray — no in-place-safe alternative exists).
  • One spot (update_header_from_data) required reassigning self._header since .view() returns a new object; this is a small behavior change. A header reference grabbed before calling set_data() with byte-swapped data no longer auto-reflects the byte-order change. Updated the
    one affected test (test_header_byte_order_is_changed_by_data_with_opposite_order) to re-fetch mrc.header instead.
  • Fixed three test-code call sites in test_mrcfile.py using the same deprecated pattern.
  • Verified against the issue's exact repro script, the full test suite (861 tests) in both the existing environment and a fresh conda env with Python 3.14 + numpy 2.5.0, plus mypy and ruff — all clean.

Closes #75

NumPy 2.5 deprecates assigning to .dtype on an existing array. Replace
in-place dtype mutation with view()-based reinterpretation in
mrcinterpreter.py and mrcobject.py.

In update_header_from_data(), this means a header reference obtained
before calling set_data() with byte-swapped data no longer reflects the
byte-order change in place; callers must re-fetch mrc.header afterwards.
The affected test has been updated accordingly.

Fixes ccpem#75
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.

DeprecationWarning: setting header.dtype is deprecated in NumPy 2.5

1 participant