:mod:`xdoctest.utils.util_import`
=================================

.. py:module:: xdoctest.utils.util_import

.. autoapi-nested-parse::

   This file was autogenerated based on code in ubelt



Module Contents
---------------

Classes
~~~~~~~

.. autoapisummary::

   xdoctest.utils.util_import.PythonPathContext



Functions
~~~~~~~~~

.. autoapisummary::

   xdoctest.utils.util_import.is_modname_importable
   xdoctest.utils.util_import._importlib_import_modpath
   xdoctest.utils.util_import._pkgutil_modname_to_modpath
   xdoctest.utils.util_import._custom_import_modpath
   xdoctest.utils.util_import.import_module_from_path
   xdoctest.utils.util_import.import_module_from_name
   xdoctest.utils.util_import._extension_module_tags
   xdoctest.utils.util_import._platform_pylib_exts
   xdoctest.utils.util_import._syspath_modname_to_modpath
   xdoctest.utils.util_import.modname_to_modpath
   xdoctest.utils.util_import.normalize_modpath
   xdoctest.utils.util_import.modpath_to_modname
   xdoctest.utils.util_import.split_modpath


.. function:: is_modname_importable(modname, sys_path=None, exclude=None)

   Determines if a modname is importable based on your current sys.path

   :Parameters: * **modname** (*str*) -- name of module to check
                * **sys_path** (*list, default=None*) -- if specified overrides `sys.path`
                * **exclude** (*list*) -- list of directory paths. if specified prevents these
                  directories from being searched.

   :returns: True if the module can be imported
   :rtype: bool

   .. rubric:: Example

   >>> is_modname_importable('xdoctest')
   True
   >>> is_modname_importable('not_a_real_module')
   False
   >>> is_modname_importable('xdoctest', sys_path=[])
   False


.. function:: _importlib_import_modpath(modpath)

   Alternative to import_module_from_path using importlib mechainsms


.. function:: _pkgutil_modname_to_modpath(modname)

   faster version of `_syspath_modname_to_modpath` using builtin python
   mechanisms, but unfortunately it doesn't play nice with pytest.

   .. rubric:: Example

   >>> # xdoctest: +SKIP
   >>> modname = 'xdoctest.static_analysis'
   >>> _pkgutil_modname_to_modpath(modname)
   ...static_analysis.py
   >>> # xdoctest: +REQUIRES(CPython)
   >>> _pkgutil_modname_to_modpath('_ctypes')
   ..._ctypes...

   Ignore:
       >>> _pkgutil_modname_to_modpath('cv2')


.. py:class:: PythonPathContext(dpath, index=0)

   Bases: :class:`object`

   Context for temporarily adding a dir to the PYTHONPATH. Used in testing

   :Parameters: * **dpath** (*str*) -- directory to insert into the PYTHONPATH
                * **index** (*int*) -- position to add to. Typically either -1 or 0.

   .. rubric:: Example

   >>> with PythonPathContext('foo', -1):
   >>>     assert sys.path[-1] == 'foo'
   >>> assert sys.path[-1] != 'foo'
   >>> with PythonPathContext('bar', 0):
   >>>     assert sys.path[0] == 'bar'
   >>> assert sys.path[0] != 'bar'

   .. rubric:: Example

   >>> # Mangle the path inside the context
   >>> # xdoctest: +REQUIRES(module:pytest)
   >>> self = PythonPathContext('foo', 0)
   >>> self.__enter__()
   >>> import pytest
   >>> with pytest.warns(UserWarning):
   >>>     sys.path.insert(0, 'mangled')
   >>>     self.__exit__(None, None, None)

   .. rubric:: Example

   >>> # xdoctest: +REQUIRES(module:pytest)
   >>> self = PythonPathContext('foo', 0)
   >>> self.__enter__()
   >>> sys.path.remove('foo')
   >>> import pytest
   >>> with pytest.raises(RuntimeError):
   >>>     self.__exit__(None, None, None)

   .. method:: __enter__(self)



   .. method:: __exit__(self, type, value, trace)




.. function:: _custom_import_modpath(modpath, index=-1)


.. function:: import_module_from_path(modpath, index=-1)

   Imports a module via its path

   :Parameters: * **modpath** (*PathLike*) -- path to the module on disk or within a zipfile.
                * **index** (*int*) -- location at which we modify PYTHONPATH if necessary.
                  If your module name does not conflict, the safest value is -1,
                  However, if there is a conflict, then use an index of 0.
                  The default may change to 0 in the future.

   :returns: the imported module
   :rtype: module

   .. rubric:: References

   https://stackoverflow.com/questions/67631/import-module-given-path

   .. rubric:: Notes

   If the module is part of a package, the package will be imported first.
   These modules may cause problems when reloading via IPython magic

   This can import a module from within a zipfile. To do this modpath
   should specify the path to the zipfile and the path to the module
   within that zipfile separated by a colon or pathsep.
   E.g. `/path/to/archive.zip:mymodule.py`

   .. warning::

      It is best to use this with paths that will not conflict with
      previously existing modules.
      
      If the modpath conflicts with a previously existing module name. And
      the target module does imports of its own relative to this conflicting
      path. In this case, the module that was loaded first will win.
      
      For example if you try to import '/foo/bar/pkg/mod.py' from the folder
      structure:
        - foo/
          +- bar/
             +- pkg/
                +  __init__.py
                |- mod.py
                |- helper.py

      If there exists another module named `pkg` already in sys.modules
      and mod.py does something like `from . import helper`, Python will
      assume helper belongs to the `pkg` module already in sys.modules.
      This can cause a NameError or worse --- a incorrect helper module.

   .. rubric:: Example

   >>> import xdoctest
   >>> modpath = xdoctest.__file__
   >>> module = import_module_from_path(modpath)
   >>> assert module is xdoctest

   .. rubric:: Example

   >>> # Test importing a module from within a zipfile
   >>> import zipfile
   >>> from xdoctest import utils
   >>> from os.path import join, expanduser
   >>> dpath = expanduser('~/.cache/xdoctest')
   >>> dpath = utils.ensuredir(dpath)
   >>> # Write to an external module named bar
   >>> external_modpath = join(dpath, 'bar.py')
   >>> # For pypy support we have to write this using with
   >>> with open(external_modpath, 'w') as file:
   >>>     file.write('testvar = 1')
   >>> assert open(external_modpath, 'r').read() == 'testvar = 1'
   >>> internal = 'folder/bar.py'
   >>> # Move the external bar module into a zipfile
   >>> zippath = join(dpath, 'myzip.zip')
   >>> with zipfile.ZipFile(zippath, 'w') as myzip:
   >>>     myzip.write(external_modpath, internal)
   >>> assert exists(zippath)
   >>> # Import the bar module from within the zipfile
   >>> modpath = zippath + ':' + internal
   >>> modpath = zippath + os.path.sep + internal
   >>> module = import_module_from_path(modpath)
   >>> assert module.__name__ == os.path.normpath('folder/bar')
   >>> print('module = {!r}'.format(module))
   >>> print('module.__file__ = {!r}'.format(module.__file__))
   >>> print(dir(module))
   >>> assert module.testvar == 1

   Doctest:
       >>> # xdoctest: +REQUIRES(module:pytest)
       >>> import pytest
       >>> with pytest.raises(IOError):
       >>>     import_module_from_path('does-not-exist')
       >>> with pytest.raises(IOError):
       >>>     import_module_from_path('does-not-exist.zip/')


.. function:: import_module_from_name(modname)

   Imports a module from its string name (__name__)

   :Parameters: **modname** (*str*) -- module name

   :returns: module
   :rtype: module

   .. rubric:: Example

   >>> # test with modules that wont be imported in normal circumstances
   >>> # todo write a test where we gaurentee this
   >>> modname_list = [
   >>>     'pickletools',
   >>>     'lib2to3.fixes.fix_apply',
   >>> ]
   >>> #assert not any(m in sys.modules for m in modname_list)
   >>> modules = [import_module_from_name(modname) for modname in modname_list]
   >>> assert [m.__name__ for m in modules] == modname_list
   >>> assert all(m in sys.modules for m in modname_list)


.. function:: _extension_module_tags()

   Returns valid tags an extension module might have


.. function:: _platform_pylib_exts()

   Returns .so, .pyd, or .dylib depending on linux, win or mac.
   On python3 return the previous with and without abi (e.g.
   .cpython-35m-x86_64-linux-gnu) flags. On python2 returns with
   and without multiarch.


.. function:: _syspath_modname_to_modpath(modname, sys_path=None, exclude=None)

   syspath version of modname_to_modpath

   :Parameters: * **modname** (*str*) -- name of module to find
                * **sys_path** (*List[PathLike], default=None*) -- if specified overrides ``sys.path``
                * **exclude** (*List[PathLike], default=None*) -- list of directory paths. if specified prevents these directories
                  from being searched.

   .. rubric:: Notes

   This is much slower than the pkgutil mechanisms.

   .. rubric:: Example

   >>> print(_syspath_modname_to_modpath('xdoctest.static_analysis'))
   ...static_analysis.py
   >>> print(_syspath_modname_to_modpath('xdoctest'))
   ...xdoctest
   >>> # xdoctest: +REQUIRES(CPython)
   >>> print(_syspath_modname_to_modpath('_ctypes'))
   ..._ctypes...
   >>> assert _syspath_modname_to_modpath('xdoctest', sys_path=[]) is None
   >>> assert _syspath_modname_to_modpath('xdoctest.static_analysis', sys_path=[]) is None
   >>> assert _syspath_modname_to_modpath('_ctypes', sys_path=[]) is None
   >>> assert _syspath_modname_to_modpath('this', sys_path=[]) is None

   .. rubric:: Example

   >>> # test what happens when the module is not visible in the path
   >>> modname = 'xdoctest.static_analysis'
   >>> modpath = _syspath_modname_to_modpath(modname)
   >>> exclude = [split_modpath(modpath)[0]]
   >>> found = _syspath_modname_to_modpath(modname, exclude=exclude)
   >>> # this only works if installed in dev mode, pypi fails
   >>> # assert found is None, 'should not have found {}'.format(found)


.. function:: modname_to_modpath(modname, hide_init=True, hide_main=False, sys_path=None)

   Finds the path to a python module from its name.

   Determines the path to a python module without directly import it

   Converts the name of a module (__name__) to the path (__file__) where it is
   located without importing the module. Returns None if the module does not
   exist.

   :Parameters: * **modname** (*str*) -- module filepath
                * **hide_init** (*bool*) -- if False, __init__.py will be returned for packages
                * **hide_main** (*bool*) -- if False, and hide_init is True, __main__.py will be
                  returned for packages, if it exists.
                * **sys_path** (*list, default=None*) -- if specified overrides `sys.path`

   :returns: modpath - path to the module, or None if it doesn't exist
   :rtype: str

   .. rubric:: Example

   >>> modname = 'xdoctest.__main__'
   >>> modpath = modname_to_modpath(modname, hide_main=False)
   >>> assert modpath.endswith('__main__.py')
   >>> modname = 'xdoctest'
   >>> modpath = modname_to_modpath(modname, hide_init=False)
   >>> assert modpath.endswith('__init__.py')
   >>> # xdoctest: +REQUIRES(CPython)
   >>> modpath = basename(modname_to_modpath('_ctypes'))
   >>> assert 'ctypes' in modpath


.. function:: normalize_modpath(modpath, hide_init=True, hide_main=False)

   Normalizes __init__ and __main__ paths.

   :Parameters: * **modpath** (*PathLike*) -- path to a module
                * **hide_init** (*bool, default=True*) -- if True, always return package modules
                  as __init__.py files otherwise always return the dpath.
                * **hide_main** (*bool, default=False*) -- if True, always strip away main files
                  otherwise ignore __main__.py.

   :returns: a normalized path to the module
   :rtype: PathLike

   .. rubric:: Notes

   Adds __init__ if reasonable, but only removes __main__ by default

   .. rubric:: Example

   >>> from xdoctest import static_analysis as module
   >>> modpath = module.__file__
   >>> assert normalize_modpath(modpath) == modpath.replace('.pyc', '.py')
   >>> dpath = dirname(modpath)
   >>> res0 = normalize_modpath(dpath, hide_init=0, hide_main=0)
   >>> res1 = normalize_modpath(dpath, hide_init=0, hide_main=1)
   >>> res2 = normalize_modpath(dpath, hide_init=1, hide_main=0)
   >>> res3 = normalize_modpath(dpath, hide_init=1, hide_main=1)
   >>> assert res0.endswith('__init__.py')
   >>> assert res1.endswith('__init__.py')
   >>> assert not res2.endswith('.py')
   >>> assert not res3.endswith('.py')


.. function:: modpath_to_modname(modpath, hide_init=True, hide_main=False, check=True, relativeto=None)

   Determines importable name from file path

   Converts the path to a module (__file__) to the importable python name
   (__name__) without importing the module.

   The filename is converted to a module name, and parent directories are
   recursively included until a directory without an __init__.py file is
   encountered.

   :Parameters: * **modpath** (*str*) -- module filepath
                * **hide_init** (*bool, default=True*) -- removes the __init__ suffix
                * **hide_main** (*bool, default=False*) -- removes the __main__ suffix
                * **check** (*bool, default=True*) -- if False, does not raise an error if
                  modpath is a dir and does not contain an __init__ file.
                * **relativeto** (*str, default=None*) -- if specified, all checks are ignored
                  and this is considered the path to the root module.

   :returns: modname
   :rtype: str

   :raises ValueError: if check is True and the path does not exist

   .. rubric:: Example

   >>> from xdoctest import static_analysis
   >>> modpath = static_analysis.__file__.replace('.pyc', '.py')
   >>> modpath = modpath.replace('.pyc', '.py')
   >>> modname = modpath_to_modname(modpath)
   >>> assert modname == 'xdoctest.static_analysis'

   .. rubric:: Example

   >>> import xdoctest
   >>> assert modpath_to_modname(xdoctest.__file__.replace('.pyc', '.py')) == 'xdoctest'
   >>> assert modpath_to_modname(dirname(xdoctest.__file__.replace('.pyc', '.py'))) == 'xdoctest'

   .. rubric:: Example

   >>> # xdoctest: +REQUIRES(CPython)
   >>> modpath = modname_to_modpath('_ctypes')
   >>> modname = modpath_to_modname(modpath)
   >>> assert modname == '_ctypes'

   .. rubric:: Example

   >>> modpath = '/foo/libfoobar.linux-x86_64-3.6.so'
   >>> modname = modpath_to_modname(modpath, check=False)
   >>> assert modname == 'libfoobar'


.. function:: split_modpath(modpath, check=True)

   Splits the modpath into the dir that must be in PYTHONPATH for the module
   to be imported and the modulepath relative to this directory.

   :Parameters: * **modpath** (*str*) -- module filepath
                * **check** (*bool*) -- if False, does not raise an error if modpath is a
                  directory and does not contain an `__init__.py` file.

   :returns: (directory, rel_modpath)
   :rtype: tuple

   :raises ValueError: if modpath does not exist or is not a package

   .. rubric:: Example

   >>> from xdoctest import static_analysis
   >>> modpath = static_analysis.__file__.replace('.pyc', '.py')
   >>> modpath = abspath(modpath)
   >>> dpath, rel_modpath = split_modpath(modpath)
   >>> recon = join(dpath, rel_modpath)
   >>> assert recon == modpath
   >>> assert rel_modpath == join('xdoctest', 'static_analysis.py')


