Repository: asottile/pyupgrade

Issue:
Replace open(file, "rU") with open(file)?
"U" (universal newlines) `mode` was deprecated in Python 3.4 and the `newline=None` argument handles it instead. The default mode is `"r"` anyway

Comments:

Patch:
diff --git a/README.md b/README.md
index 8461601..96b0026 100644
--- a/README.md
+++ b/README.md
@@ -379,6 +379,7 @@ Availability:
 '{foo} {bar}'.format(foo=foo, bar=bar)  # f'{foo} {bar}'
 '{} {}'.format(foo, bar)                # f'{foo} {bar}'
 '{} {}'.format(foo.bar, baz.womp)       # f'{foo.bar} {baz.womp}'
+'{} {}'.format(f(), g())                # f'{f()} {g()}'
 ```
 
 _note_: `pyupgrade` is intentionally timid and will not create an f-string
diff --git a/pyupgrade.py b/pyupgrade.py
index 8e1fb1c..b49b72d 100644
--- a/pyupgrade.py
+++ b/pyupgrade.py
@@ -1225,6 +1225,7 @@ class FindPy3Plus(ast.NodeVisitor):
             set,
         )  # type: Dict[str, Set[str]]
         self.io_open_calls = set()  # type: Set[Offset]
+        self.open_mode_calls = set()  # type: Set[Offset]
         self.os_error_alias_calls = set()  # type: Set[Offset]
         self.os_error_alias_simple = {}  # type: Dict[Offset, NameOrAttr]
         self.os_error_alias_excepts = set()  # type: Set[Offset]
@@ -1500,6 +1501,15 @@ class FindPy3Plus(ast.NodeVisitor):
             self.encode_calls[_ast_to_offset(node)] = node
         elif self._is_io_open(node.func):
             self.io_open_calls.add(_ast_to_offset(node))
+        elif (
+                isinstance(node.func, ast.Name) and
+                node.func.id == 'open' and
+                len(node.args) >= 2 and
+                not _starargs(node) and
+                isinstance(node.args[1], ast.Str) and
+                node.args[1].s in {'Ur', 'rU', 'Ub', 'bU', 'r', 'rt', 'tr'}
+        ):
+            self.open_mode_calls.add(_ast_to_offset(node))
 
         self.generic_visit(node)
 
@@ -1882,6 +1892,7 @@ def _fix_py3_plus(contents_text):  # type: (str) -> str
             visitor.if_py3_blocks_else,
             visitor.native_literals,
             visitor.io_open_calls,
+            visitor.open_mode_calls,
             visitor.os_error_alias_calls,
             visitor.os_error_alias_simple,
             visitor.os_error_alias_excepts,
@@ -2061,6 +2072,18 @@ def _fix_py3_plus(contents_text):  # type: (str) -> str
         elif token.offset in visitor.io_open_calls:
             j = _find_open_paren(tokens, i)
             tokens[i:j] = [token._replace(name='NAME', src='open')]
+        elif token.offset in visitor.open_mode_calls:
+            j = _find_open_paren(tokens, i)
+            func_args, end = _parse_call_args(tokens, j)
+            mode = tokens_to_src(tokens[slice(*func_args[1])])
+            mode_stripped = mode.strip().strip('"\'')
+            if mode_stripped in {'Ur', 'rU', 'r', 'rt'}:
+                del tokens[func_args[0][1]:func_args[1][1]]
+            elif mode_stripped in {'Ub', 'bU'}:
+                new_mode = mode.replace('U', 'r')
+                tokens[slice(*func_args[1])] = [Token('SRC', new_mode)]
+            else:
+                raise AssertionError('unreachable: {!r}'.format(mode))
         elif token.offset in visitor.os_error_alias_calls:
             j = _find_open_paren(tokens, i)
             tokens[i:j] = [token._replace(name='NAME', src='OSError')]
@@ -2131,7 +2154,14 @@ def _fix_py3_plus(contents_text):  # type: (str) -> str
 def _simple_arg(arg):  # type: (ast.expr) -> bool
     return (
         isinstance(arg, ast.Name) or
-        (isinstance(arg, ast.Attribute) and _simple_arg(arg.value))
+        (isinstance(arg, ast.Attribute) and _simple_arg(arg.value)) or
+        (
+            isinstance(arg, ast.Call) and
+            _simple_arg(arg.func) and
+            not arg.args and not arg.keywords and
+            # only needed for py2
+            not _starargs(arg)
+        )
     )
 
 
@@ -2217,6 +2247,8 @@ def _unparse(node):  # type: (ast.expr) -> str
         return node.id
     elif isinstance(node, ast.Attribute):
         return ''.join((_unparse(node.value), '.', node.attr))
+    elif isinstance(node, ast.Call):
+        return '{}()'.format(_unparse(node.func))
     else:
         raise NotImplementedError(ast.dump(node))
 


Test patch:
diff --git a/tests/fstrings_test.py b/tests/fstrings_test.py
index 66f90ae..63b3614 100644
--- a/tests/fstrings_test.py
+++ b/tests/fstrings_test.py
@@ -46,6 +46,9 @@ def test_fix_fstrings_noop(s):
         ('"{x.y}".format(x=z)', 'f"{z.y}"'),
         ('"{.x} {.y}".format(a, b)', 'f"{a.x} {b.y}"'),
         ('"{} {}".format(a.b, c.d)', 'f"{a.b} {c.d}"'),
+        ('"{}".format(a())', 'f"{a()}"'),
+        ('"{}".format(a.b())', 'f"{a.b()}"'),
+        ('"{}".format(a.b().c())', 'f"{a.b().c()}"'),
         ('"hello {}!".format(name)', 'f"hello {name}!"'),
         ('"{}{{}}{}".format(escaped, y)', 'f"{escaped}{{}}{y}"'),
         ('"{}{b}{}".format(a, c, b=b)', 'f"{a}{b}{c}"'),
diff --git a/tests/open_mode_test.py b/tests/open_mode_test.py
new file mode 100644
index 0000000..dd6f939
--- /dev/null
+++ b/tests/open_mode_test.py
@@ -0,0 +1,37 @@
+# -*- coding: utf-8 -*-
+from __future__ import absolute_import
+from __future__ import unicode_literals
+
+import pytest
+
+from pyupgrade import _fix_py3_plus
+
+
+@pytest.mark.parametrize(
+    's',
+    (
+        # already a reduced mode
+        'open("foo", "w")',
+        'open("foo", "rb")',
+        # nonsense mode
+        'open("foo", "Uw")',
+        # TODO: could maybe be rewritten to remove t?
+        'open("foo", "wt")',
+    ),
+)
+def test_fix_open_mode_noop(s):
+    assert _fix_py3_plus(s) == s
+
+
+@pytest.mark.parametrize(
+    ('s', 'expected'),
+    (
+        ('open("foo", "Ur")', 'open("foo")'),
+        ('open("foo", "Ub")', 'open("foo", "rb")'),
+        ('open("foo", "r")', 'open("foo")'),
+        ('open("foo", "rt")', 'open("foo")'),
+        ('open("f", "r", encoding="UTF-8")', 'open("f", encoding="UTF-8")'),
+    ),
+)
+def test_fix_open_mode(s, expected):
+    assert _fix_py3_plus(s) == expected