Python Sphinx autodoc在random.choice()上被卡住,使用mock

Python Sphinx autodoc在random.choice()上被卡住,使用mock,python,numpy,mocking,python-sphinx,autodoc,Python,Numpy,Mocking,Python Sphinx,Autodoc,这是我在这篇文章中最初提出的一个问题的延续: 在这个问题中,我将问题简化到了最简单的程度,并且能够重现Sphinx挂在random.choice函数上的问题 下面是文件randor_test.py中的Python代码;它以PyCharm运行: import random import numpy as np def rand_test(svr_C, svr_gamma): """This is test docstring #. item one

这是我在这篇文章中最初提出的一个问题的延续:

在这个问题中,我将问题简化到了最简单的程度,并且能够重现Sphinx挂在random.choice函数上的问题

下面是文件randor_test.py中的Python代码;它以PyCharm运行:

import random
import numpy as np

def rand_test(svr_C, svr_gamma):
    """This is test docstring

    #. item one
    #. item two
    """
    ml_params = {'C': random.choice(svr_C), 'gamma': random.choice(svr_gamma)}
    return ml_params

svr_C = list(np.linspace(50, 300, 10))
svr_gamma = list(np.logspace(-4, -2, 3))

rand_result = rand_test(svr_C, svr_gamma)

for i in rand_result:
    print(i, rand_result[i])
我设置了Sphinx目录,并按照本文中的所有说明进行操作:

运行make html后,我收到以下错误:

WARNING: autodoc: failed to import module 'randor_test'; the following exception was raised:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sphinx/ext/autodoc/importer.py", line 32, in import_module
    return importlib.import_module(modname)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/Users/kellihed/PAC_projects/basic_0629/src/randor_test.py", line 19, in <module>
    rand_result = rand_test(svr_C, svr_gamma)
  File "/Users/kellihed/PAC_projects/basic_0629/src/randor_test.py", line 10, in rand_test
    ml_params = {'C': random.choice(svr_C), 'gamma': random.choice(svr_gamma)}
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/random.py", line 261, in choice
    raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence
我在conf.py中有以下ignoreimports语句:

autodoc_mock_imports = ["random", "numpy"]
下面是我的conf.py文件:

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join('..', '..', 'src')))


# -- Project information -----------------------------------------------------

project = 'random_test'
copyright = '2020, DK'
author = 'DK'

# The full version, including alpha/beta/rc tags
release = '0.1'


# -- General configuration ---------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.autodoc']
autodoc_mock_imports = ["random", "numpy"]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = []


# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

当Sphinx导入randor_测试时,将始终执行模块级代码。svr_C=listnp.linspace50、300、10不会直接导致错误,但结果是svr_C是一个空列表

执行random.choicesvr_C时会发生错误。我不认为在autodoc\u mock\u导入中使用random会有任何区别,它是一个内置的标准模块,始终可用。我认为最好的解决方案是将模块级代码放在if uuu name uuuu=='\uuuu main_uuu'块中


另请参见。

您有模块级代码,当Sphinx导入randor_测试时,这些代码将始终执行。svr_C=listnp.linspace50、300、10不会直接导致错误,但结果是svr_C是一个空列表

执行random.choicesvr_C时会发生错误。我不认为在autodoc\u mock\u导入中使用random会有任何区别,它是一个内置的标准模块,始终可用。我认为最好的解决方案是将模块级代码放在if uuu name uuuu=='\uuuu main_uuu'块中

另请参见。

如果不使用autodoc\u mock\u imports=[numpy],它将在不给出错误的情况下工作:

那么为什么autodoc\u mock\u imports=[numpy]会导致错误呢?因为使用mock将导致import numpy作为np提供签名,虽然可以调用这些签名,但它们的返回值将为空。 例如:

import numpy as np
type(np)  # using mock in conf.py
<class 'sphinx.ext.autodoc.mock._MockModule'>
引用文件:

此值包含要模拟的模块列表。当某些外部依赖项在构建时未得到满足并中断构建过程时,这非常有用。您可以只指定依赖项本身的根包,而忽略子模块:

如果您的外部依赖项(换句话说,当您调用Sphinx时,从您自己的库外部进行的导入在构建时可以正常工作),那么您不必使用mock。如果您没有使用mock,您的简短示例可能会起作用。 除了使用_umain _uuu外,另一个常见的选项是不通过将变量封装在方法或函数中而在模块级初始化变量

6.1。 模块可以包含可执行语句以及函数定义。这些语句用于初始化模块。只有在import语句中第一次遇到模块名时,才会执行这些命令。如果文件作为脚本执行,它们也会运行

如果您没有使用autodoc\u mock\u imports=[numpy],它将不会出现错误:

那么为什么autodoc\u mock\u imports=[numpy]会导致错误呢?因为使用mock将导致import numpy作为np提供签名,虽然可以调用这些签名,但它们的返回值将为空。 例如:

import numpy as np
type(np)  # using mock in conf.py
<class 'sphinx.ext.autodoc.mock._MockModule'>
引用文件:

此值包含要模拟的模块列表。当某些外部依赖项在构建时未得到满足并中断构建过程时,这非常有用。您可以只指定依赖项本身的根包,而忽略子模块:

如果您的外部依赖项(换句话说,当您调用Sphinx时,从您自己的库外部进行的导入在构建时可以正常工作),那么您不必使用mock。如果您没有使用mock,您的简短示例可能会起作用。 除了使用_umain _uuu外,另一个常见的选项是不通过将变量封装在方法或函数中而在模块级初始化变量

6.1。 模块可以包含可执行语句以及函数定义。这些语句用于初始化模块。只有在import语句中第一次遇到模块名时,才会执行这些命令。如果文件作为脚本执行,它们也会运行


再次感谢!这是真的。我从模拟列表中删除了if name==“main”numpy,它运行时没有任何错误。这是最好的,因为将main集成到代码的这一部分将是另一个挑战。再次感谢!这是真的。我从模拟列表中删除了if name==“main”numpy,它运行时没有任何错误。这是更可取的,因为将main集成到代码的这一部分将是另一个挑战。
import numpy as np
type(np)  # not using mock in conf.py
<class 'module'>