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,
(path, forceload=0, cache={})
| 430 | raise ErrorDuringImport(path, sys.exc_info()) |
| 431 | |
| 432 | def safeimport(path, forceload=0, cache={}): |
| 433 | """Import a module; handle errors; return None if the module isn't found. |
| 434 | |
| 435 | If the module *is* found but an exception occurs, it's wrapped in an |
| 436 | ErrorDuringImport exception and reraised. Unlike __import__, if a |
| 437 | package path is specified, the module at the end of the path is returned, |
| 438 | not the package at the beginning. If the optional 'forceload' argument |
| 439 | is 1, we reload the module from disk (unless it's a dynamic extension).""" |
| 440 | try: |
| 441 | # If forceload is 1 and the module has been previously loaded from |
| 442 | # disk, we always have to reload the module. Checking the file's |
| 443 | # mtime isn't good enough (e.g. the module could contain a class |
| 444 | # that inherits from another module that has changed). |
| 445 | if forceload and path in sys.modules: |
| 446 | if path not in sys.builtin_module_names: |
| 447 | # Remove the module from sys.modules and re-import to try |
| 448 | # and avoid problems with partially loaded modules. |
| 449 | # Also remove any submodules because they won't appear |
| 450 | # in the newly loaded module's namespace if they're already |
| 451 | # in sys.modules. |
| 452 | subs = [m for m in sys.modules if m.startswith(path + '.')] |
| 453 | for key in [path] + subs: |
| 454 | # Prevent garbage collection. |
| 455 | cache[key] = sys.modules[key] |
| 456 | del sys.modules[key] |
| 457 | module = __import__(path) |
| 458 | except: |
| 459 | # Did the error occur before or after the module was found? |
| 460 | (exc, value, tb) = info = sys.exc_info() |
| 461 | if path in sys.modules: |
| 462 | # An error occurred while executing the imported module. |
| 463 | raise ErrorDuringImport(sys.modules[path].__file__, info) |
| 464 | elif exc is SyntaxError: |
| 465 | # A SyntaxError occurred before we could execute the module. |
| 466 | raise ErrorDuringImport(value.filename, info) |
| 467 | elif issubclass(exc, ImportError) and value.name == path: |
| 468 | # No such module in the path. |
| 469 | return None |
| 470 | else: |
| 471 | # Some other error occurred during the importing process. |
| 472 | raise ErrorDuringImport(path, sys.exc_info()) |
| 473 | for part in path.split('.')[1:]: |
| 474 | try: module = getattr(module, part) |
| 475 | except AttributeError: return None |
| 476 | return module |
| 477 | |
| 478 | # ---------------------------------------------------- formatter base class |
| 479 |
no test coverage detected