MCPcopy Index your code
hub / github.com/python/cpython / safeimport

Function safeimport

Lib/pydoc.py:425–465  ·  view source on GitHub ↗

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={})

Source from the content-addressed store, hash-verified

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

Callers 1

locateFunction · 0.85

Calls 3

ErrorDuringImportClass · 0.85
startswithMethod · 0.45
import_moduleMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…