Add stacklevel parameter to warnings.warn() call

This commit is contained in:
Takeshi KOMIYA 2020-05-03 22:40:19 +09:00
parent a5cba8cdbb
commit 41b4a77dea
31 changed files with 71 additions and 67 deletions

View File

@ -990,7 +990,7 @@ class Sphinx:
if isinstance(lexer, Lexer): if isinstance(lexer, Lexer):
warnings.warn('app.add_lexer() API changed; ' warnings.warn('app.add_lexer() API changed; '
'Please give lexer class instead instance', 'Please give lexer class instead instance',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
lexers[alias] = lexer lexers[alias] = lexer
else: else:
lexer_classes[alias] = lexer lexer_classes[alias] = lexer

View File

@ -173,7 +173,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
"""Replace all characters not allowed in text an attribute values.""" """Replace all characters not allowed in text an attribute values."""
warnings.warn( warnings.warn(
'%s.esc() is deprecated. Use html.escape() instead.' % self.__class__.__name__, '%s.esc() is deprecated. Use html.escape() instead.' % self.__class__.__name__,
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
name = name.replace('&', '&') name = name.replace('&', '&')
name = name.replace('<', '&lt;') name = name.replace('<', '&lt;')
name = name.replace('>', '&gt;') name = name.replace('>', '&gt;')

View File

@ -32,7 +32,7 @@ deprecated_alias('sphinx.builders.applehelp',
def setup(app: Sphinx) -> Dict[str, Any]: def setup(app: Sphinx) -> Dict[str, Any]:
warnings.warn('sphinx.builders.applehelp has been moved to sphinxcontrib-applehelp.', warnings.warn('sphinx.builders.applehelp has been moved to sphinxcontrib-applehelp.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
app.setup_extension('sphinxcontrib.applehelp') app.setup_extension('sphinxcontrib.applehelp')
return { return {

View File

@ -882,7 +882,7 @@ class StandaloneHTMLBuilder(Builder):
'The %s.feed() method signature is deprecated. Update to ' 'The %s.feed() method signature is deprecated. Update to '
'%s.feed(docname, filename, title, doctree).' % ( '%s.feed(docname, filename, title, doctree).' % (
indexer_name, indexer_name), indexer_name, indexer_name),
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
def _get_local_toctree(self, docname: str, collapse: bool = True, **kwargs: Any) -> str: def _get_local_toctree(self, docname: str, collapse: bool = True, **kwargs: Any) -> str:
if 'includehidden' not in kwargs: if 'includehidden' not in kwargs:

View File

@ -32,7 +32,7 @@ deprecated_alias('sphinx.builders.htmlhelp',
def setup(app: Sphinx) -> Dict[str, Any]: def setup(app: Sphinx) -> Dict[str, Any]:
warnings.warn('sphinx.builders.htmlhelp has been moved to sphinxcontrib-htmlhelp.', warnings.warn('sphinx.builders.htmlhelp has been moved to sphinxcontrib-htmlhelp.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
app.setup_extension('sphinxcontrib.htmlhelp') app.setup_extension('sphinxcontrib.htmlhelp')
return { return {

View File

@ -363,7 +363,7 @@ class LaTeXBuilder(Builder):
def apply_transforms(self, doctree: nodes.document) -> None: def apply_transforms(self, doctree: nodes.document) -> None:
warnings.warn('LaTeXBuilder.apply_transforms() is deprecated.', warnings.warn('LaTeXBuilder.apply_transforms() is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
def finish(self) -> None: def finish(self) -> None:
self.copy_image_files() self.copy_image_files()

View File

@ -187,7 +187,7 @@ def do_prompt(text: str, default: str = None, validator: Callable[[str], Any] =
def convert_python_source(source: str, rex: Pattern = re.compile(r"[uU]('.*?')")) -> str: def convert_python_source(source: str, rex: Pattern = re.compile(r"[uU]('.*?')")) -> str:
# remove Unicode literal prefixes # remove Unicode literal prefixes
warnings.warn('convert_python_source() is deprecated.', warnings.warn('convert_python_source() is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
return rex.sub('\\1', source) return rex.sub('\\1', source)

View File

@ -444,7 +444,7 @@ def check_unicode(config: Config) -> None:
since that can result in UnicodeErrors all over the place since that can result in UnicodeErrors all over the place
""" """
warnings.warn('sphinx.config.check_unicode() is deprecated.', warnings.warn('sphinx.config.check_unicode() is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
nonascii_re = re.compile(br'[\x80-\xff]') nonascii_re = re.compile(br'[\x80-\xff]')

View File

@ -142,7 +142,7 @@ class MathDomain(Domain):
def add_equation(self, env: BuildEnvironment, docname: str, labelid: str) -> int: def add_equation(self, env: BuildEnvironment, docname: str, labelid: str) -> int:
warnings.warn('MathDomain.add_equation() is deprecated.', warnings.warn('MathDomain.add_equation() is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
if labelid in self.equations: if labelid in self.equations:
path = env.doc2path(self.equations[labelid][0]) path = env.doc2path(self.equations[labelid][0])
msg = __('duplicate label of equation %s, other instance in %s') % (labelid, path) msg = __('duplicate label of equation %s, other instance in %s') % (labelid, path)
@ -154,7 +154,7 @@ class MathDomain(Domain):
def get_next_equation_number(self, docname: str) -> int: def get_next_equation_number(self, docname: str) -> int:
warnings.warn('MathDomain.get_next_equation_number() is deprecated.', warnings.warn('MathDomain.get_next_equation_number() is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
targets = [eq for eq in self.equations.values() if eq[0] == docname] targets = [eq for eq in self.equations.values() if eq[0] == docname]
return len(targets) + 1 return len(targets) + 1

View File

@ -530,10 +530,11 @@ class PyModulelevel(PyObject):
if cls.__name__ != 'DirectiveAdapter': if cls.__name__ != 'DirectiveAdapter':
warnings.warn('PyModulelevel is deprecated. ' warnings.warn('PyModulelevel is deprecated. '
'Please check the implementation of %s' % cls, 'Please check the implementation of %s' % cls,
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
break break
else: else:
warnings.warn('PyModulelevel is deprecated', RemovedInSphinx40Warning) warnings.warn('PyModulelevel is deprecated',
RemovedInSphinx40Warning, stacklevel=2)
return super().run() return super().run()
@ -675,10 +676,11 @@ class PyClassmember(PyObject):
if cls.__name__ != 'DirectiveAdapter': if cls.__name__ != 'DirectiveAdapter':
warnings.warn('PyClassmember is deprecated. ' warnings.warn('PyClassmember is deprecated. '
'Please check the implementation of %s' % cls, 'Please check the implementation of %s' % cls,
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
break break
else: else:
warnings.warn('PyClassmember is deprecated', RemovedInSphinx40Warning) warnings.warn('PyClassmember is deprecated',
RemovedInSphinx40Warning, stacklevel=2)
return super().run() return super().run()
@ -896,10 +898,11 @@ class PyDecoratorMixin:
if cls.__name__ != 'DirectiveAdapter': if cls.__name__ != 'DirectiveAdapter':
warnings.warn('PyDecoratorMixin is deprecated. ' warnings.warn('PyDecoratorMixin is deprecated. '
'Please check the implementation of %s' % cls, 'Please check the implementation of %s' % cls,
RemovedInSphinx50Warning) RemovedInSphinx50Warning, stacklevel=2)
break break
else: else:
warnings.warn('PyDecoratorMixin is deprecated', RemovedInSphinx50Warning) warnings.warn('PyDecoratorMixin is deprecated',
RemovedInSphinx50Warning, stacklevel=2)
ret = super().handle_signature(sig, signode) # type: ignore ret = super().handle_signature(sig, signode) # type: ignore
signode.insert(0, addnodes.desc_addname('@', '@')) signode.insert(0, addnodes.desc_addname('@', '@'))

View File

@ -292,7 +292,7 @@ def make_glossary_term(env: "BuildEnvironment", textnodes: Iterable[Node], index
document.note_explicit_target(term) document.note_explicit_target(term)
else: else:
warnings.warn('make_glossary_term() expects document is passed as an argument.', warnings.warn('make_glossary_term() expects document is passed as an argument.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
gloss_entries = env.temp_data.setdefault('gloss_entries', set()) gloss_entries = env.temp_data.setdefault('gloss_entries', set())
node_id = nodes.make_id('term-' + termtext) node_id = nodes.make_id('term-' + termtext)
if node_id == 'term': if node_id == 'term':
@ -660,7 +660,7 @@ class StandardDomain(Domain):
def add_object(self, objtype: str, name: str, docname: str, labelid: str) -> None: def add_object(self, objtype: str, name: str, docname: str, labelid: str) -> None:
warnings.warn('StandardDomain.add_object() is deprecated.', warnings.warn('StandardDomain.add_object() is deprecated.',
RemovedInSphinx50Warning) RemovedInSphinx50Warning, stacklevel=2)
self.objects[objtype, name] = (docname, labelid) self.objects[objtype, name] = (docname, labelid)
@property @property
@ -786,7 +786,7 @@ class StandardDomain(Domain):
resolver = self._resolve_option_xref resolver = self._resolve_option_xref
elif typ == 'citation': elif typ == 'citation':
warnings.warn('pending_xref(domain=std, type=citation) is deprecated: %r' % node, warnings.warn('pending_xref(domain=std, type=citation) is deprecated: %r' % node,
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
domain = env.get_domain('citation') domain = env.get_domain('citation')
return domain.resolve_xref(env, fromdocname, builder, typ, target, node, contnode) return domain.resolve_xref(env, fromdocname, builder, typ, target, node, contnode)
elif typ == 'term': elif typ == 'term':
@ -1082,15 +1082,15 @@ class StandardDomain(Domain):
def note_citations(self, env: "BuildEnvironment", docname: str, document: nodes.document) -> None: # NOQA def note_citations(self, env: "BuildEnvironment", docname: str, document: nodes.document) -> None: # NOQA
warnings.warn('StandardDomain.note_citations() is deprecated.', warnings.warn('StandardDomain.note_citations() is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
def note_citation_refs(self, env: "BuildEnvironment", docname: str, document: nodes.document) -> None: # NOQA def note_citation_refs(self, env: "BuildEnvironment", docname: str, document: nodes.document) -> None: # NOQA
warnings.warn('StandardDomain.note_citation_refs() is deprecated.', warnings.warn('StandardDomain.note_citation_refs() is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
def note_labels(self, env: "BuildEnvironment", docname: str, document: nodes.document) -> None: # NOQA def note_labels(self, env: "BuildEnvironment", docname: str, document: nodes.document) -> None: # NOQA
warnings.warn('StandardDomain.note_labels() is deprecated.', warnings.warn('StandardDomain.note_labels() is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
def setup(app: "Sphinx") -> Dict[str, Any]: def setup(app: "Sphinx") -> Dict[str, Any]:

View File

@ -331,10 +331,10 @@ class BuildEnvironment:
""" """
if suffix: if suffix:
warnings.warn('The suffix argument for doc2path() is deprecated.', warnings.warn('The suffix argument for doc2path() is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
if base not in (True, False, None): if base not in (True, False, None):
warnings.warn('The string style base argument for doc2path() is deprecated.', warnings.warn('The string style base argument for doc2path() is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
pathname = self.project.doc2path(docname, base is True) pathname = self.project.doc2path(docname, base is True)
if suffix: if suffix:

View File

@ -29,7 +29,7 @@ class IndexEntriesCollector(EnvironmentCollector):
def __init__(self) -> None: def __init__(self) -> None:
warnings.warn('IndexEntriesCollector is deprecated.', warnings.warn('IndexEntriesCollector is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
def clear_doc(self, app: Sphinx, env: BuildEnvironment, docname: str) -> None: def clear_doc(self, app: Sphinx, env: BuildEnvironment, docname: str) -> None:
env.indexentries.pop(docname, None) env.indexentries.pop(docname, None)

View File

@ -54,7 +54,7 @@ template_dir = path.join(package_dir, 'templates', 'apidoc')
def makename(package: str, module: str) -> str: def makename(package: str, module: str) -> str:
"""Join package and module with a dot.""" """Join package and module with a dot."""
warnings.warn('makename() is deprecated.', warnings.warn('makename() is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
# Both package and module can be None/empty. # Both package and module can be None/empty.
if package: if package:
name = package name = package
@ -112,7 +112,7 @@ def write_file(name: str, text: str, opts: Any) -> None:
def format_heading(level: int, text: str, escape: bool = True) -> str: def format_heading(level: int, text: str, escape: bool = True) -> str:
"""Create a heading of <level> [1, 2 or 3 supported].""" """Create a heading of <level> [1, 2 or 3 supported]."""
warnings.warn('format_warning() is deprecated.', warnings.warn('format_warning() is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
if escape: if escape:
text = rst.escape(text) text = rst.escape(text)
underlining = ['=', '-', '~', ][level - 1] * len(text) underlining = ['=', '-', '~', ][level - 1] * len(text)
@ -122,7 +122,7 @@ def format_heading(level: int, text: str, escape: bool = True) -> str:
def format_directive(module: str, package: str = None) -> str: def format_directive(module: str, package: str = None) -> str:
"""Create the automodule directive and add the options.""" """Create the automodule directive and add the options."""
warnings.warn('format_directive() is deprecated.', warnings.warn('format_directive() is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
directive = '.. automodule:: %s\n' % module_join(package, module) directive = '.. automodule:: %s\n' % module_join(package, module)
for option in OPTIONS: for option in OPTIONS:
directive += ' :%s:\n' % option directive += ' :%s:\n' % option
@ -209,7 +209,7 @@ def create_modules_toc_file(modules: List[str], opts: Any, name: str = 'modules'
def shall_skip(module: str, opts: Any, excludes: List[str] = []) -> bool: def shall_skip(module: str, opts: Any, excludes: List[str] = []) -> bool:
"""Check if we want to skip this module.""" """Check if we want to skip this module."""
warnings.warn('shall_skip() is deprecated.', warnings.warn('shall_skip() is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
# skip if the file doesn't exist and not using implicit namespaces # skip if the file doesn't exist and not using implicit namespaces
if not opts.implicit_namespaces and not path.exists(module): if not opts.implicit_namespaces and not path.exists(module):
return True return True

View File

@ -434,7 +434,7 @@ class Documenter:
if encoding is not None: if encoding is not None:
warnings.warn("The 'encoding' argument to autodoc.%s.get_doc() is deprecated." warnings.warn("The 'encoding' argument to autodoc.%s.get_doc() is deprecated."
% self.__class__.__name__, % self.__class__.__name__,
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
if ignore is not None: if ignore is not None:
warnings.warn("The 'ignore' argument to autodoc.%s.get_doc() is deprecated." warnings.warn("The 'ignore' argument to autodoc.%s.get_doc() is deprecated."
% self.__class__.__name__, % self.__class__.__name__,
@ -953,7 +953,7 @@ class DocstringSignatureMixin:
if encoding is not None: if encoding is not None:
warnings.warn("The 'encoding' argument to autodoc.%s._find_signature() is " warnings.warn("The 'encoding' argument to autodoc.%s._find_signature() is "
"deprecated." % self.__class__.__name__, "deprecated." % self.__class__.__name__,
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
docstrings = self.get_doc() docstrings = self.get_doc()
self._new_docstrings = docstrings[:] self._new_docstrings = docstrings[:]
result = None result = None
@ -987,7 +987,7 @@ class DocstringSignatureMixin:
if encoding is not None: if encoding is not None:
warnings.warn("The 'encoding' argument to autodoc.%s.get_doc() is deprecated." warnings.warn("The 'encoding' argument to autodoc.%s.get_doc() is deprecated."
% self.__class__.__name__, % self.__class__.__name__,
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
lines = getattr(self, '_new_docstrings', None) lines = getattr(self, '_new_docstrings', None)
if lines is not None: if lines is not None:
return lines return lines
@ -1247,7 +1247,7 @@ class ClassDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # type:
if encoding is not None: if encoding is not None:
warnings.warn("The 'encoding' argument to autodoc.%s.get_doc() is deprecated." warnings.warn("The 'encoding' argument to autodoc.%s.get_doc() is deprecated."
% self.__class__.__name__, % self.__class__.__name__,
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
lines = getattr(self, '_new_docstrings', None) lines = getattr(self, '_new_docstrings', None)
if lines is not None: if lines is not None:
return lines return lines
@ -1757,7 +1757,7 @@ class SlotsAttributeDocumenter(AttributeDocumenter):
def get_documenters(app: Sphinx) -> Dict[str, "Type[Documenter]"]: def get_documenters(app: Sphinx) -> Dict[str, "Type[Documenter]"]:
"""Returns registered Documenter classes""" """Returns registered Documenter classes"""
warnings.warn("get_documenters() is deprecated.", RemovedInSphinx50Warning) warnings.warn("get_documenters() is deprecated.", RemovedInSphinx50Warning, stacklevel=2)
return app.registry.documenters return app.registry.documenters

View File

@ -66,7 +66,7 @@ class DocumenterBridge:
else: else:
# create fake object for self.state.document.settings.tab_width # create fake object for self.state.document.settings.tab_width
warnings.warn('DocumenterBridge requires a state object on instantiation.', warnings.warn('DocumenterBridge requires a state object on instantiation.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
settings = Struct(tab_width=8) settings = Struct(tab_width=8)
document = Struct(settings=settings) document = Struct(settings=settings)
self.state = Struct(document=document) self.state = Struct(document=document)

View File

@ -659,7 +659,7 @@ def autolink_role(typ: str, rawtext: str, etext: str, lineno: int, inliner: Inli
Expands to ':obj:`text`' if `text` is an object that can be imported; Expands to ':obj:`text`' if `text` is an object that can be imported;
otherwise expands to '*text*'. otherwise expands to '*text*'.
""" """
warnings.warn('autolink_role() is deprecated.', RemovedInSphinx40Warning) warnings.warn('autolink_role() is deprecated.', RemovedInSphinx40Warning, stacklevel=2)
env = inliner.document.settings.env env = inliner.document.settings.env
pyobj_role = env.get_domain('py').role('obj') pyobj_role = env.get_domain('py').role('obj')
objects, msg = pyobj_role('obj', rawtext, etext, lineno, inliner, options, content) objects, msg = pyobj_role('obj', rawtext, etext, lineno, inliner, options, content)

View File

@ -126,7 +126,7 @@ class AutosummaryRenderer:
RemovedInSphinx50Warning, stacklevel=2) RemovedInSphinx50Warning, stacklevel=2)
if template_dir: if template_dir:
warnings.warn('template_dir argument for AutosummaryRenderer is deprecated.', warnings.warn('template_dir argument for AutosummaryRenderer is deprecated.',
RemovedInSphinx50Warning) RemovedInSphinx50Warning, stacklevel=2)
system_templates_path = [os.path.join(package_dir, 'ext', 'autosummary', 'templates')] system_templates_path = [os.path.join(package_dir, 'ext', 'autosummary', 'templates')]
loader = SphinxTemplateLoader(app.srcdir, app.config.templates_path, loader = SphinxTemplateLoader(app.srcdir, app.config.templates_path,
@ -279,25 +279,25 @@ def generate_autosummary_docs(sources: List[str], output_dir: str = None,
overwrite: bool = True) -> None: overwrite: bool = True) -> None:
if info: if info:
warnings.warn('info argument for generate_autosummary_docs() is deprecated.', warnings.warn('info argument for generate_autosummary_docs() is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
_info = info _info = info
else: else:
_info = logger.info _info = logger.info
if warn: if warn:
warnings.warn('warn argument for generate_autosummary_docs() is deprecated.', warnings.warn('warn argument for generate_autosummary_docs() is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
_warn = warn _warn = warn
else: else:
_warn = logger.warning _warn = logger.warning
if builder: if builder:
warnings.warn('builder argument for generate_autosummary_docs() is deprecated.', warnings.warn('builder argument for generate_autosummary_docs() is deprecated.',
RemovedInSphinx50Warning) RemovedInSphinx50Warning, stacklevel=2)
if template_dir: if template_dir:
warnings.warn('template_dir argument for generate_autosummary_docs() is deprecated.', warnings.warn('template_dir argument for generate_autosummary_docs() is deprecated.',
RemovedInSphinx50Warning) RemovedInSphinx50Warning, stacklevel=2)
showed_sources = list(sorted(sources)) showed_sources = list(sorted(sources))
if len(showed_sources) > 20: if len(showed_sources) > 20:
@ -390,7 +390,7 @@ def find_autosummary_in_docstring(name: str, module: str = None, filename: str =
""" """
if module: if module:
warnings.warn('module argument for find_autosummary_in_docstring() is deprecated.', warnings.warn('module argument for find_autosummary_in_docstring() is deprecated.',
RemovedInSphinx50Warning) RemovedInSphinx50Warning, stacklevel=2)
try: try:
real_name, obj, parent, modname = import_by_name(name) real_name, obj, parent, modname = import_by_name(name)

View File

@ -47,7 +47,7 @@ doctestopt_re = re.compile(r'#\s*doctest:.+$', re.MULTILINE)
def doctest_encode(text: str, encoding: str) -> str: def doctest_encode(text: str, encoding: str) -> str:
warnings.warn('doctest_encode() is deprecated.', warnings.warn('doctest_encode() is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
return text return text

View File

@ -105,7 +105,7 @@ class TodoDomain(Domain):
def process_todos(app: Sphinx, doctree: nodes.document) -> None: def process_todos(app: Sphinx, doctree: nodes.document) -> None:
warnings.warn('process_todos() is deprecated.', RemovedInSphinx40Warning) warnings.warn('process_todos() is deprecated.', RemovedInSphinx40Warning, stacklevel=2)
# collect all todos in the environment # collect all todos in the environment
# this is not done in the directive itself because it some transformations # this is not done in the directive itself because it some transformations
# must have already been run, e.g. substitutions # must have already been run, e.g. substitutions
@ -221,7 +221,8 @@ def process_todo_nodes(app: Sphinx, doctree: nodes.document, fromdocname: str) -
"""Replace all todolist nodes with a list of the collected todos. """Replace all todolist nodes with a list of the collected todos.
Augment each todo with a backlink to the original location. Augment each todo with a backlink to the original location.
""" """
warnings.warn('process_todo_nodes() is deprecated.', RemovedInSphinx40Warning) warnings.warn('process_todo_nodes() is deprecated.',
RemovedInSphinx40Warning, stacklevel=2)
domain = cast(TodoDomain, app.env.get_domain('todo')) domain = cast(TodoDomain, app.env.get_domain('todo'))
todos = sum(domain.todos.values(), []) # type: List[todo_node] todos = sum(domain.todos.values(), []) # type: List[todo_node]
@ -273,7 +274,7 @@ def process_todo_nodes(app: Sphinx, doctree: nodes.document, fromdocname: str) -
def purge_todos(app: Sphinx, env: BuildEnvironment, docname: str) -> None: def purge_todos(app: Sphinx, env: BuildEnvironment, docname: str) -> None:
warnings.warn('purge_todos() is deprecated.', RemovedInSphinx40Warning) warnings.warn('purge_todos() is deprecated.', RemovedInSphinx40Warning, stacklevel=2)
if not hasattr(env, 'todo_all_todos'): if not hasattr(env, 'todo_all_todos'):
return return
env.todo_all_todos = [todo for todo in env.todo_all_todos # type: ignore env.todo_all_todos = [todo for todo in env.todo_all_todos # type: ignore
@ -282,7 +283,7 @@ def purge_todos(app: Sphinx, env: BuildEnvironment, docname: str) -> None:
def merge_info(app: Sphinx, env: BuildEnvironment, docnames: Iterable[str], def merge_info(app: Sphinx, env: BuildEnvironment, docnames: Iterable[str],
other: BuildEnvironment) -> None: other: BuildEnvironment) -> None:
warnings.warn('merge_info() is deprecated.', RemovedInSphinx40Warning) warnings.warn('merge_info() is deprecated.', RemovedInSphinx40Warning, stacklevel=2)
if not hasattr(other, 'todo_all_todos'): if not hasattr(other, 'todo_all_todos'):
return return
if not hasattr(env, 'todo_all_todos'): if not hasattr(env, 'todo_all_todos'):

View File

@ -64,7 +64,7 @@ class Parser(docutils.parsers.Parser):
@property @property
def app(self) -> "Sphinx": def app(self) -> "Sphinx":
warnings.warn('parser.app is deprecated.', RemovedInSphinx50Warning) warnings.warn('parser.app is deprecated.', RemovedInSphinx50Warning, stacklevel=2)
return self._app return self._app

View File

@ -133,7 +133,7 @@ class ModuleAnalyzer:
pos = source.tell() pos = source.tell()
if not decoded: if not decoded:
warnings.warn('decode option for ModuleAnalyzer is deprecated.', warnings.warn('decode option for ModuleAnalyzer is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
self._encoding, _ = tokenize.detect_encoding(source.readline) self._encoding, _ = tokenize.detect_encoding(source.readline)
source.seek(pos) source.seek(pos)
self.code = source.read().decode(self._encoding) self.code = source.read().decode(self._encoding)
@ -185,5 +185,5 @@ class ModuleAnalyzer:
@property @property
def encoding(self) -> str: def encoding(self) -> str:
warnings.warn('ModuleAnalyzer.encoding is deprecated.', warnings.warn('ModuleAnalyzer.encoding is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
return self._encoding return self._encoding

View File

@ -574,7 +574,7 @@ def index_role(typ: str, rawtext: str, text: str, lineno: int, inliner: Inliner,
class Index(ReferenceRole): class Index(ReferenceRole):
def run(self) -> Tuple[List[Node], List[system_message]]: def run(self) -> Tuple[List[Node], List[system_message]]:
warnings.warn('Index role is deprecated.', RemovedInSphinx40Warning) warnings.warn('Index role is deprecated.', RemovedInSphinx40Warning, stacklevel=2)
target_id = 'index-%s' % self.env.new_serialno('index') target_id = 'index-%s' % self.env.new_serialno('index')
if self.has_explicit_title: if self.has_explicit_title:
# if an explicit target is given, process it as a full entry # if an explicit target is given, process it as a full entry

View File

@ -203,7 +203,7 @@ class WordCollector(nodes.NodeVisitor):
def is_meta_keywords(self, node: addnodes.meta, nodetype: Any = None) -> bool: def is_meta_keywords(self, node: addnodes.meta, nodetype: Any = None) -> bool:
if nodetype is not None: if nodetype is not None:
warnings.warn('"nodetype" argument for WordCollector.is_meta_keywords() ' warnings.warn('"nodetype" argument for WordCollector.is_meta_keywords() '
'is deprecated.', RemovedInSphinx40Warning) 'is deprecated.', RemovedInSphinx40Warning, stacklevel=2)
if isinstance(node, addnodes.meta) and node.get('name') == 'keywords': if isinstance(node, addnodes.meta) and node.get('name') == 'keywords':
meta_lang = node.get('lang') meta_lang = node.get('lang')

View File

@ -110,7 +110,7 @@ def get_matching_docs(dirname: str, suffixes: List[str],
Exclude files and dirs matching a pattern in *exclude_patterns*. Exclude files and dirs matching a pattern in *exclude_patterns*.
""" """
warnings.warn('get_matching_docs() is now deprecated. Use get_matching_files() instead.', warnings.warn('get_matching_docs() is now deprecated. Use get_matching_files() instead.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
suffixpatterns = ['*' + s for s in suffixes] suffixpatterns = ['*' + s for s in suffixes]
for filename in get_matching_files(dirname, exclude_matchers): for filename in get_matching_files(dirname, exclude_matchers):
for suffixpattern in suffixpatterns: for suffixpattern in suffixpatterns:
@ -315,7 +315,7 @@ _coding_re = re.compile(r'coding[:=]\s*([-\w.]+)')
def detect_encoding(readline: Callable[[], bytes]) -> str: def detect_encoding(readline: Callable[[], bytes]) -> str:
"""Like tokenize.detect_encoding() from Py3k, but a bit simplified.""" """Like tokenize.detect_encoding() from Py3k, but a bit simplified."""
warnings.warn('sphinx.util.detect_encoding() is deprecated', warnings.warn('sphinx.util.detect_encoding() is deprecated',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
def read_or_stop() -> bytes: def read_or_stop() -> bytes:
try: try:

View File

@ -46,7 +46,7 @@ class IndexEntriesMigrator(SphinxTransform):
if len(entries) == 4: if len(entries) == 4:
source, line = get_source_line(node) source, line = get_source_line(node)
warnings.warn('An old styled index node found: %r at (%s:%s)' % warnings.warn('An old styled index node found: %r at (%s:%s)' %
(node, source, line), RemovedInSphinx40Warning) (node, source, line), RemovedInSphinx40Warning, stacklevel=2)
node['entries'][i] = entries + (None,) node['entries'][i] = entries + (None,)

View File

@ -224,12 +224,12 @@ class DocFieldTransformer:
except Exception: except Exception:
# for 3rd party extensions directly calls this transformer. # for 3rd party extensions directly calls this transformer.
warnings.warn('DocFieldTransformer expects given directive object is a subclass ' warnings.warn('DocFieldTransformer expects given directive object is a subclass '
'of ObjectDescription.', RemovedInSphinx40Warning) 'of ObjectDescription.', RemovedInSphinx40Warning, stacklevel=2)
self.typemap = self.preprocess_fieldtypes(directive.__class__.doc_field_types) self.typemap = self.preprocess_fieldtypes(directive.__class__.doc_field_types)
def preprocess_fieldtypes(self, types: List[Field]) -> Dict[str, Tuple[Field, bool]]: def preprocess_fieldtypes(self, types: List[Field]) -> Dict[str, Tuple[Field, bool]]:
warnings.warn('DocFieldTransformer.preprocess_fieldtypes() is deprecated.', warnings.warn('DocFieldTransformer.preprocess_fieldtypes() is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
typemap = {} typemap = {}
for fieldtype in types: for fieldtype in types:
for name in fieldtype.names: for name in fieldtype.names:

View File

@ -58,7 +58,7 @@ def getargspec(func: Callable) -> Any:
"""Like inspect.getfullargspec but supports bound methods, and wrapped """Like inspect.getfullargspec but supports bound methods, and wrapped
methods.""" methods."""
warnings.warn('sphinx.ext.inspect.getargspec() is deprecated', warnings.warn('sphinx.ext.inspect.getargspec() is deprecated',
RemovedInSphinx50Warning) RemovedInSphinx50Warning, stacklevel=2)
# On 3.5+, signature(int) or similar raises ValueError. On 3.4, it # On 3.5+, signature(int) or similar raises ValueError. On 3.4, it
# succeeds with a bogus signature. We want a TypeError uniformly, to # succeeds with a bogus signature. We want a TypeError uniformly, to
# match historical behavior. # match historical behavior.
@ -329,7 +329,7 @@ def safe_getattr(obj: Any, name: str, *defargs: Any) -> Any:
def safe_getmembers(object: Any, predicate: Callable[[str], bool] = None, def safe_getmembers(object: Any, predicate: Callable[[str], bool] = None,
attr_getter: Callable = safe_getattr) -> List[Tuple[str, Any]]: attr_getter: Callable = safe_getattr) -> List[Tuple[str, Any]]:
"""A version of inspect.getmembers() that uses safe_getattr().""" """A version of inspect.getmembers() that uses safe_getattr()."""
warnings.warn('safe_getmembers() is deprecated', RemovedInSphinx40Warning) warnings.warn('safe_getmembers() is deprecated', RemovedInSphinx40Warning, stacklevel=2)
results = [] # type: List[Tuple[str, Any]] results = [] # type: List[Tuple[str, Any]]
for key in dir(object): for key in dir(object):
@ -555,7 +555,7 @@ class Signature:
def __init__(self, subject: Callable, bound_method: bool = False, def __init__(self, subject: Callable, bound_method: bool = False,
has_retval: bool = True) -> None: has_retval: bool = True) -> None:
warnings.warn('sphinx.util.inspect.Signature() is deprecated', warnings.warn('sphinx.util.inspect.Signature() is deprecated',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
# check subject is not a built-in class (ex. int, str) # check subject is not a built-in class (ex. int, str)
if (isinstance(subject, type) and if (isinstance(subject, type) and

View File

@ -280,7 +280,7 @@ def extract_messages(doctree: Element) -> Iterable[Tuple[Element, str]]:
def find_source_node(node: Element) -> str: def find_source_node(node: Element) -> str:
warnings.warn('find_source_node() is deprecated.', warnings.warn('find_source_node() is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
return get_node_source(node) return get_node_source(node)

View File

@ -86,7 +86,7 @@ def ensuredir(path: str) -> None:
def walk(top: str, topdown: bool = True, followlinks: bool = False) -> Iterator[Tuple[str, List[str], List[str]]]: # NOQA def walk(top: str, topdown: bool = True, followlinks: bool = False) -> Iterator[Tuple[str, List[str], List[str]]]: # NOQA
warnings.warn('sphinx.util.osutil.walk() is deprecated for removal. ' warnings.warn('sphinx.util.osutil.walk() is deprecated for removal. '
'Please use os.walk() instead.', 'Please use os.walk() instead.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
return os.walk(top, topdown=topdown, followlinks=followlinks) return os.walk(top, topdown=topdown, followlinks=followlinks)
@ -178,7 +178,7 @@ def abspath(pathdir: str) -> str:
def getcwd() -> str: def getcwd() -> str:
warnings.warn('sphinx.util.osutil.getcwd() is deprecated. ' warnings.warn('sphinx.util.osutil.getcwd() is deprecated. '
'Please use os.getcwd() instead.', 'Please use os.getcwd() instead.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
return os.getcwd() return os.getcwd()

View File

@ -96,7 +96,7 @@ class LaTeXWriter(writers.Writer):
visitor = self.builder.create_translator(self.document, self.builder, self.theme) visitor = self.builder.create_translator(self.document, self.builder, self.theme)
except TypeError: except TypeError:
warnings.warn('LaTeXTranslator now takes 3rd argument; "theme".', warnings.warn('LaTeXTranslator now takes 3rd argument; "theme".',
RemovedInSphinx50Warning) RemovedInSphinx50Warning, stacklevel=2)
visitor = self.builder.create_translator(self.document, self.builder) visitor = self.builder.create_translator(self.document, self.builder)
self.document.walkabout(visitor) self.document.walkabout(visitor)
@ -292,7 +292,7 @@ class LaTeXTranslator(SphinxTranslator):
if theme is None: if theme is None:
warnings.warn('LaTeXTranslator now takes 3rd argument; "theme".', warnings.warn('LaTeXTranslator now takes 3rd argument; "theme".',
RemovedInSphinx50Warning) RemovedInSphinx50Warning, stacklevel=2)
# flags # flags
self.in_title = 0 self.in_title = 0
@ -2072,7 +2072,7 @@ class LaTeXTranslator(SphinxTranslator):
def babel_defmacro(self, name: str, definition: str) -> str: def babel_defmacro(self, name: str, definition: str) -> str:
warnings.warn('babel_defmacro() is deprecated.', warnings.warn('babel_defmacro() is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
if self.elements['babel']: if self.elements['babel']:
prefix = '\\addto\\extras%s{' % self.babel.get_language() prefix = '\\addto\\extras%s{' % self.babel.get_language()
@ -2085,7 +2085,7 @@ class LaTeXTranslator(SphinxTranslator):
def generate_numfig_format(self, builder: "LaTeXBuilder") -> str: def generate_numfig_format(self, builder: "LaTeXBuilder") -> str:
warnings.warn('generate_numfig_format() is deprecated.', warnings.warn('generate_numfig_format() is deprecated.',
RemovedInSphinx40Warning) RemovedInSphinx40Warning, stacklevel=2)
ret = [] # type: List[str] ret = [] # type: List[str]
figure = self.builder.config.numfig_format['figure'].split('%s', 1) figure = self.builder.config.numfig_format['figure'].split('%s', 1)
if len(figure) == 1: if len(figure) == 1: