Import a module; handle errors; return None if the module isn't found. If the module *is* found but an exception occurs, it's wrapped in an ErrorDuringImport exception and reraised. Unlike __import__, if a package path is specified, the module at the end of the path is returned, no
(path, forceload=0, cache={})
| 488 | raise ErrorDuringImport(path, err) |
| 489 | |
| 490 | def safeimport(path, forceload=0, cache={}): |
| 491 | """Import a module; handle errors; return None if the module isn't found. |
| 492 | |
| 493 | If the module *is* found but an exception occurs, it's wrapped in an |
| 494 | ErrorDuringImport exception and reraised. Unlike __import__, if a |
| 495 | package path is specified, the module at the end of the path is returned, |
| 496 | not the package at the beginning. If the optional 'forceload' argument |
| 497 | is 1, we reload the module from disk (unless it's a dynamic extension).""" |
| 498 | try: |
| 499 | # If forceload is 1 and the module has been previously loaded from |
| 500 | # disk, we always have to reload the module. Checking the file's |
| 501 | # mtime isn't good enough (e.g. the module could contain a class |
| 502 | # that inherits from another module that has changed). |
| 503 | if forceload and path in sys.modules: |
| 504 | if path not in sys.builtin_module_names: |
| 505 | # Remove the module from sys.modules and re-import to try |
| 506 | # and avoid problems with partially loaded modules. |
| 507 | # Also remove any submodules because they won't appear |
| 508 | # in the newly loaded module's namespace if they're already |
| 509 | # in sys.modules. |
| 510 | subs = [m for m in sys.modules if m.startswith(path + '.')] |
| 511 | for key in [path] + subs: |
| 512 | # Prevent garbage collection. |
| 513 | cache[key] = sys.modules[key] |
| 514 | del sys.modules[key] |
| 515 | module = importlib.import_module(path) |
| 516 | except BaseException as err: |
| 517 | # Did the error occur before or after the module was found? |
| 518 | if path in sys.modules: |
| 519 | # An error occurred while executing the imported module. |
| 520 | raise ErrorDuringImport(sys.modules[path].__file__, err) |
| 521 | elif type(err) is SyntaxError: |
| 522 | # A SyntaxError occurred before we could execute the module. |
| 523 | raise ErrorDuringImport(err.filename, err) |
| 524 | elif isinstance(err, ImportError) and err.name == path: |
| 525 | # No such module in the path. |
| 526 | return None |
| 527 | else: |
| 528 | # Some other error occurred during the importing process. |
| 529 | raise ErrorDuringImport(path, err) |
| 530 | return module |
| 531 | |
| 532 | # ---------------------------------------------------- formatter base class |
| 533 |
no test coverage detected