Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 23 additions & 5 deletions autopep8.py
Original file line number Diff line number Diff line change
Expand Up @@ -1300,6 +1300,7 @@ def fix_e721(self, result):
# NOTE: match objects
# * type(a) == type(b) -> (None, None, 'a', '==')
# * str == type(b) -> ('==', 'b', None, None)
# * type(b) == str -> (None, None, 'b', '==')
# * type("") != type(b) -> (None, None, '""', '!=')
start = match.start()
end = match.end()
Expand All @@ -1320,6 +1321,10 @@ def fix_e721(self, result):
isinstance_stmt = " not isinstance"

_type_comp = f"{_target_obj}, {target[:start]}"
indent_match = re.match(r'^\s+', target)
indent = ""
if indent_match:
indent = indent_match.group()

_prefix_tmp = target[:start].split()
if len(_prefix_tmp) >= 1:
Expand All @@ -1332,15 +1337,28 @@ def fix_e721(self, result):

_suffix_tmp = target[end:]
_suffix_type_match = TYPE_REGEX.search(_suffix_tmp)
if len(_suffix_tmp.split()) >= 1 and _suffix_type_match:
if _suffix_type_match:
if _suffix_type_match:
if len(_suffix_tmp.split()) >= 1:
type_match_end = _suffix_type_match.end()
_suffix = _suffix_tmp[type_match_end:]
if _suffix_type_match:
cmp_b = _suffix_type_match.groups()[0]
_type_comp = f"{_target_obj}, {cmp_b}"

fix_line = f"{_prefix}{isinstance_stmt}({_type_comp}){_suffix}"
else:
_else_suffix_match = re.match(
r"^\s*([^\s:]+)(.*)$",
_suffix_tmp,
)
if _else_suffix_match:
_else_suffix = _else_suffix_match.group(1)
_else_suffix_other = _else_suffix_match.group(2)
_type_comp = f"{_target_obj}, {_else_suffix}"
_else_suffix_end = _suffix_tmp[_else_suffix_match.end():]
_suffix = f"{_else_suffix_other}{_else_suffix_end}"
# `else` route is not care

fix_line = (
f"{indent}{_prefix}{isinstance_stmt}({_type_comp}){_suffix}"
)
self.source[line_index] = fix_line

def fix_e722(self, result):
Expand Down
12 changes: 12 additions & 0 deletions test/test_autopep8.py
Original file line number Diff line number Diff line change
Expand Up @@ -4419,6 +4419,18 @@ def test_e721_in_conditional_pat2(self):
with autopep8_context(line, options=['--aggressive']) as result:
self.assertEqual(fixed, result)

def test_e721_in_conditional_pat3(self):
line = "if type(res) == str:\n pass\n"
fixed = "if isinstance(res, str):\n pass\n"
with autopep8_context(line, options=['--aggressive']) as result:
self.assertEqual(fixed, result)

def test_e721_in_conditional_with_indent(self):
line = "if True:\n if str == type(''):\n pass\n"
fixed = "if True:\n if isinstance('', str):\n pass\n"
with autopep8_context(line, options=['--aggressive']) as result:
self.assertEqual(fixed, result)

def test_e721_in_not_conditional(self):
line = "if type(res) != type(''):\n pass\n"
fixed = "if not isinstance(res, type('')):\n pass\n"
Expand Down
Loading