def import_object(self, raiseerror: bool = False) -> bool:
        """
		Never import anything.

		:param raiseerror:
		"""

        # disguise as an attribute
        self.objtype = "attribute"
        self._datadescriptor = True

        with mock(self.env.config.autodoc_mock_imports):
            try:
                ret = import_object(
                    self.modname,
                    self.objpath[:-1],
                    "class",
                    attrgetter=self.get_attr,
                    warningiserror=self.env.config.autodoc_warningiserror)
                self.module, _, _, self.parent = ret
                return True
            except ImportError as exc:
                if raiseerror:
                    raise
                else:
                    logger.warning(exc.args[0],
                                   type="autodoc",
                                   subtype="import_object")
                    self.env.note_reread()
                    return False
Exemple #2
0
def test_stringify_mock():
    with mock(['unknown']):
        import unknown
        assert stringify(unknown) == 'unknown'
        assert stringify(unknown.secret.Class) == 'unknown.secret.Class'
        assert stringify(unknown.secret.Class,
                         "smart") == 'unknown.secret.Class'
Exemple #3
0
def test_restify_mock():
    with mock(['unknown']):
        import unknown
        assert restify(unknown) == ':py:class:`unknown`'
        assert restify(
            unknown.secret.Class) == ':py:class:`unknown.secret.Class`'
        assert restify(unknown.secret.Class,
                       "smart") == ':py:class:`~unknown.secret.Class`'
Exemple #4
0
def test_stringify_mock():
    with mock(['unknown']):
        import unknown
        assert stringify(unknown.secret.Class, False) == 'unknown.secret.Class'
        assert stringify(unknown.secret.Class, True) == 'unknown.secret.Class'
    def import_object(self):
        ret = super(DocumenterAnnotator, self).import_object()

        # get its file if possible. This will fail for builtins and such, so just in case we'll try/except.
        try:
            filepath_py = os.path.abspath(inspect.getsourcefile(self.object))
            module = inspect.getmodule(self.object)
        except TypeError:
            print(self.object)
            print('\n\n\n\n')
            return ret

        filepath = os.path.splitext(filepath_py)[0]
        filepath_pyi = '{}i'.format(filepath_py)
        filepath_py2annotate_py = filepath + '_py2annotate.py'

        # generate py2annotate file...
        if not os.path.isfile(filepath_py2annotate_py):
            # ...by copying a .pyi file if it exists...
            if os.path.isfile(filepath_pyi):
                shutil.copy(filepath_pyi, filepath_py2annotate_py)
            # ...or by creating it from stubgen if it doesn't.
            else:
                opts = []
                if self.env.config.py2annotate_no_import:
                    opts.append('--no-import')
                if self.env.config.py2annotate_parse_only:
                    opts.append('--parse-only')
                if self.env.config.py2annotate_ignore_errors:
                    opts.append('--ignore-errors')
                if self.env.config.py2annotate_include_private:
                    opts.append('--include-private')
                outdir = os.path.dirname(filepath_py)
                while os.path.isfile(os.path.join(outdir, '__init__.py')):
                    outdir, _ = os.path.split(outdir)
                opts.append('--output')
                opts.append(outdir)
                opts.append(filepath_py)
                stubgen_main(opts)
                os.rename(filepath_pyi, filepath_py2annotate_py)
            self.env.app.py2annotate_files.add(filepath_py2annotate_py)

        # import the corresponding object from the py2annotate file and copy its annotations
        try:
            with autodoc.mock(self.env.config.autodoc_mock_imports):
                try:
                    obj = importlib.import_module(module.__name__ +
                                                  '_py2annotate')
                except SyntaxError as e:
                    if sys.version_info < (3, 6):
                        version = '.'.join(map(str, sys.version_info))
                        raise RuntimeError(
                            'Failed to import py2annotate file. You are using Python version {version}, '
                            'which is earlier than the required version 3.6. Update your Python!'
                            .format(version=version)) from e
                    else:
                        raise
            for o in self.object.__qualname__.split('.'):
                obj = getattr(obj, o)
            if hasattr(obj, '__annotations__'):
                self.object.__annotations__ = obj.__annotations__
            if self.objtype == 'class':
                for method in ('__init__', '__call__'):
                    if hasattr(self.object, method) and hasattr(obj, method):
                        object_meth = getattr(self.object, method)
                        obj_meth = getattr(obj, method)
                        if hasattr(obj_meth, '__annotations__'):
                            object_meth.__annotations__ = obj_meth.__annotations__
        except Exception as e:
            print(e)

        return ret