sys.path_importer_cache

Here are the examples of the python api sys.path_importer_cache taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

23 Examples 7

Example 1

Project: TrustRouter Source File: test_path.py
Function: test_path_hooks
    def test_path_hooks(self):
        # Test that sys.path_hooks is used.
        # Test that sys.path_importer_cache is set.
        module = '<test module>'
        path = '<test path>'
        importer = util.mock_modules(module)
        hook = import_util.mock_path_hook(path, importer=importer)
        with util.import_state(path_hooks=[hook]):
            loader = machinery.PathFinder.find_module(module, [path])
            self.assertTrue(loader is importer)
            self.assertTrue(path in sys.path_importer_cache)
            self.assertTrue(sys.path_importer_cache[path] is importer)

Example 2

Project: brython Source File: test_path.py
Function: test_path_hooks
    def test_path_hooks(self):
        # Test that sys.path_hooks is used.
        # Test that sys.path_importer_cache is set.
        module = '<test module>'
        path = '<test path>'
        importer = util.mock_modules(module)
        hook = import_util.mock_path_hook(path, importer=importer)
        with util.import_state(path_hooks=[hook]):
            loader = machinery.PathFinder.find_module(module, [path])
            self.assertIs(loader, importer)
            self.assertIn(path, sys.path_importer_cache)
            self.assertIs(sys.path_importer_cache[path], importer)

Example 3

Project: kbengine Source File: test_path.py
Function: test_path_hooks
    def test_path_hooks(self):
        # Test that sys.path_hooks is used.
        # Test that sys.path_importer_cache is set.
        module = '<test module>'
        path = '<test path>'
        importer = util.mock_spec(module)
        hook = import_util.mock_path_hook(path, importer=importer)
        with util.import_state(path_hooks=[hook]):
            loader = self.machinery.PathFinder.find_module(module, [path])
            self.assertIs(loader, importer)
            self.assertIn(path, sys.path_importer_cache)
            self.assertIs(sys.path_importer_cache[path], importer)

Example 4

Project: iot-utilities Source File: test_path.py
Function: test_path_hooks
    def test_path_hooks(self):
        # Test that sys.path_hooks is used.
        # Test that sys.path_importer_cache is set.
        module = '<test module>'
        path = '<test path>'
        importer = util.mock_spec(module)
        hook = util.mock_path_hook(path, importer=importer)
        with util.import_state(path_hooks=[hook]):
            loader = self.machinery.PathFinder.find_module(module, [path])
            self.assertIs(loader, importer)
            self.assertIn(path, sys.path_importer_cache)
            self.assertIs(sys.path_importer_cache[path], importer)

Example 5

Project: astroid Source File: spec.py
def _precache_zipimporters(path=None):
    pic = sys.path_importer_cache
    path = path or sys.path
    for entry_path in path:
        if entry_path not in pic:
            try:
                pic[entry_path] = zipimport.zipimporter(entry_path)
            except zipimport.ZipImportError:
                continue
    return pic

Example 6

Project: brython Source File: test_path.py
Function: test_empty_path_hooks
    def test_empty_path_hooks(self):
        # Test that if sys.path_hooks is empty a warning is raised,
        # sys.path_importer_cache gets None set, and PathFinder returns None.
        path_entry = 'bogus_path'
        with util.import_state(path_importer_cache={}, path_hooks=[],
                               path=[path_entry]):
            with warnings.catch_warnings(record=True) as w:
                warnings.simplefilter('always')
                self.assertIsNone(machinery.PathFinder.find_module('os'))
                self.assertIsNone(sys.path_importer_cache[path_entry])
                self.assertEqual(len(w), 1)
                self.assertTrue(issubclass(w[-1].category, ImportWarning))

Example 7

Project: brython Source File: test_path.py
Function: test_path_importer_cache_empty_string
    def test_path_importer_cache_empty_string(self):
        # The empty string should create a finder using the cwd.
        path = ''
        module = '<test module>'
        importer = util.mock_modules(module)
        hook = import_util.mock_path_hook(os.curdir, importer=importer)
        with util.import_state(path=[path], path_hooks=[hook]):
            loader = machinery.PathFinder.find_module(module)
            self.assertIs(loader, importer)
            self.assertIn(os.curdir, sys.path_importer_cache)

Example 8

Project: brython Source File: test_api.py
    def test_method_lacking(self):
        # There should be no issues if the method is not defined.
        key = 'gobbledeegook'
        sys.path_importer_cache[key] = imp.NullImporter('abc')
        self.addCleanup(lambda: sys.path_importer_cache.__delitem__(key))
        importlib.invalidate_caches()  # Shouldn't trigger an exception.

Example 9

Project: kbengine Source File: test_path.py
Function: test_empty_path_hooks
    def test_empty_path_hooks(self):
        # Test that if sys.path_hooks is empty a warning is raised,
        # sys.path_importer_cache gets None set, and PathFinder returns None.
        path_entry = 'bogus_path'
        with util.import_state(path_importer_cache={}, path_hooks=[],
                               path=[path_entry]):
            with warnings.catch_warnings(record=True) as w:
                warnings.simplefilter('always')
                self.assertIsNone(self.machinery.PathFinder.find_module('os'))
                self.assertIsNone(sys.path_importer_cache[path_entry])
                self.assertEqual(len(w), 1)
                self.assertTrue(issubclass(w[-1].category, ImportWarning))

Example 10

Project: kbengine Source File: test_path.py
Function: test_path_importer_cache_empty_string
    def test_path_importer_cache_empty_string(self):
        # The empty string should create a finder using the cwd.
        path = ''
        module = '<test module>'
        importer = util.mock_spec(module)
        hook = import_util.mock_path_hook(os.getcwd(), importer=importer)
        with util.import_state(path=[path], path_hooks=[hook]):
            loader = self.machinery.PathFinder.find_module(module)
            self.assertIs(loader, importer)
            self.assertIn(os.getcwd(), sys.path_importer_cache)

Example 11

Project: iot-utilities Source File: test_path.py
Function: test_path_importer_cache_empty_string
    def test_path_importer_cache_empty_string(self):
        # The empty string should create a finder using the cwd.
        path = ''
        module = '<test module>'
        importer = util.mock_spec(module)
        hook = util.mock_path_hook(os.getcwd(), importer=importer)
        with util.import_state(path=[path], path_hooks=[hook]):
            loader = self.machinery.PathFinder.find_module(module)
            self.assertIs(loader, importer)
            self.assertIn(os.getcwd(), sys.path_importer_cache)

Example 12

Project: iot-utilities Source File: test_api.py
Function: test_method_lacking
    def test_method_lacking(self):
        # There should be no issues if the method is not defined.
        key = 'gobbledeegook'
        sys.path_importer_cache[key] = None
        self.addCleanup(lambda: sys.path_importer_cache.__delitem__(key))
        self.init.invalidate_caches()  # Shouldn't trigger an exception.

Example 13

Project: pando.py Source File: harness.py
def teardown():
    """Standard teardown function.

    - reset the current working directory
    - remove FSFIX = %{tempdir}/fsfix
    - reset Pando's global state
    - clear out sys.path_importer_cache

    """
    os.chdir(CWD)
    # Reset some process-global caches. Hrm ...
    resources.__cache__ = {}
    sys.path_importer_cache = {} # see test_weird.py

Example 14

Project: PokemonGo-Bot-Desktop Source File: pkgutil.py
Function: get_importer
def get_importer(path_item):
    """Retrieve a PEP 302 importer for the given path item

    The returned importer is cached in sys.path_importer_cache
    if it was newly created by a path hook.

    If there is no importer, a wrapper around the basic import
    machinery is returned. This wrapper is never inserted into
    the importer cache (None is inserted instead).

    The cache (or part of it) can be cleared manually if a
    rescan of sys.path_hooks is necessary.
    """
    try:
        importer = sys.path_importer_cache[path_item]
    except KeyError:
        for path_hook in sys.path_hooks:
            try:
                importer = path_hook(path_item)
                break
            except ImportError:
                pass
        else:
            importer = None
        sys.path_importer_cache.setdefault(path_item, importer)

    if importer is None:
        try:
            importer = ImpImporter(path_item)
        except ImportError:
            importer = None
    return importer

Example 15

Project: TrustRouter Source File: test_path.py
    def test_implicit_hooks(self):
        # Test that the implicit path hooks are used.
        bad_path = '<path>'
        module = '<module>'
        assert not os.path.exists(bad_path)
        existing_path = tempfile.mkdtemp()
        try:
            with util.import_state():
                nothing = _bootstrap._DefaultPathFinder.find_module(module,
                                                        path=[existing_path])
                self.assertTrue(nothing is None)
                self.assertTrue(existing_path in sys.path_importer_cache)
                result = isinstance(sys.path_importer_cache[existing_path],
                                    imp.NullImporter)
                self.assertFalse(result)
                nothing = _bootstrap._DefaultPathFinder.find_module(module,
                                                            path=[bad_path])
                self.assertTrue(nothing is None)
                self.assertTrue(bad_path in sys.path_importer_cache)
                self.assertTrue(isinstance(sys.path_importer_cache[bad_path],
                                           imp.NullImporter))
        finally:
            os.rmdir(existing_path)

Example 16

Project: blockcanvas Source File: _pkgutil.py
Function: get_importer
    def get_importer(path_item):
        """Retrieve a PEP 302 importer for the given path item

        The returned importer is cached in sys.path_importer_cache
        if it was newly created by a path hook.

        If there is no importer, a wrapper around the basic import
        machinery is returned. This wrapper is never inserted into
        the importer cache (None is inserted instead).

        The cache (or part of it) can be cleared manually if a
        rescan of sys.path_hooks is necessary.
        """
        try:
            importer = sys.path_importer_cache[path_item]
        except KeyError:
            for path_hook in sys.path_hooks:
                try:
                    importer = path_hook(path_item)
                    break
                except ImportError:
                    pass
            else:
                importer = None
            sys.path_importer_cache.setdefault(path_item, importer)

        if importer is None:
            try:
                importer = ImpImporter(path_item)
            except ImportError:
                importer = None
        return importer

Example 17

Project: ironpython3 Source File: pkgutil.py
Function: get_importer
def get_importer(path_item):
    """Retrieve a PEP 302 importer for the given path item

    The returned importer is cached in sys.path_importer_cache
    if it was newly created by a path hook.

    The cache (or part of it) can be cleared manually if a
    rescan of sys.path_hooks is necessary.
    """
    try:
        importer = sys.path_importer_cache[path_item]
    except KeyError:
        for path_hook in sys.path_hooks:
            try:
                importer = path_hook(path_item)
                sys.path_importer_cache.setdefault(path_item, importer)
                break
            except ImportError:
                pass
        else:
            importer = None
    return importer

Example 18

Project: PokemonGo-Bot-Desktop Source File: runpy.py
Function: get_importer
def _get_importer(path_name):
    """Python version of PyImport_GetImporter C API function"""
    cache = sys.path_importer_cache
    try:
        importer = cache[path_name]
    except KeyError:
        # Not yet cached. Flag as using the
        # standard machinery until we finish
        # checking the hooks
        cache[path_name] = None
        for hook in sys.path_hooks:
            try:
                importer = hook(path_name)
                break
            except ImportError:
                pass
        else:
            # The following check looks a bit odd. The trick is that
            # NullImporter raises ImportError if the supplied path is a
            # *valid* directory entry (and hence able to be handled
            # by the standard import machinery)
            try:
                importer = imp.NullImporter(path_name)
            except ImportError:
                return None
        cache[path_name] = importer
    return importer

Example 19

Project: astroid Source File: unittest_modutils.py
Function: tear_down
    def tearDown(self):
        for k in list(sys.path_importer_cache):
            if 'MyPyPa' in k:
                del sys.path_importer_cache[k]

Example 20

Project: pymo Source File: runpy.py
Function: get_importer
def _get_importer(path_name):
    """Python version of PyImport_GetImporter C API function"""
    cache = sys.path_importer_cache
    try:
        importer = cache[path_name]
    except KeyError:
        # Not yet cached. Flag as using the
        # standard machinery until we finish
        # checking the hooks
        cache[path_name] = None
        for hook in sys.path_hooks:
            try:
                importer = hook(path_name)
                break
            except ImportError:
                pass
        else:
            # The following check looks a bit odd. The trick is that
            # NullImporter throws ImportError if the supplied path is a
            # *valid* directory entry (and hence able to be handled
            # by the standard import machinery)
            try:
                importer = imp.NullImporter(path_name)
            except ImportError:
                return None
        cache[path_name] = importer
    return importer

Example 21

Project: Python-mode-klen Source File: modutils.py
def _module_file(modpath, path=None):
    """get a module type / file path

    :type modpath: list or tuple
    :param modpath:
      splitted module's name (i.e name of a module or package splitted
      on '.'), with leading empty strings for explicit relative import

    :type path: list or None
    :param path:
      optional list of path where the module or package should be
      searched (use sys.path if nothing or None is given)


    :rtype: tuple(int, str)
    :return: the module type flag and the file path for a module
    """
    # egg support compat
    try:
        pic = sys.path_importer_cache
        _path = (path is None and sys.path or path)
        for __path in _path:
            if not __path in pic:
                try:
                    pic[__path] = zipimport.zipimporter(__path)
                except zipimport.ZipImportError:
                    pic[__path] = None
        checkeggs = True
    except AttributeError:
        checkeggs = False
    # pkg_resources support (aka setuptools namespace packages)
    if pkg_resources is not None and modpath[0] in pkg_resources._namespace_packages and len(modpath) > 1:
        # setuptools has added into sys.modules a module object with proper
        # __path__, get back information from there
        module = sys.modules[modpath.pop(0)]
        path = module.__path__
    imported = []
    while modpath:
        modname = modpath[0]
        # take care to changes in find_module implementation wrt builtin modules
        #
        # Python 2.6.6 (r266:84292, Sep 11 2012, 08:34:23)
        # >>> imp.find_module('posix')
        # (None, 'posix', ('', '', 6))
        #
        # Python 3.3.1 (default, Apr 26 2013, 12:08:46)
        # >>> imp.find_module('posix')
        # (None, None, ('', '', 6))
        try:
            _, mp_filename, mp_desc = find_module(modname, path)
        except ImportError:
            if checkeggs:
                return _search_zip(modpath, pic)[:2]
            raise
        else:
            if checkeggs and mp_filename:
                fullabspath = [abspath(x) for x in _path]
                try:
                    pathindex = fullabspath.index(dirname(abspath(mp_filename)))
                    emtype, emp_filename, zippath = _search_zip(modpath, pic)
                    if pathindex > _path.index(zippath):
                        # an egg takes priority
                        return emtype, emp_filename
                except ValueError:
                    # XXX not in _path
                    pass
                except ImportError:
                    pass
                checkeggs = False
        imported.append(modpath.pop(0))
        mtype = mp_desc[2]
        if modpath:
            if mtype != PKG_DIRECTORY:
                raise ImportError('No module %s in %s' % ('.'.join(modpath),
                                                          '.'.join(imported)))
            # XXX guess if package is using pkgutil.extend_path by looking for
            # those keywords in the first four Kbytes
            try:
                with open(join(mp_filename, '__init__.py')) as stream:
                    data = stream.read(4096)
            except IOError:
                path = [mp_filename]
            else:
                if 'pkgutil' in data and 'extend_path' in data:
                    # extend_path is called, search sys.path for module/packages
                    # of this name see pkgutil.extend_path docuementation
                    path = [join(p, *imported) for p in sys.path
                            if isdir(join(p, *imported))]
                else:
                    path = [mp_filename]
    return mtype, mp_filename

Example 22

Project: python-mode Source File: modutils.py
def _module_file(modpath, path=None):
    """get a module type / file path

    :type modpath: list or tuple
    :param modpath:
      splitted module's name (i.e name of a module or package splitted
      on '.'), with leading empty strings for explicit relative import

    :type path: list or None
    :param path:
      optional list of path where the module or package should be
      searched (use sys.path if nothing or None is given)


    :rtype: tuple(int, str)
    :return: the module type flag and the file path for a module
    """
    # egg support compat
    try:
        pic = sys.path_importer_cache
        _path = (path is None and sys.path or path)
        for __path in _path:
            if not __path in pic:
                try:
                    pic[__path] = zipimport.zipimporter(__path)
                except zipimport.ZipImportError:
                    pic[__path] = None
        checkeggs = True
    except AttributeError:
        checkeggs = False
    # pkg_resources support (aka setuptools namespace packages)
    if (pkg_resources is not None
            and modpath[0] in pkg_resources._namespace_packages
            and modpath[0] in sys.modules
            and len(modpath) > 1):
        # setuptools has added into sys.modules a module object with proper
        # __path__, get back information from there
        module = sys.modules[modpath.pop(0)]
        path = module.__path__
    imported = []
    while modpath:
        modname = modpath[0]
        # take care to changes in find_module implementation wrt builtin modules
        #
        # Python 2.6.6 (r266:84292, Sep 11 2012, 08:34:23)
        # >>> imp.find_module('posix')
        # (None, 'posix', ('', '', 6))
        #
        # Python 3.3.1 (default, Apr 26 2013, 12:08:46)
        # >>> imp.find_module('posix')
        # (None, None, ('', '', 6))
        try:
            stream, mp_filename, mp_desc = imp.find_module(modname, path)
        except ImportError:
            if checkeggs:
                return _search_zip(modpath, pic)[:2]
            raise
        else:
            # Don't forget to close the stream to avoid
            # spurious ResourceWarnings.
            if stream:
               stream.close()

            if checkeggs and mp_filename:
                fullabspath = [_cache_normalize_path(x) for x in _path]
                try:
                    pathindex = fullabspath.index(os.path.dirname(_normalize_path(mp_filename)))
                    emtype, emp_filename, zippath = _search_zip(modpath, pic)
                    if pathindex > _path.index(zippath):
                        # an egg takes priority
                        return emtype, emp_filename
                except ValueError:
                    # XXX not in _path
                    pass
                except ImportError:
                    pass
                checkeggs = False
        imported.append(modpath.pop(0))
        mtype = mp_desc[2]
        if modpath:
            if mtype != imp.PKG_DIRECTORY:
                raise ImportError('No module %s in %s' % ('.'.join(modpath),
                                                          '.'.join(imported)))
            # XXX guess if package is using pkgutil.extend_path by looking for
            # those keywords in the first four Kbytes
            try:
                with open(os.path.join(mp_filename, '__init__.py'), 'rb') as stream:
                    data = stream.read(4096)
            except IOError:
                path = [mp_filename]
            else:
                if b'pkgutil' in data and b'extend_path' in data:
                    # extend_path is called, search sys.path for module/packages
                    # of this name see pkgutil.extend_path docuementation
                    path = [os.path.join(p, *imported) for p in sys.path
                            if os.path.isdir(os.path.join(p, *imported))]
                else:
                    path = [mp_filename]
    return mtype, mp_filename

Example 23

Project: python-mode Source File: modutils.py
def _module_file(modpath, path=None):
    """get a module type / file path

    :type modpath: list or tuple
    :param modpath:
      splitted module's name (i.e name of a module or package splitted
      on '.'), with leading empty strings for explicit relative import

    :type path: list or None
    :param path:
      optional list of path where the module or package should be
      searched (use sys.path if nothing or None is given)


    :rtype: tuple(int, str)
    :return: the module type flag and the file path for a module
    """
    # egg support compat
    try:
        pic = sys.path_importer_cache
        _path = (path is None and sys.path or path)
        for __path in _path:
            if not __path in pic:
                try:
                    pic[__path] = zipimport.zipimporter(__path)
                except zipimport.ZipImportError:
                    pic[__path] = None
        checkeggs = True
    except AttributeError:
        checkeggs = False
    # pkg_resources support (aka setuptools namespace packages)
    if (_is_namespace(modpath[0]) and modpath[0] in sys.modules):
        # setuptools has added into sys.modules a module object with proper
        # __path__, get back information from there
        module = sys.modules[modpath.pop(0)]
        path = module.__path__
        if not modpath:
            return C_BUILTIN, None
    imported = []
    while modpath:
        modname = modpath[0]
        # take care to changes in find_module implementation wrt builtin modules
        #
        # Python 2.6.6 (r266:84292, Sep 11 2012, 08:34:23)
        # >>> imp.find_module('posix')
        # (None, 'posix', ('', '', 6))
        #
        # Python 3.3.1 (default, Apr 26 2013, 12:08:46)
        # >>> imp.find_module('posix')
        # (None, None, ('', '', 6))
        try:
            _, mp_filename, mp_desc = find_module(modname, path)
        except ImportError:
            if checkeggs:
                return _search_zip(modpath, pic)[:2]
            raise
        else:
            if checkeggs and mp_filename:
                fullabspath = [abspath(x) for x in _path]
                try:
                    pathindex = fullabspath.index(dirname(abspath(mp_filename)))
                    emtype, emp_filename, zippath = _search_zip(modpath, pic)
                    if pathindex > _path.index(zippath):
                        # an egg takes priority
                        return emtype, emp_filename
                except ValueError:
                    # XXX not in _path
                    pass
                except ImportError:
                    pass
                checkeggs = False
        imported.append(modpath.pop(0))
        mtype = mp_desc[2]
        if modpath:
            if mtype != PKG_DIRECTORY:
                raise ImportError('No module %s in %s' % ('.'.join(modpath),
                                                          '.'.join(imported)))
            # XXX guess if package is using pkgutil.extend_path by looking for
            # those keywords in the first four Kbytes
            try:
                with open(join(mp_filename, '__init__.py')) as stream:
                    data = stream.read(4096)
            except IOError:
                path = [mp_filename]
            else:
                if 'pkgutil' in data and 'extend_path' in data:
                    # extend_path is called, search sys.path for module/packages
                    # of this name see pkgutil.extend_path docuementation
                    path = [join(p, *imported) for p in sys.path
                            if isdir(join(p, *imported))]
                else:
                    path = [mp_filename]
    return mtype, mp_filename