Load and return a given import path to a module or class
977345
def load_path(self, path):
        '''
        
        '''
        containing_module, _, last_item = path.rpartition('.')
        if last_item[0].isupper():
            # Is a class definition, should do an "import from"
            path = containing_module
        imported_obj = importlib.import_module(path)
        if last_item[0].isupper():
            try:
                imported_obj = getattr(imported_obj, last_item)
            except AttributeError:
                msg = 'Cannot import "%s". ' \
                    '(Hint: CamelCase is only for classes)' % last_item
                raise ConfigurationError(msg)
        return imported_obj
448542
def load_object(s):
    
    try:
        m_path, o_name = s.rsplit('.', 1)
    except ValueError:
        raise ImportError('Cant import backend from path: {}'.format(s))

    module = import_module(m_path)
    return getattr(module, o_name)
990864
def load_object(path):
    """"""
    i = path.rfind('.')
    module_name, object_name = path[:i], path[i + 1:]
    # Load module.
    try:
        module = import_module(module_name)
    except ImportError:
        raise ImproperlyConfigured('Module %r not found' % module_name)
    except ValueError:
        raise ImproperlyConfigured('Invalid module %r' % module_name)
    # Load object.
    try:
        return getattr(module, object_name)
    except AttributeError:
        msg = 'Module %r does not define an object named %r'
        raise ImproperlyConfigured(msg % (module_name, object_name))
166730
def load_module(name):
    

    spec = importlib.util.find_spec(name)
    mod = importlib.util.module_from_spec(spec)
    mod.__spec__ = spec
    mod.__loader__ = spec.loader
    spec.loader.exec_module(mod)
    return mod
275259
def import_class(import_path, setting_name=None):
    
    mod_name, class_name = import_path.rsplit('.', 1)

    # import module
    mod = import_module_or_none(mod_name)
    if mod is not None:
        # Loaded module, get attribute
        try:
            return getattr(mod, class_name)
        except AttributeError:
            pass

    # For ImportError and AttributeError, raise the same exception.
    if setting_name:
        raise ImproperlyConfigured("{0} does not point to an existing class: {1}".format(setting_name, import_path))
    else:
        raise ImproperlyConfigured("Class not found: {0}".format(import_path))
87870
def import_(path):
    
    exists(path)
    log(_("importing {}...").format(path))
    name = Path(path).stem
    try:
        return internal.import_file(name, path)
    except Exception as e:
        raise Failure(str(e))
201685
def _import_module(module_path, classnames):
    
    try:
        imported_module = __import__(module_path, fromlist=classnames)
        return imported_module
    except ImportError:
        # In case of an ImportError, the module being loaded generally does not exist. But an
        # ImportError can occur if the module being loaded exists and another import located inside
        # it failed.
        #
        # In order to provide a meaningfull traceback, the execution information can be inspected in
        # order to determine which case to consider. If the execution information provides more than
        # a certain amount of frames, this means that an ImportError occured while loading the
        # initial Python module.
        __, __, exc_traceback = sys.exc_info()
        frames = traceback.extract_tb(exc_traceback)
        if len(frames) > 1:
            raise
101901
def import_as(module, name):
    
    dir = os.path.split(__file__)[0]
    return imp.load_module(name, *imp.find_module(module, [dir]))
1125561
def import_class(path):
    
    components = path.split(".")
    module = components[:-1]
    module = ".".join(module)
    mod = __import__(module, fromlist=[native_str(components[-1])])
    return getattr(mod, native_str(components[-1]))
1325406
def tryImportClass(self):
        
        logger.info("Importing: {}".format(self.fullClassName))
        self._triedImport = True
        self._exception = None
        self._cls = None
        try:
            for pyPath in self.pythonPath.split(':'):
                if pyPath and pyPath not in sys.path:
                    logger.debug("Appending {!r} to the PythonPath.".format(pyPath))
                    sys.path.append(pyPath)
            self._cls = import_symbol(self.fullClassName) # TODO: check class?
        except Exception as ex:
            self._exception = ex
            logger.warn("Unable to import {!r}: {}".format(self.fullClassName, ex))
            if DEBUGGING:
                raise
1230327
def import_module(path):
    
    mod = __import__(path, locals={}, globals={})
    for item in path.split('.')[1:]:
        try:
            mod = getattr(mod, item)
        except AttributeError:
            raise ImportError('No module named %s' % path)
    return mod
239109
def import_by_path(path):

    """"""

    sys.path.append(os.path.dirname(path))
    try:
        return __import__(os.path.basename(path))
    except ImportError:
        logger.warn('unable to import {0}'.format(path))
    finally:
        del sys.path[-1]
805548
def load_module(self, name):
        
        _verbose_message('namespace module loaded with path {!r}', self.path)

        # Adjusting code from LoaderBasics
        if name in sys.modules:
            mod = sys.modules[name]
            self.exec_module(mod)
            # In this case we do not want to remove the module in case of error
            # Ref : https://docs.python.org/3/reference/import.html#loaders
        else:
            try:
                # Building custom spec and loading as in _LoaderBasics...
                spec = ModuleSpec(name, self, origin='namespace', is_package=True)
                spec.submodule_search_locations = self.path

                # this will call create_module and also initialize the module properly (like for py3)
                mod = module_from_spec(spec)

                # as per https://docs.python.org/3/reference/import.html#loaders
                assert mod.__name__ in sys.modules

                self.exec_module(mod)
                # We don't ensure that the import-related module attributes get
                # set in the sys.modules replacement case.  Such modules are on
                # their own.
            except:
                # as per https://docs.python.org/3/reference/import.html#loaders
                if name in sys.modules:
                    del sys.modules[name]
                raise

        return sys.modules[name]
30214
def _import_class(self, class_path):
        
        LOGGER.debug('Importing %s', class_path)
        try:
            return utils.import_namespaced_class(class_path)
        except ImportError as error:
            LOGGER.critical('Could not import %s: %s', class_path, error)
            return None
933806
def get_class(class_path):
        
        module_path, class_name = class_path.rsplit(".", 1)

        try:
            module = __import__(class_path, fromlist=[class_name])
        except ImportError:
            raise ValueError('Class {0} could not be imported'.format(class_path))

        try:
            cls = getattr(module, class_name)
        except AttributeError:
            raise ValueError("Module '%s' has no class '%s'" % (module_path, class_name,))

        try:
            instance = cls()
        except TypeError as type_error:
            raise ValueError('Failed to instantiate class {0}. Error: {1}'.format(class_name, type_error.message))

        return instance
1138691
def load_module(modulename, modulepath):
    
    if '.' in modulename:
        modulepackage, modulebase = modulename.rsplit('.', 1)
    else:
        modulepackage = ''

    imp.acquire_lock()
    try:
        # Check if module is already loaded
        if modulename not in sys.modules:
            # Find module on disk and try to load it
            path, name = os.path.split(modulepath)
            name = os.path.splitext(name)[0]
            handle, path, info = imp.find_module(name, [path])
            try:
                # Load the module and put into sys.modules
                module = imp.load_module(modulename, handle, path, info)
                if modulepackage:
                    setattr(sys.modules[modulepackage], modulebase, module)
            finally:
                # Make sure handle is closed properly
                if handle:
                    handle.close()
    finally:
        imp.release_lock()

    return sys.modules[modulename]
224305
async def load_by_path(self, path):
        
        try:
            p, module = findModule(path, True)
        except KeyError as exc:
            raise ModuleLoadException('Cannot load module ' + repr(path) + ': ' + str(exc) + 'is not defined in the package')
        except Exception as exc:
            raise ModuleLoadException('Cannot load module ' + repr(path) + ': ' + str(exc))
        if module is None:
            raise ModuleLoadException('Cannot find module: ' + repr(path))
        return await self.loadmodule(module)