|
8 | 8 | mat = {"csr": [rowp, colind, data], "shape": [nrow, ncols]} # A csr matrix |
9 | 9 | mat = {"csc": [colp, rowind, data], "shape": [nrow, ncols]} # A csc matrix |
10 | 10 | """ |
11 | | - |
12 | 11 | # Standard Python modules |
| 12 | +import contextlib |
13 | 13 | import importlib |
14 | 14 | import os |
15 | 15 | import sys |
@@ -576,6 +576,20 @@ def _broadcast_to_array(name: str, value: ArrayType, n_values: int, allow_none: |
576 | 576 | return value |
577 | 577 |
|
578 | 578 |
|
| 579 | +@contextlib.contextmanager |
| 580 | +def _prepend_path(path: Union[str, Sequence[str]]): |
| 581 | + """Context manager which temporarily prepends to `sys.path`.""" |
| 582 | + if isinstance(path, str): |
| 583 | + path = [path] |
| 584 | + orig_path = sys.path |
| 585 | + if path: |
| 586 | + path = [os.path.abspath(os.path.expandvars(os.path.expanduser(p))) for p in path] |
| 587 | + sys.path = path + sys.path |
| 588 | + yield |
| 589 | + sys.path = orig_path |
| 590 | + return |
| 591 | + |
| 592 | + |
579 | 593 | def import_module( |
580 | 594 | module_name: str, |
581 | 595 | path: Union[str, Sequence[str]] = (), |
@@ -603,20 +617,12 @@ def import_module( |
603 | 617 | if on_error.lower() not in ("raise", "return"): |
604 | 618 | raise ValueError("`on_error` must be 'raise' or 'return'.") |
605 | 619 |
|
606 | | - if isinstance(path, str): |
607 | | - path = [path] |
608 | | - |
609 | | - orig_path = sys.path |
610 | | - if path: |
611 | | - path = [os.path.abspath(os.path.expandvars(os.path.expanduser(p))) for p in path] |
612 | | - sys.path = path + sys.path |
613 | | - try: |
614 | | - module = importlib.import_module(module_name) |
615 | | - except ImportError as e: |
616 | | - if on_error.lower() == "raise": |
617 | | - raise e |
618 | | - else: |
619 | | - module = e |
620 | | - finally: |
621 | | - sys.path = orig_path |
| 620 | + with _prepend_path(path): |
| 621 | + try: |
| 622 | + module = importlib.import_module(module_name) |
| 623 | + except ImportError as e: |
| 624 | + if on_error.lower() == "raise": |
| 625 | + raise e |
| 626 | + else: |
| 627 | + module = e |
622 | 628 | return module |
0 commit comments