#-----------------------------------------------------------------------------# Copyright (c) Anaconda, Inc., and Bokeh Contributors.# All rights reserved.## The full license is in the file LICENSE.txt, distributed with this software.#-----------------------------------------------------------------------------''' Utilities for checking dependencies'''#-----------------------------------------------------------------------------# Boilerplate#-----------------------------------------------------------------------------from__future__importannotationsimportlogging# isort:skiplog=logging.getLogger(__name__)#-----------------------------------------------------------------------------# Imports#-----------------------------------------------------------------------------# Standard library importsfromimportlibimportimport_modulefromtypesimportModuleTypefromtypingimportAny#-----------------------------------------------------------------------------# Globals and constants#-----------------------------------------------------------------------------__all__=('import_optional','import_required','uses_pandas',)#-----------------------------------------------------------------------------# General API#-----------------------------------------------------------------------------
[docs]defimport_optional(mod_name:str)->ModuleType|None:''' Attempt to import an optional dependency. Silently returns None if the requested module is not available. Args: mod_name (str) : name of the optional module to try to import Returns: imported module or None, if import fails '''try:returnimport_module(mod_name)exceptImportError:passexceptException:msg=f"Failed to import optional module `{mod_name}`"log.exception(msg)returnNone
[docs]defimport_required(mod_name:str,error_msg:str)->ModuleType:''' Attempt to import a required dependency. Raises a RuntimeError if the requested module is not available. Args: mod_name (str) : name of the required module to try to import error_msg (str) : error message to raise when the module is missing Returns: imported module Raises: RuntimeError '''try:returnimport_module(mod_name)exceptImportErrorase:raiseRuntimeError(error_msg)frome
[docs]defuses_pandas(obj:Any)->bool:""" Checks if an object is a ``pandas`` object. Use this before conditional ``import pandas as pd``. """module=type(obj).__module__returnmoduleisnotNoneandmodule.startswith("pandas.")
#-----------------------------------------------------------------------------# Dev API#-----------------------------------------------------------------------------#-----------------------------------------------------------------------------# Private API#-----------------------------------------------------------------------------#-----------------------------------------------------------------------------# Code#-----------------------------------------------------------------------------