Coverage for python/lsst/images/serialization/_backends.py: 38%

26 statements  

« prev     ^ index     » next       coverage.py v7.14.1, created at 2026-06-10 18:02 +0000

1# This file is part of lsst-images. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

5# (https://www.lsst.org). 

6# See the COPYRIGHT file at the top-level directory of this distribution 

7# for details of code ownership. 

8# 

9# Use of this source code is governed by a 3-clause BSD-style 

10# license that can be found in the LICENSE file. 

11 

12from __future__ import annotations 

13 

14__all__ = ("Backend", "backend_for_path") 

15 

16import dataclasses 

17from collections.abc import Callable 

18from typing import TYPE_CHECKING 

19 

20from lsst.resources import ResourcePathExpression 

21 

22if TYPE_CHECKING: 

23 from ._input_archive import InputArchive 

24 

25 

26@dataclasses.dataclass(frozen=True) 

27class Backend: 

28 """A file-format backend resolved from a path suffix. 

29 

30 Bundles the backend's free ``write`` function and its `InputArchive` 

31 subclass. Reading goes through the generic ``open`` / ``read`` in 

32 `lsst.images.serialization`, which use the `InputArchive`'s 

33 ``get_basic_info`` and ``open_tree``. 

34 """ 

35 

36 name: str 

37 write: Callable[..., object] 

38 input_archive: type[InputArchive] 

39 

40 

41def backend_for_path(path: ResourcePathExpression) -> Backend: 

42 """Return the `Backend` for ``path`` based on its file extension. 

43 

44 Supported extensions: ``.fits`` / ``.fits.gz`` (FITS), ``.sdf`` / 

45 ``.ndf`` (NDF), and ``.json`` (JSON). The NDF and FITS backends are 

46 imported lazily so optional dependencies (e.g. ``h5py``) are only 

47 required when actually used. 

48 

49 Raises 

50 ------ 

51 ValueError 

52 If the extension is not recognised. 

53 """ 

54 s = str(path) 

55 if s.endswith(".fits") or s.endswith(".fits.gz"): 

56 from ..fits import FitsInputArchive 

57 from ..fits import write as fits_write 

58 

59 return Backend("fits", fits_write, FitsInputArchive) 

60 if s.endswith(".sdf") or s.endswith(".ndf"): 

61 from ..ndf import NdfInputArchive 

62 from ..ndf import write as ndf_write 

63 

64 return Backend("ndf", ndf_write, NdfInputArchive) 

65 if s.endswith(".json"): 

66 from ..json import JsonInputArchive 

67 from ..json import write as json_write 

68 

69 return Backend("json", json_write, JsonInputArchive) 

70 raise ValueError( 

71 f"Unrecognised file extension: {path!r}; expected one of .fits, .fits.gz, .sdf, .ndf, .json." 

72 )