Convenience functions

For a one-shot read or a small edit, fitsy offers module-level helpers. Each one opens the file, does its work, and closes it again:

For repeated access to one file, open it once with fitsy.open(). That is faster, because each helper above does its own open and close.

Example

"""Module-level convenience functions: `getdata`, `getval`, `setval`,
`delval`, `info` and `append`.

Each one opens the file, does its work, and closes it again. Use them
for a single read or a single write. Use `fitsy.open` instead when you
need several operations on one file.

Run from the repository root:

    python examples/python/convenience.py
"""

import os
import tempfile

import fitsy
import numpy as np

with tempfile.TemporaryDirectory() as td:
    path = os.path.join(td, "scratch.fits")
    fitsy.write(
        path,
        [
            fitsy.image(
                np.arange(16, dtype="i2").reshape(4, 4),
                header={"OBJECT": "demo"},
            )
        ],
    )

    # One-shot reads.
    arr = fitsy.getdata(path)
    print("shape:", arr.shape)

    arr2, hdr = fitsy.getdata(path, header=True)
    print("OBJECT:", hdr["OBJECT"])

    obj = fitsy.getval(path, "OBJECT")
    print("getval :", obj)

    # One-shot writes (open + edit + atomic rewrite).
    fitsy.setval(path, "OBSERVER", value="Edwin Hubble", comment="discoverer")
    fitsy.setval(path, "OBJECT", value="NGC 2403")
    fitsy.delval(path, "OBSERVER")

    # Stream a new HDU onto the end without rewriting the existing
    # file. `fitsy.append` takes a raw numpy array and an optional
    # header dict, not a builder.
    fitsy.append(
        path,
        np.zeros((2, 2), dtype="f4"),
        header={"EXTNAME": "MASK"},
    )

    # `info` returns a list of (index, name, ver, kind, dims) tuples.
    for index, name, ver, kind, dims in fitsy.info(path):
        print(f"{index}: {name or '(primary)'} v{ver} {kind} {dims}")