Skip to content

Instantly share code, notes, and snippets.

@bhgomes
Created April 12, 2019 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhgomes/f509e82f150759a75150ea1074d8ff41 to your computer and use it in GitHub Desktop.
Save bhgomes/f509e82f150759a75150ea1074d8ff41 to your computer and use it in GitHub Desktop.
Try Import
from importlib import import_module
def try_import(
name, package=None, *exceptions, log_error=passf, log_success=passf, default=None
):
"""
Attempt Package Import With Automatic Exception Handling.
:param name:
:param package:
:param exceptions:
:param log_error:
:param log_success:
:param default:
:return:
"""
if not exceptions:
exceptions = (ImportError, ModuleNotFoundError)
try:
module = import_module(name, package=package)
log_success(module)
return module, True
except exceptions as import_error:
try:
module = import_module(package)
resource = getattr(module, name)
log_success(resource)
return resource, True
except exceptions as import_error:
log_error(import_error)
except AttributeError as attribute_error:
log_error(attribute_error)
log_error(import_error)
return default, False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment