Merge pull request #5784 from tk0miya/refactor_hack_for_py2

Refactor hack for py2
This commit is contained in:
Takeshi KOMIYA 2018-12-15 22:40:46 +09:00 committed by GitHub
commit 415ebc15c5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 29 additions and 46 deletions

View File

@ -62,7 +62,8 @@ Deprecated
* ``sphinx.testing.util.remove_unicode_literal()`` * ``sphinx.testing.util.remove_unicode_literal()``
* ``sphinx.util.attrdict`` * ``sphinx.util.attrdict``
* ``sphinx.util.force_decode()`` * ``sphinx.util.force_decode()``
* ``sphinx.util.get_matching_docs()`` is deprecated * ``sphinx.util.get_matching_docs()``
* ``sphinx.util.inspect.Parameter``
* ``sphinx.util.osutil.walk()`` * ``sphinx.util.osutil.walk()``
* ``sphinx.util.PeekableIterator`` * ``sphinx.util.PeekableIterator``
* ``sphinx.util.pycompat.u`` * ``sphinx.util.pycompat.u``

View File

@ -202,6 +202,11 @@ The following is a list of deprecated interfaces.
- 4.0 - 4.0
- ``sphinx.util.get_matching_files()`` - ``sphinx.util.get_matching_files()``
* - ``sphinx.util.inspect.Parameter``
- 2.0
- 3.0
- N/A
* - ``sphinx.util.osutil.walk()`` * - ``sphinx.util.osutil.walk()``
- 2.0 - 2.0
- 4.0 - 4.0

View File

@ -22,7 +22,6 @@ from .deprecation import RemovedInNextVersionWarning
if False: if False:
# For type annotation # For type annotation
# note: Don't use typing.TYPE_CHECK here (for py27 and py34).
from typing import Any # NOQA from typing import Any # NOQA

View File

@ -418,8 +418,7 @@ class StandaloneHTMLBuilder(Builder):
buildinfo = BuildInfo.load(fp) buildinfo = BuildInfo.load(fp)
if self.build_info != buildinfo: if self.build_info != buildinfo:
for docname in self.env.found_docs: yield from self.env.found_docs
yield docname
return return
except ValueError as exc: except ValueError as exc:
logger.warning(__('Failed to read build info file: %r'), exc) logger.warning(__('Failed to read build info file: %r'), exc)

View File

@ -13,7 +13,6 @@ import warnings
if False: if False:
# For type annotation # For type annotation
# note: Don't use typing.TYPE_CHECK here (for py27 and py34).
from typing import Any, Dict, Type # NOQA from typing import Any, Dict, Type # NOQA
from sphinx.util.typing import unicode # NOQA from sphinx.util.typing import unicode # NOQA

View File

@ -3845,9 +3845,8 @@ class Symbol:
yield c yield c
if not c.identOrOp.is_anon(): if not c.identOrOp.is_anon():
continue continue
# TODO: change to 'yield from' when Python 2 support is dropped
for nested in c.children_recurse_anon: yield from c.children_recurse_anon
yield nested
def get_lookup_key(self): def get_lookup_key(self):
# type: () -> List[Tuple[ASTNestedNameElement, Any]] # type: () -> List[Tuple[ASTNestedNameElement, Any]]

View File

@ -458,8 +458,7 @@ class Documenter:
self.env.app.emit('autodoc-process-docstring', self.env.app.emit('autodoc-process-docstring',
self.objtype, self.fullname, self.object, self.objtype, self.fullname, self.object,
self.options, docstringlines) self.options, docstringlines)
for line in docstringlines: yield from docstringlines
yield line
def get_sourcename(self): def get_sourcename(self):
# type: () -> unicode # type: () -> unicode

View File

@ -667,8 +667,7 @@ def status_iterator(iterable, summary, color="darkgreen", length=0, verbosity=0,
stringify_func=display_chunk): stringify_func=display_chunk):
# type: (Iterable, unicode, str, int, int, Callable[[Any], unicode]) -> Iterable # NOQA # type: (Iterable, unicode, str, int, int, Callable[[Any], unicode]) -> Iterable # NOQA
if length == 0: if length == 0:
for item in old_status_iterator(iterable, summary, color, stringify_func): yield from old_status_iterator(iterable, summary, color, stringify_func)
yield item
return return
l = 0 l = 0
summary = bold(summary) summary = bold(summary)

View File

@ -16,9 +16,11 @@ import inspect
import re import re
import sys import sys
import typing import typing
import warnings
from functools import partial from functools import partial
from io import StringIO from io import StringIO
from sphinx.deprecation import RemovedInSphinx30Warning
from sphinx.util import logging from sphinx.util import logging
from sphinx.util.pycompat import NoneType from sphinx.util.pycompat import NoneType
@ -128,10 +130,7 @@ def isclassmethod(obj):
"""Check if the object is classmethod.""" """Check if the object is classmethod."""
if isinstance(obj, classmethod): if isinstance(obj, classmethod):
return True return True
elif inspect.ismethod(obj): elif inspect.ismethod(obj) and obj.__self__ is not None:
if getattr(obj, 'im_self', None): # py2
return True
elif getattr(obj, '__self__', None): # py3
return True return True
return False return False
@ -288,6 +287,9 @@ class Parameter:
self.default = default self.default = default
self.annotation = self.empty self.annotation = self.empty
warnings.warn('sphinx.util.inspect.Parameter is deprecated.',
RemovedInSphinx30Warning, stacklevel=2)
class Signature: class Signature:
"""The Signature object represents the call signature of a callable object and """The Signature object represents the call signature of a callable object and

View File

@ -47,7 +47,7 @@ except ImportError:
# try to load requests[security] (but only if SSL is available) # try to load requests[security] (but only if SSL is available)
try: try:
import ssl import ssl # NOQA
except ImportError: except ImportError:
pass pass
else: else:
@ -55,17 +55,7 @@ else:
pkg_resources.require(['requests[security]']) pkg_resources.require(['requests[security]'])
except (pkg_resources.DistributionNotFound, except (pkg_resources.DistributionNotFound,
pkg_resources.VersionConflict): pkg_resources.VersionConflict):
if not getattr(ssl, 'HAS_SNI', False): pass # ignored
# don't complain on each url processed about the SSL issue
if InsecurePlatformWarning:
requests.packages.urllib3.disable_warnings(InsecurePlatformWarning)
warnings.warn(
'Some links may return broken results due to being unable to '
'check the Server Name Indication (SNI) in the returned SSL cert '
'against the hostname in the url requested. Recommended to '
'install "requests[security]" as a dependency or upgrade to '
'a python version with SNI support (Python 3 and Python 2.7.9+).'
)
except pkg_resources.UnknownExtra: except pkg_resources.UnknownExtra:
warnings.warn( warnings.warn(
'Some links may return broken results due to being unable to ' 'Some links may return broken results due to being unable to '

View File

@ -926,8 +926,7 @@ class LaTeXTranslator(SphinxTranslator):
if isinstance(c, addnodes.start_of_file): if isinstance(c, addnodes.start_of_file):
continue continue
elif isinstance(c, nodes.Element): elif isinstance(c, nodes.Element):
for k in footnotes_under(c): yield from footnotes_under(c)
yield k
fnotes = {} # type: Dict[unicode, List[Union[collected_footnote, bool]]] fnotes = {} # type: Dict[unicode, List[Union[collected_footnote, bool]]]
for fn in footnotes_under(node): for fn in footnotes_under(node):

View File

@ -535,8 +535,7 @@ class TexinfoTranslator(SphinxTranslator):
if isinstance(c, addnodes.start_of_file): if isinstance(c, addnodes.start_of_file):
continue continue
elif isinstance(c, nodes.Element): elif isinstance(c, nodes.Element):
for k in footnotes_under(c): yield from footnotes_under(c)
yield k
fnotes = {} # type: Dict[unicode, List[Union[collected_footnote, bool]]] fnotes = {} # type: Dict[unicode, List[Union[collected_footnote, bool]]]
for fn in footnotes_under(node): for fn in footnotes_under(node):
label = cast(nodes.label, fn[0]) label = cast(nodes.label, fn[0])

View File

@ -273,7 +273,6 @@ class TextWrapper(textwrap.TextWrapper):
The original _wrap_chunks uses len() to calculate width. The original _wrap_chunks uses len() to calculate width.
This method respects wide/fullwidth characters for width adjustment. This method respects wide/fullwidth characters for width adjustment.
""" """
drop_whitespace = getattr(self, 'drop_whitespace', True) # py25 compat
lines = [] # type: List[unicode] lines = [] # type: List[unicode]
if self.width <= 0: if self.width <= 0:
raise ValueError("invalid width %r (must be > 0)" % self.width) raise ValueError("invalid width %r (must be > 0)" % self.width)
@ -291,7 +290,7 @@ class TextWrapper(textwrap.TextWrapper):
width = self.width - column_width(indent) width = self.width - column_width(indent)
if drop_whitespace and chunks[-1].strip() == '' and lines: if self.drop_whitespace and chunks[-1].strip() == '' and lines:
del chunks[-1] del chunks[-1]
while chunks: while chunks:
@ -307,7 +306,7 @@ class TextWrapper(textwrap.TextWrapper):
if chunks and column_width(chunks[-1]) > width: if chunks and column_width(chunks[-1]) > width:
self._handle_long_word(chunks, cur_line, cur_len, width) self._handle_long_word(chunks, cur_line, cur_len, width)
if drop_whitespace and cur_line and cur_line[-1].strip() == '': if self.drop_whitespace and cur_line and cur_line[-1].strip() == '':
del cur_line[-1] del cur_line[-1]
if cur_line: if cur_line:

View File

@ -1028,16 +1028,13 @@ def test_autodoc_member_order(app):
@pytest.mark.sphinx('html', testroot='ext-autodoc') @pytest.mark.sphinx('html', testroot='ext-autodoc')
def test_autodoc_module_scope(app): def test_autodoc_module_scope(app):
def convert(s):
return re.sub('<.*>', '<FILTERED>', s) # for py2/py3
app.env.temp_data['autodoc:module'] = 'target' app.env.temp_data['autodoc:module'] = 'target'
actual = do_autodoc(app, 'attribute', 'Class.mdocattr') actual = do_autodoc(app, 'attribute', 'Class.mdocattr')
assert list(map(convert, actual)) == [ assert list(actual) == [
u'', u'',
u'.. py:attribute:: Class.mdocattr', u'.. py:attribute:: Class.mdocattr',
u' :module: target', u' :module: target',
u' :annotation: = <FILTERED>', u' :annotation: = <_io.StringIO object>',
u'', u'',
u' should be documented as well - süß', u' should be documented as well - süß',
u' ' u' '
@ -1046,17 +1043,14 @@ def test_autodoc_module_scope(app):
@pytest.mark.sphinx('html', testroot='ext-autodoc') @pytest.mark.sphinx('html', testroot='ext-autodoc')
def test_autodoc_class_scope(app): def test_autodoc_class_scope(app):
def convert(s):
return re.sub('<.*>', '<FILTERED>', s) # for py2/py3
app.env.temp_data['autodoc:module'] = 'target' app.env.temp_data['autodoc:module'] = 'target'
app.env.temp_data['autodoc:class'] = 'Class' app.env.temp_data['autodoc:class'] = 'Class'
actual = do_autodoc(app, 'attribute', 'mdocattr') actual = do_autodoc(app, 'attribute', 'mdocattr')
assert list(map(convert, actual)) == [ assert list(actual) == [
u'', u'',
u'.. py:attribute:: Class.mdocattr', u'.. py:attribute:: Class.mdocattr',
u' :module: target', u' :module: target',
u' :annotation: = <FILTERED>', u' :annotation: = <_io.StringIO object>',
u'', u'',
u' should be documented as well - süß', u' should be documented as well - süß',
u' ' u' '