Created
April 12, 2019 17:24
-
-
Save bhgomes/f509e82f150759a75150ea1074d8ff41 to your computer and use it in GitHub Desktop.
Try Import
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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