Skip to content

FITS checksum comments set by add_checksum(when=...) are overwritten on flush in update mode #20789

Open

Description

@cgobat

Description

When a FITS file containing existing CHECKSUM and DATASUM keywords is opened with mode="update", calling add_checksum(when=...) correctly updates the checksum comments in memory. However, when the HDUList is flushed or closed, the comments are overwritten with Astropy's default timestamp comments.

This happens because _update_checksum() calls add_checksum() without passing a when argument, even if the user has already explicitly updated the checksums with custom comments.

It seems like it might be preferable for automatic checksum updates to preserve existing comments, particularly when the checksum cards have already been explicitly updated by the user.

Expected behavior

An explicit call to add_checksum(when=...) should preserve the supplied comments when the file is saved. Automatic checksum recalculation should not silently overwrite them.

How to Reproduce

from astropy.io import fits

orig_header = fits.getheader("astropy_demo.fits.gz")
print(orig_header.comments["CHECKSUM"]) # HDU already has a CHECKSUM and DATASUM

with fits.open("astropy_demo.fits.gz", mode="update") as hdul:
    hdul[0].data[0, 0] = 5 # change the data
    hdul[0].add_checksum(when="This is a custom `when` comment")
    print(hdul[0].header.comments["CHECKSUM"]) # confirm that the custom comment did take

new_header = fits.getheader("astropy_demo.fits.gz")
print(new_header.comments["CHECKSUM"]) # overwritten by default `when` comment

astropy_demo.fits.gz

(also works with a non-gzipped FITS file, but GitHub only allows .gz attachments)

Versions

import astropy
astropy.system_info()
platform
--------
platform.platform() = 'Linux-7.0.0-42-generic-x86_64-with-glibc2.39'
platform.version() = '#42~24.04.1-Ubuntu SMP PREEMPT_DYNAMIC Mon Oct 19 14:43:01 UTC 2'
platform.python_version() = '3.13.18'

packages
--------
astropy              8.0.2
numpy                2.5.4
scipy                1.18.1
matplotlib           3.11.2
pandas               3.1.0
pyerfa               2.0.1.5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions