Coverage for python/lsst/resources/packageresource.py: 100%

22 statements  

« prev     ^ index     » next       coverage.py v6.5.0, created at 2023-01-06 01:38 -0800

1# This file is part of lsst-resources. 

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 

12import contextlib 

13import logging 

14from typing import IO, Iterator, Optional 

15 

16import pkg_resources 

17 

18__all__ = ("PackageResourcePath",) 

19 

20from ._resourcePath import ResourcePath 

21 

22log = logging.getLogger(__name__) 

23 

24 

25class PackageResourcePath(ResourcePath): 

26 """URI referring to a Python package resource. 

27 

28 These URIs look like: ``resource://lsst.daf.butler/configs/file.yaml`` 

29 where the network location is the Python package and the path is the 

30 resource name. 

31 """ 

32 

33 def exists(self) -> bool: 

34 """Check that the python resource exists.""" 

35 return pkg_resources.resource_exists(self.netloc, self.relativeToPathRoot) 

36 

37 def read(self, size: int = -1) -> bytes: 

38 """Read the contents of the resource.""" 

39 with pkg_resources.resource_stream(self.netloc, self.relativeToPathRoot) as fh: 

40 return fh.read(size) 

41 

42 @contextlib.contextmanager 

43 def open( 

44 self, 

45 mode: str = "r", 

46 *, 

47 encoding: Optional[str] = None, 

48 prefer_file_temporary: bool = False, 

49 ) -> Iterator[IO]: 

50 # Docstring inherited. 

51 if "r" not in mode or "+" in mode: 

52 raise RuntimeError(f"Package resource URI {self} is read-only.") 

53 if "b" in mode: 

54 with pkg_resources.resource_stream(self.netloc, self.relativeToPathRoot) as buffer: 

55 yield buffer 

56 else: 

57 with super().open(mode, encoding=encoding, prefer_file_temporary=prefer_file_temporary) as buffer: 

58 yield buffer