Imports the module with the given name.

    Returns None if the module doesn't exist,
    but it does propagates import errors in deeper modules.
764574
def import_module_or_none(module_label):
    
    try:
        # On Python 3, importlib has much more functionality compared to Python 2.
        return importlib.import_module(module_label)
    except ImportError:
        # Based on code from django-oscar:
        # There are 2 reasons why there could be an ImportError:
        #
        #  1. Module does not exist. In that case, we ignore the import and return None
        #  2. Module exists but another ImportError occurred when trying to import the module.
        #     In that case, it is important to propagate the error.
        #
        # ImportError does not provide easy way to distinguish those two cases.
        # Fortunately, the traceback of the ImportError starts at __import__
        # statement. If the traceback has more than one frame, it means that
        # application was found and ImportError originates within the local app
        __, __, exc_traceback = sys.exc_info()
        frames = traceback.extract_tb(exc_traceback)
        frames = [f for f in frames
                  if f[0] != "<frozen importlib._bootstrap>" and  # Python 3.6
                  f[0] != IMPORT_PATH_IMPORTLIB and
                  not f[0].endswith(IMPORT_PATH_GEVENT) and
                  not IMPORT_PATH_PYDEV in f[0]]
        if len(frames) > 1:
            raise
    return None
106538
def load_module(self, name):
        

        # Get the name relative to SITEDIR ..
        filepath = self.module_info[1]
        fullname = splitext( \
            relpath(filepath, self.sitedir) \
            )[0].replace(os.sep, '.')

        modulename = filename_to_module(fullname)
        if modulename not in allowed_modules:
            if remember_blocks:
                blocked_imports.add(fullname)
            if log_blocks:
                raise ImportError("Vext blocked import of '%s'" % modulename)
            else:
                # Standard error message
                raise ImportError("No module named %s" % modulename)

        if name not in sys.modules:
            try:
                logger.debug("load_module %s %s", name, self.module_info)
                module = imp.load_module(name, *self.module_info)
            except Exception as e:
                logger.debug(e)
                raise
            sys.modules[fullname] = module

        return sys.modules[fullname]
484492
def maybedotted(name):
    
    if not name:
        raise LookupError(
            'Not able to resolve %s' % name)
    if not hasattr(name, '__name__'):
        try:
            mod = importlib.import_module(name)
        except ImportError:
            attr = None
            if '.' in name:
                names = name.split('.')
                attr = names.pop(-1)
                try:
                    mod = maybedotted('.'.join(names))
                except LookupError:
                    attr = None
                else:
                    attr = getattr(mod, attr, None)
            if attr is not None:
                return attr
            raise LookupError(
                'Not able to resolve %s' % name)
        else:
            return mod
    return name
174470
def _import_module(name, package='vlfd', warn=True, prefix='_py_', ignore='_'):
    
    import warnings
    from importlib import import_module
    try:
        try:
            module = import_module(name)
        except ImportError:
            module = import_module('.' + name, package=package)
    except ImportError:
        if warn:
            warnings.warn("failed to import module %s" % name)
    else:
        for attr in dir(module):
            if ignore and attr.startswith(ignore):
                continue
            if prefix:
                if attr in globals():
                    globals()[prefix + attr] = globals()[attr]
                elif warn:
                    warnings.warn("no Python implementation of " + attr)
            globals()[attr] = getattr(module, attr)
        return True
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
1191989
def get_imported_module(self, context):
        
        if self.level == 0:
            return context.project.get_module(
                self.module_name, context.folder)
        else:
            return context.project.get_relative_module(
                self.module_name, context.folder, self.level)
140937
def safe_import(self, name):
        """"""
        module = None
        if name not in self._modules:
            self._modules[name] = importlib.import_module(name)
        module = self._modules[name]
        if not module:
            dist = next(iter(
                dist for dist in self.base_working_set if dist.project_name == name
            ), None)
            if dist:
                dist.activate()
            module = importlib.import_module(name)
        if name in sys.modules:
            try:
                six.moves.reload_module(module)
                six.moves.reload_module(sys.modules[name])
            except TypeError:
                del sys.modules[name]
                sys.modules[name] = self._modules[name]
        return module
445031
def import_mod(mod_name:str, ignore_errors=False):
    ""
    splits = str.split(mod_name, '.')
    try:
        if len(splits) > 1 : mod = importlib.import_module('.' + '.'.join(splits[1:]), splits[0])
        else: mod = importlib.import_module(mod_name)
        return mod
    except:
        if not ignore_errors: print(f"Module {mod_name} doesn't exist.")
1004729
def force_lazy_import(name):
  
  obj = import_object(name)
  module_items = list(getattr(obj, '__dict__', {}).items())
  for key, value in module_items:
    if getattr(value, '__module__', None):
        import_object(name + '.' + key)
478090
def import_from(name):
    
    obj = name
    if isinstance(name, str) and len(name):
        try:
            obj = locate(name)
            assert obj is not None
        except (AttributeError, TypeError, AssertionError, ErrorDuringImport):
            try:
                name = name.split(".")
                attr = name[-1]
                name = ".".join(name[:-1])
                mod = importlib.import_module(name)
                obj = getattr(mod, attr)
            except (SyntaxError, AttributeError, ImportError, ValueError):
                try:
                    name = name.split(".")
                    attr_sup = name[-1]
                    name = ".".join(name[:-1])
                    mod = importlib.import_module(name)
                    obj = getattr(getattr(mod, attr_sup), attr)
                except:
                    # We give up.
                    pass

    obj = unwrap_obj(obj)
    return obj
678536
def safe_import_module(module_name):
    
    try:
        return import_module(module_name)
    except ImportError as e:
        m = re.match(r"No module named '([\w\.]+)'", str(e))
        if not m or not module_name.startswith(m.group(1)):
            raise e
902188
def load_module(self, name):
        
        # Implementation inspired from pytest.rewrite and importlib

        # If there is an existing module object named 'name' in
        # sys.modules, the loader must use that existing module. (Otherwise,
        # the reload() builtin will not work correctly.)
        if name in sys.modules:
            return sys.modules[name]
        try:
            # we have already done the search, an gone through package layers
            # so we directly feed the latest module and correct path
            # to reuse the logic for choosing the proper loading behavior

            # TODO : double check maybe we do not need the loop here, already handled by finders in dir hierarchy
            # TODO : use exec_module (recent, more tested API) from here
            for name_idx, name_part in enumerate(name.split('.')):
                pkgname = ".".join(name.split('.')[:name_idx+1])
                if pkgname not in sys.modules:
                    if '.' in pkgname:
                        # parent has to be in sys.modules. make sure it is a package, else fails
                        if '__path__' in vars(sys.modules[pkgname.rpartition('.')[0]]):
                            path = sys.modules[pkgname.rpartition('.')[0]].__path__
                        else:
                            raise ImportError("{0} is not a package (no __path__ detected)".format(pkgname.rpartition('.')[0]))
                    else:  # using __file__ instead. should always be there.
                        path = os.path.dirname(sys.modules[pkgname].__file__)if pkgname in sys.modules else None
                    try:
                        file, pathname, description = imp.find_module(pkgname.rpartition('.')[-1], path)
                        sys.modules[pkgname] = imp.load_module(pkgname, file, pathname, description)
                    finally:
                        if file:
                            file.close()
        except:
            # dont pollute the interpreter environment if we dont know what we are doing
            if name in sys.modules:
                del sys.modules[name]
            raise
        return sys.modules[name]
733719
def tryDynMod(name):
    '''
    
    '''
    try:
        return importlib.import_module(name)
    except ModuleNotFoundError:
        raise s_exc.NoSuchDyn(name=name)
1132792
def import_module(module):  # pylint: disable=R0201
        
        if isinstance(module, list):
            all_modules = module
        else:
            all_modules = [module]
        for mod in all_modules:
            globals()[mod] = __import__(mod.strip())
1107649
def import_from(module, name):
    '''
    
    '''
    module = importlib.import_module(module)
    return getattr(module, name)
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
411343
def import_name_or_class(name):
    "  "

    if isinstance(name, str):

        # for "a.b.c.d" -> [ 'a.b.c', 'd' ]
        module_name, object_name = name.rsplit('.',1)
        # __import__ loads the multi-level of module, but returns
        # the top level, which we have to descend into
        mod = __import__(module_name)

        components = name.split('.')

        for comp in components[1:]: # Already got the top level, so start at 1

            mod = getattr(mod, comp)
        return mod
    else:
        return name