|
1 | | -# Copyright (c) 2021 Chris Reed |
| 1 | +# Copyright (c) 2021-2023 Chris Reed |
2 | 2 | # |
3 | 3 | # SPDX-License-Identifier: Apache-2.0 |
4 | 4 | # |
|
14 | 14 | # See the License for the specific language governing permissions and |
15 | 15 | # limitations under the License. |
16 | 16 |
|
| 17 | +from __future__ import annotations |
| 18 | + |
17 | 19 | import atexit |
18 | 20 | import ctypes.util |
19 | 21 | import functools |
20 | 22 | import platform |
21 | 23 | import sys |
22 | 24 | from typing import (Any, Optional, TYPE_CHECKING) |
23 | 25 |
|
24 | | -# importlib.resources isn't available before Python 3.7, so if importing it |
25 | | -# fails we import the backport. |
26 | | -try: |
27 | | - from importlib import resources |
28 | | -except ImportError: |
29 | | - import importlib_resources as resources # type:ignore |
| 26 | +import importlib_resources |
30 | 27 |
|
31 | 28 | from ._version import version as __version__ |
32 | 29 |
|
|
46 | 43 | _LIBRARY_NAME = 'libusb-1.0' + _LIBRARY_EXT |
47 | 44 |
|
48 | 45 | @functools.lru_cache() |
49 | | -def get_library_path() -> Optional["Path"]: |
50 | | - """@brief Returns the path to included library, if there is one.""" |
51 | | - if resources.is_resource(__name__, _LIBRARY_NAME): |
52 | | - path_resource = resources.path(__name__, _LIBRARY_NAME) |
53 | | - path = path_resource.__enter__() |
| 46 | +def get_library_path() -> Optional[Path]: |
| 47 | + """@brief Returns the path to included library, if there is one. |
| 48 | +
|
| 49 | + The path is valid until the process exits. If the library was extracted from a zip in order to |
| 50 | + be accessible as a file, it will be cleaned up with the process exits. |
| 51 | + """ |
| 52 | + lib_resource = importlib_resources.files(__name__).joinpath(_LIBRARY_NAME) |
| 53 | + if lib_resource.is_file(): |
| 54 | + path_context = importlib_resources.as_file(lib_resource) |
| 55 | + path = path_context.__enter__() |
54 | 56 |
|
55 | 57 | @atexit.register |
56 | 58 | def cleanup(): |
57 | | - path_resource.__exit__(None, None, None) |
| 59 | + path_context.__exit__(None, None, None) |
58 | 60 |
|
59 | 61 | return path |
60 | 62 | else: |
@@ -89,7 +91,7 @@ def find_library(candidate: str) -> Optional[str]: |
89 | 91 | # dependency unless these functions are used. |
90 | 92 |
|
91 | 93 | @functools.lru_cache() |
92 | | -def get_libusb1_backend() -> Optional["IBackend"]: |
| 94 | +def get_libusb1_backend() -> Optional[IBackend]: |
93 | 95 | """@brief Return a usb backend for pyusb.""" |
94 | 96 | import usb.backend.libusb1 |
95 | 97 | return usb.backend.libusb1.get_backend(find_library=find_library) |
|
0 commit comments