instance_id
stringlengths
10
57
patch
stringlengths
261
37.7k
repo
stringlengths
7
53
base_commit
stringlengths
40
40
hints_text
stringclasses
301 values
test_patch
stringlengths
212
2.22M
problem_statement
stringlengths
23
37.7k
version
stringclasses
1 value
environment_setup_commit
stringlengths
40
40
FAIL_TO_PASS
listlengths
1
4.94k
PASS_TO_PASS
listlengths
0
7.82k
meta
dict
created_at
stringlengths
25
25
license
stringclasses
8 values
__index_level_0__
int64
0
6.41k
asottile__babi-187
diff --git a/babi/highlight.py b/babi/highlight.py index cbd2f75..284ac53 100644 --- a/babi/highlight.py +++ b/babi/highlight.py @@ -10,6 +10,7 @@ from typing import Tuple from typing import TypeVar from identify.identify import tags_from_filename +from identify.identify import tags_from_path from babi._types import Protocol from babi.fdict import FChainMap @@ -721,7 +722,11 @@ class Grammars: return self.compiler_for_scope('source.unknown') def compiler_for_file(self, filename: str, first_line: str) -> Compiler: - for tag in tags_from_filename(filename) - {'text'}: + try: + tags = tags_from_path(filename) + except ValueError: + tags = tags_from_filename(filename) + for tag in tags - {'text'}: try: # TODO: this doesn't always match even if we detect it return self.compiler_for_scope(f'source.{tag}')
asottile/babi
e137233f4d79614f5b9d2cd5f6021a19a02fdde8
diff --git a/tests/highlight_test.py b/tests/highlight_test.py index db8d2b7..3a72e5a 100644 --- a/tests/highlight_test.py +++ b/tests/highlight_test.py @@ -1,5 +1,7 @@ from __future__ import annotations +import stat + import pytest from babi.highlight import highlight_line @@ -13,6 +15,17 @@ def test_grammar_matches_extension_only_name(make_grammars): assert compiler.root_state.entries[0].scope[0] == 'shell' +def test_file_without_extension(tmpdir, make_grammars): + f = tmpdir.join('f') + f.write('#!/usr/bin/env python3') + f.chmod(stat.S_IRWXU) + + data = {'scopeName': 'source.python', 'patterns': []} + grammars = make_grammars(data) + compiler = grammars.compiler_for_file(str(f), f.read()) + assert compiler.root_state.entries[0].scope[0] == 'source.python' + + def test_grammar_matches_via_identify_tag(make_grammars): grammars = make_grammars({'scopeName': 'source.ini', 'patterns': []}) compiler = grammars.compiler_for_file('setup.cfg', '')
utilize identify's shebang detection for grammar when possible an example: ```python #!/usr/bin/env python3 print('hello') ``` this file saved as `foo/install` gets highlighted incorrectly as shell, but we can utilize `tags_from_path` to identify this as `python` earlier on
0.0
e137233f4d79614f5b9d2cd5f6021a19a02fdde8
[ "tests/highlight_test.py::test_file_without_extension" ]
[ "tests/highlight_test.py::test_grammar_matches_extension_only_name", "tests/highlight_test.py::test_grammar_matches_via_identify_tag", "tests/highlight_test.py::test_backslash_a", "tests/highlight_test.py::test_backslash_g_inline", "tests/highlight_test.py::test_backslash_g_next_line", "tests/highlight_test.py::test_end_before_other_match", "tests/highlight_test.py::test_backslash_g_captures_nl", "tests/highlight_test.py::test_backslash_g_captures_nl_next_line", "tests/highlight_test.py::test_while_no_nl", "tests/highlight_test.py::test_complex_captures", "tests/highlight_test.py::test_captures_multiple_applied_to_same_capture", "tests/highlight_test.py::test_captures_ignores_empty", "tests/highlight_test.py::test_captures_ignores_invalid_out_of_bounds", "tests/highlight_test.py::test_captures_begin_end", "tests/highlight_test.py::test_captures_while_captures", "tests/highlight_test.py::test_captures_implies_begin_end_captures", "tests/highlight_test.py::test_captures_implies_begin_while_captures", "tests/highlight_test.py::test_include_self", "tests/highlight_test.py::test_include_repository_rule", "tests/highlight_test.py::test_include_with_nested_repositories", "tests/highlight_test.py::test_include_other_grammar", "tests/highlight_test.py::test_include_base", "tests/highlight_test.py::test_rule_with_begin_and_no_end", "tests/highlight_test.py::test_begin_end_substitute_special_chars", "tests/highlight_test.py::test_backslash_z", "tests/highlight_test.py::test_buggy_begin_end_grammar" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2022-01-29 18:36:54+00:00
mit
1,120
asottile__babi-328
diff --git a/babi/linters/pre_commit.py b/babi/linters/pre_commit.py index d5ffc5c..380608b 100644 --- a/babi/linters/pre_commit.py +++ b/babi/linters/pre_commit.py @@ -63,10 +63,16 @@ class PreCommit: return None # not in a git repo! # no pre-commit config! - if not os.path.exists(os.path.join(root, '.pre-commit-config.yaml')): + cfg = os.path.join(root, '.pre-commit-config.yaml') + if not os.path.exists(cfg): return None - return ('pre-commit', 'run', '--color=never', '--files', filename) + return ( + 'pre-commit', 'run', + '--color=never', + '--config', cfg, + '--files', filename, + ) def parse(self, filename: str, output: str) -> tuple[linting.Error, ...]: root = self._root(filename)
asottile/babi
4d4b0ef970286374a33d886b0695ed6c92409325
diff --git a/tests/linters/pre_commit_test.py b/tests/linters/pre_commit_test.py index 6fdf20a..7fa7781 100644 --- a/tests/linters/pre_commit_test.py +++ b/tests/linters/pre_commit_test.py @@ -96,10 +96,16 @@ def test_command_returns_none_no_pre_commit_config(tmpdir_git): def test_command_returns_when_config_exists(tmpdir_git): - tmpdir_git.join('.pre-commit-config.yaml').write('{}\n') + cfg = tmpdir_git.join('.pre-commit-config.yaml') + cfg.write('{}\n') path = str(tmpdir_git.join('t.py')) ret = PreCommit().command(path, 'source.python') - assert ret == ('pre-commit', 'run', '--color=never', '--files', path) + assert ret == ( + 'pre-commit', 'run', + '--color=never', + '--config', str(cfg), + '--files', path, + ) def test_filters_file_paths_to_actual_file(tmpdir_git):
pre-commit runs with the wrong configuration when accessing a file in a different repository went through all the trouble to check the right config exists here: https://github.com/asottile/babi/blob/5cf5f2501c90274e7f640ff0ad4dfb355631b960/babi/linters/pre_commit.py#L66 but then didn't bother actually using it here: https://github.com/asottile/babi/blob/5cf5f2501c90274e7f640ff0ad4dfb355631b960/babi/linters/pre_commit.py#L69
0.0
4d4b0ef970286374a33d886b0695ed6c92409325
[ "tests/linters/pre_commit_test.py::test_command_returns_when_config_exists" ]
[ "tests/linters/pre_commit_test.py::test_parse_pre_commit_noop", "tests/linters/pre_commit_test.py::test_parse_pre_commit_output", "tests/linters/pre_commit_test.py::test_command_returns_none_not_in_git_dir", "tests/linters/pre_commit_test.py::test_command_returns_none_abspath_to_file", "tests/linters/pre_commit_test.py::test_command_returns_none_no_pre_commit_config", "tests/linters/pre_commit_test.py::test_filters_file_paths_to_actual_file", "tests/linters/pre_commit_test.py::test_matches_files_with_absolute_paths", "tests/linters/pre_commit_test.py::test_normalizes_paths_to_repo_root" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2023-10-30 23:55:26+00:00
mit
1,121
asottile__covdefaults-57
diff --git a/README.md b/README.md index 281cd5a..4b25ec2 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,13 @@ exclude_lines = if __name__ == ['"]__main__['"]:$ # additional platform related pragmas (see below) + # additional version related pragmas (see below) +partial_branches = + # a more strict default pragma + \# pragma: no cover\b + + # our version pragmas + \# pragma: (>=?|<=?|==|!=)\d+\.\d+ cover\b' ``` ### platform specific `# pragma: no cover` @@ -123,6 +130,28 @@ note here that `# pragma: win32 cover` will become a "no cover" for everything which is not `win32` -- whereas the `# pragma: win32 no cover` will be a "no cover" only on `win32`. +### version specific `# pragma: no cover` + +several `# pragma: no cover` tags will be added automatically based on the +platform and implementation. + +these will be in the form of: + +```python +# pragma: >=#.# cover +``` + +where the comparison operator is one of `>`, `>=`, `<`, `<=`, `==`, `!=` + +for example: + +```python +if sys.version_info >= (3, 9): # pragma: >=3.9 cover + print('3.9+') +else: # pragma: <3.9 cover + print('old') +``` + ### overriding options several of the options can be overridden / extended in your coverage diff --git a/covdefaults.py b/covdefaults.py index 981a9eb..cd863c5 100644 --- a/covdefaults.py +++ b/covdefaults.py @@ -27,6 +27,54 @@ def _plat_impl_pragmas() -> List[str]: return ret +def _lt(n: int) -> str: + n_s = str(n) + digit = r'\d' + + parts = [ + f'{n_s[:i]}[0-{int(n_s[i]) - 1}]{len(n_s[i + 1:]) * digit}' + for i in range(len(n_s)) + if n_s[i] != '0' + ] + if len(n_s) > 1: + parts.append(f'{digit}{{1,{len(n_s) - 1}}}') + + return f'({"|".join(parts)})' + + +def _gt(n: int) -> str: + n_s = str(n) + digit = r'\d' + + parts = [ + f'{n_s[:i]}[{int(n_s[i]) + 1}-9]{len(n_s[i + 1:]) * digit}' + for i in range(len(n_s)) + if n_s[i] != '9' + ] + parts.append(f'{digit}{{{len(n_s) + 1},}}') + + return f'({"|".join(parts)})' + + +def _version_pragmas( + major: int = sys.version_info[0], + minor: int = sys.version_info[1], +) -> List[str]: + return [ + # < + fr'# pragma: <=?{_lt(major)}\.\d+ cover\b', + fr'# pragma: <=?{major}\.{_lt(minor)} cover\b', + fr'# pragma: <{major}\.{minor} cover\b', + # > + fr'# pragma: >=?{_gt(major)}\.\d+ cover\b', + fr'# pragma: >=?{major}\.{_gt(minor)} cover\b', + fr'# pragma: >{major}\.{minor} cover\b', + # != / == + fr'# pragma: !={major}\.{minor} cover\b', + fr'# pragma: ==(?!{major}\.{minor})\d+\.\d+ cover\b', + ] + + OPTIONS: Tuple[Tuple[str, Any], ...] = ( ('run:branch', True), @@ -53,6 +101,15 @@ EXTEND = ( # non-runnable code r'^if __name__ == [\'"]__main__[\'"]:$', *_plat_impl_pragmas(), + *_version_pragmas(), + ], + ), + ( + 'report:partial_branches', + [ + r'# pragma: no branch\b', + # version specific no cover + r'# pragma: (>=?|<=?|==|!=)\d+\.\d+ cover\b', ], ), )
asottile/covdefaults
b33cb96b0b06669148e156af0a4c0c343a97b859
diff --git a/tests/covdefaults_test.py b/tests/covdefaults_test.py index 05388c1..20fbb44 100644 --- a/tests/covdefaults_test.py +++ b/tests/covdefaults_test.py @@ -24,6 +24,89 @@ def test_plat_impl_pragmas(): assert (c, pragma, no, cover) == ('#', 'pragma:', 'no', r'cover\b'), s +def _matches_version_pragma(major, minor, s): + regexes = covdefaults._version_pragmas(major, minor) + return any(re.match(reg, s) for reg in regexes) + + [email protected]( + ('s', 'expected'), + ( + # < + ('# pragma: <2.7 cover', True), + ('# pragma: <3.6 cover', True), + ('# pragma: <3.7 cover', True), + ('# pragma: <3.8 cover', False), + ('# pragma: <3.10 cover', False), + # <= + ('# pragma: <=2.7 cover', True), + ('# pragma: <=3.6 cover', True), + ('# pragma: <=3.7 cover', False), + ('# pragma: <=3.8 cover', False), + ('# pragma: <=3.10 cover', False), + # > + ('# pragma: >2.7 cover', False), + ('# pragma: >3.6 cover', False), + ('# pragma: >3.7 cover', True), + ('# pragma: >3.8 cover', True), + ('# pragma: >3.10 cover', True), + # >= + ('# pragma: >=2.7 cover', False), + ('# pragma: >=3.6 cover', False), + ('# pragma: >=3.7 cover', False), + ('# pragma: >=3.8 cover', True), + ('# pragma: >=3.10 cover', True), + # == + ('# pragma: ==3.6 cover', True), + ('# pragma: ==3.7 cover', False), + ('# pragma: ==3.8 cover', True), + # != + ('# pragma: !=3.6 cover', False), + ('# pragma: !=3.7 cover', True), + ('# pragma: !=3.8 cover', False), + ), +) +def test_version_pragmas_py37(s, expected): + assert _matches_version_pragma(3, 7, s) == expected + + [email protected]( + ('s', 'expected'), + ( + # < + ('# pragma: <2.7 cover', True), + ('# pragma: <3.9 cover', True), + ('# pragma: <3.10 cover', True), + ('# pragma: <3.11 cover', False), + # <= + ('# pragma: <=2.7 cover', True), + ('# pragma: <=3.9 cover', True), + ('# pragma: <=3.10 cover', False), + ('# pragma: <=3.11 cover', False), + # > + ('# pragma: >2.7 cover', False), + ('# pragma: >3.9 cover', False), + ('# pragma: >3.10 cover', True), + ('# pragma: >3.11 cover', True), + # >= + ('# pragma: >=2.7 cover', False), + ('# pragma: >=3.9 cover', False), + ('# pragma: >=3.10 cover', False), + ('# pragma: >=3.11 cover', True), + # == + ('# pragma: ==3.9 cover', True), + ('# pragma: ==3.10 cover', False), + ('# pragma: ==3.11 cover', True), + # != + ('# pragma: !=3.9 cover', False), + ('# pragma: !=3.10 cover', True), + ('# pragma: !=3.11 cover', False), + ), +) +def test_version_pragmas_py310(s, expected): + assert _matches_version_pragma(3, 10, s) == expected + + @pytest.fixture def configured(): cfg = CoverageConfig() @@ -102,6 +185,26 @@ def test_excludes_lines(configured, src): raise AssertionError(f'no regex matched {src!r}') [email protected]( + 'src', + ( + 'if True: # pragma: no branch\n', + 'if sys.version_info >= (3, 9): # pragma: >=3.9 cover\n', + 'if sys.version_info > (3, 9): # pragma: >3.9 cover\n', + 'if sys.version_info <= (3, 9): # pragma: <=3.9 cover\n', + 'if sys.version_info < (3, 9): # pragma: <3.9 cover\n', + 'if sys.version_info == (3, 9): # pragma: ==3.9 cover\n', + 'if sys.version_info != (3, 9): # pragma: !=3.9 cover\n', + ), +) +def test_partial_branches(configured, src): + for reg in configured.get_option('report:partial_branches'): + if any(re.search(reg, line) for line in src.splitlines()): + break + else: + raise AssertionError(f'no regex matched {src!r}') + + def test_extends_existing_exclude_lines(): cfg = CoverageConfig() cfg.set_option('report:exclude_lines', ['^if MYPY:$'])
version specific coverage pragmas might be a fun little regex game, but it would be nice to support `# pragma: >=3.7 no cover` or some such
0.0
b33cb96b0b06669148e156af0a4c0c343a97b859
[ "tests/covdefaults_test.py::test_version_pragmas_py37[#", "tests/covdefaults_test.py::test_version_pragmas_py310[#", "tests/covdefaults_test.py::test_partial_branches[if" ]
[ "tests/covdefaults_test.py::test_plat_impl_pragmas", "tests/covdefaults_test.py::test_constant_options", "tests/covdefaults_test.py::test_source_already_set", "tests/covdefaults_test.py::test_extends_existing_omit", "tests/covdefaults_test.py::test_subtract_omit", "tests/covdefaults_test.py::test_exclude_lines_does_not_include_defaults", "tests/covdefaults_test.py::test_excludes_lines[if", "tests/covdefaults_test.py::test_excludes_lines[raise", "tests/covdefaults_test.py::test_excludes_lines[", "tests/covdefaults_test.py::test_excludes_lines[def", "tests/covdefaults_test.py::test_extends_existing_exclude_lines", "tests/covdefaults_test.py::test_configure_keeps_existing_fail_under", "tests/covdefaults_test.py::test_coverage_init", "tests/covdefaults_test.py::test_fix_coverage" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-11-28 04:46:08+00:00
mit
1,122
asottile__covdefaults-97
diff --git a/README.md b/README.md index 08a0078..2761af0 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ exclude_lines = ^\s*raise$ # typing-related code - ^if (False|TYPE_CHECKING): + ^\s*if (False|TYPE_CHECKING): : \.\.\.(\s*#.*)?$ ^ +\.\.\.$ -> ['"]?NoReturn['"]?: diff --git a/covdefaults.py b/covdefaults.py index 55a5120..09b40a9 100644 --- a/covdefaults.py +++ b/covdefaults.py @@ -93,7 +93,7 @@ EXTEND = ( r'^\s*return NotImplemented\b', r'^\s*raise$', # typing-related code - r'^if (False|TYPE_CHECKING):', + r'^\s*if (False|TYPE_CHECKING):', r': \.\.\.(\s*#.*)?$', r'^ +\.\.\.$', r'-> [\'"]?NoReturn[\'"]?:',
asottile/covdefaults
9d6e5c5c20108daa74b72783ced5452fa84678da
diff --git a/tests/covdefaults_test.py b/tests/covdefaults_test.py index 7d124ba..bc3f1bc 100644 --- a/tests/covdefaults_test.py +++ b/tests/covdefaults_test.py @@ -167,7 +167,9 @@ def test_exclude_lines_does_not_include_defaults(configured): ' return NotImplemented\n', ' raise\n', 'if False:\n', + ' if False:\n', 'if TYPE_CHECKING:\n', + ' if TYPE_CHECKING:\n', 'def f(x: int) -> int: ...\n', 'def f(x: int) -> int:\n ...\n', 'def f(x: int) -> C: ...# noqa: F821\n',
Class-level `if TYPE_CHECKING` is reported as uncovered Example: ```python from typing import TYPE_CHECKING class Some: if TYPE_CHECKING: some_attr: str ``` Here `if TYPE_CHECKING:` is reported to be uncovered. <img width="679" alt="Снимок экрана 2022-12-03 в 14 21 00" src="https://user-images.githubusercontent.com/4660275/205438416-b995b5a3-a8a1-4553-ba20-b4246650c26b.png"> While, other rules have `\s*` prefix. I have a PR ready.
0.0
9d6e5c5c20108daa74b72783ced5452fa84678da
[ "tests/covdefaults_test.py::test_excludes_lines[" ]
[ "tests/covdefaults_test.py::test_plat_impl_pragmas", "tests/covdefaults_test.py::test_version_pragmas_py37[#", "tests/covdefaults_test.py::test_version_pragmas_py310[#", "tests/covdefaults_test.py::test_constant_options", "tests/covdefaults_test.py::test_source_already_set", "tests/covdefaults_test.py::test_extends_existing_omit", "tests/covdefaults_test.py::test_subtract_omit", "tests/covdefaults_test.py::test_exclude_lines_does_not_include_defaults", "tests/covdefaults_test.py::test_excludes_lines[if", "tests/covdefaults_test.py::test_excludes_lines[raise", "tests/covdefaults_test.py::test_excludes_lines[def", "tests/covdefaults_test.py::test_partial_branches[if", "tests/covdefaults_test.py::test_extends_existing_exclude_lines", "tests/covdefaults_test.py::test_configure_keeps_existing_fail_under", "tests/covdefaults_test.py::test_coverage_init", "tests/covdefaults_test.py::test_fix_coverage" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_media", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-12-03 11:28:41+00:00
mit
1,123
asottile__dead-24
diff --git a/dead.py b/dead.py index 7879cc5..019ee8e 100644 --- a/dead.py +++ b/dead.py @@ -8,6 +8,7 @@ import subprocess import tokenize from typing import DefaultDict from typing import Generator +from typing import List from typing import NewType from typing import Optional from typing import Pattern @@ -28,13 +29,19 @@ TYPE_FUNC_RE = re.compile(r'^(\(.*?\))\s*->\s*(.*)$') DISABLE_COMMENT_RE = re.compile(r'\bdead\s*:\s*disable') -class Visitor(ast.NodeVisitor): +class Scope: def __init__(self) -> None: - self.filename = '' - self.is_test = False self.reads: UsageMap = collections.defaultdict(set) self.defines: UsageMap = collections.defaultdict(set) self.reads_tests: UsageMap = collections.defaultdict(set) + + +class Visitor(ast.NodeVisitor): + def __init__(self) -> None: + self.filename = '' + self.is_test = False + self.previous_scopes: List[Scope] = [] + self.scopes = [Scope()] self.disabled: Set[FileLine] = set() @contextlib.contextmanager @@ -52,9 +59,13 @@ class Visitor(ast.NodeVisitor): self.filename = orig_filename self.is_test = orig_is_test - @property - def reads_target(self) -> UsageMap: - return self.reads_tests if self.is_test else self.reads + @contextlib.contextmanager + def scope(self) -> Generator[None, None, None]: + self.scopes.append(Scope()) + try: + yield + finally: + self.previous_scopes.append(self.scopes.pop()) def _file_line(self, filename: str, line: int) -> FileLine: return FileLine(f'{filename}:{line}') @@ -62,31 +73,77 @@ class Visitor(ast.NodeVisitor): def definition_str(self, node: ast.AST) -> FileLine: return self._file_line(self.filename, node.lineno) + def define(self, name: str, node: ast.AST) -> None: + if not self.is_test: + self.scopes[-1].defines[name].add(self.definition_str(node)) + + def read(self, name: str, node: ast.AST) -> None: + for scope in self.scopes: + if self.is_test: + scope.reads_tests[name].add(self.definition_str(node)) + else: + scope.reads[name].add(self.definition_str(node)) + def visit_ImportFrom(self, node: ast.ImportFrom) -> None: for name in node.names: - self.reads_target[name.name].add(self.definition_str(node)) - if not self.is_test and name.asname: - self.defines[name.asname].add(self.definition_str(node)) + self.read(name.name, node) + if name.asname: + self.define(name.asname, node) self.generic_visit(node) def visit_ClassDef(self, node: ast.ClassDef) -> None: - if not self.is_test: - self.defines[node.name].add(self.definition_str(node)) + self.define(node.name, node) self.generic_visit(node) + def _is_stub_function(self, node: ast.FunctionDef) -> bool: + for stmt in node.body: + if ( + isinstance(stmt, ast.Expr) and + isinstance(stmt.value, (ast.Str, ast.Ellipsis)) + ): + continue # docstring or ... + elif isinstance(stmt, ast.Pass): + continue # pass + elif ( + isinstance(stmt, ast.Raise) and + stmt.cause is None and ( + ( + isinstance(stmt.exc, ast.Name) and + stmt.exc.id == 'NotImplementedError' + ) or ( + isinstance(stmt.exc, ast.Call) and + isinstance(stmt.exc.func, ast.Name) and + stmt.exc.func.id == 'NotImplementedError' + ) + ) + ): + continue # raise NotImplementedError + else: + return False + else: + return True + def visit_FunctionDef(self, node: ast.FunctionDef) -> None: - if not self.is_test: - self.defines[node.name].add(self.definition_str(node)) - self.generic_visit(node) + self.define(node.name, node) + with self.scope(): + if not self._is_stub_function(node): + for arg in ( + *node.args.args, + node.args.vararg, + *node.args.kwonlyargs, + node.args.kwarg, + ): + if arg is not None: + self.define(arg.arg, arg) + self.generic_visit(node) visit_AsyncFunctionDef = visit_FunctionDef def visit_Assign(self, node: ast.Assign) -> None: - if not self.is_test: - for target in node.targets: - if isinstance(target, ast.Name): - self.defines[target.id].add(self.definition_str(node)) + for target in node.targets: + if isinstance(target, ast.Name): + self.define(target.id, node) if ( len(node.targets) == 1 and @@ -96,7 +153,7 @@ class Visitor(ast.NodeVisitor): ): for elt in node.value.elts: if isinstance(elt, ast.Str): - self.reads_target[elt.s].add(self.definition_str(elt)) + self.read(elt.s, elt) self.generic_visit(node) @@ -104,13 +161,13 @@ class Visitor(ast.NodeVisitor): def visit_Name(self, node: ast.Name) -> None: if isinstance(node.ctx, ast.Load): - self.reads_target[node.id].add(self.definition_str(node)) + self.read(node.id, node) self.generic_visit(node) def visit_Attribute(self, node: ast.Attribute) -> None: if isinstance(node.ctx, ast.Load): - self.reads_target[node.attr].add(self.definition_str(node)) + self.read(node.attr, node) self.generic_visit(node) @@ -176,8 +233,7 @@ class ParsesEntryPoints(ast.NodeVisitor): def visit_Str(self, node: ast.Str) -> None: match = ENTRYPOINT_RE.match(node.s) if match: - location = self.visitor.definition_str(node) - self.visitor.reads[match.group(1)].add(location) + self.visitor.read(match.group(1), node) self.generic_visit(node) @@ -236,25 +292,29 @@ def main(argv: Optional[Sequence[str]] = None) -> int: retv = 0 + visitor.previous_scopes.append(visitor.scopes.pop()) unused_ignores = visitor.disabled.copy() - for k, v in visitor.defines.items(): - if k not in visitor.reads: - unused_ignores.difference_update(v) - v = v - visitor.disabled - - if k.startswith('__') and k.endswith('__'): - pass # skip magic methods, probably an interface - elif k not in visitor.reads and not v - visitor.disabled: - pass # all references disabled - elif k not in visitor.reads and k not in visitor.reads_tests: - print(f'{k} is never read, defined in {", ".join(sorted(v))}') - retv = 1 - elif k not in visitor.reads: - print( - f'{k} is only referenced in tests, ' - f'defined in {", ".join(sorted(v))}', - ) - retv = 1 + for scope in visitor.previous_scopes: + for k, v in scope.defines.items(): + if k not in scope.reads: + unused_ignores.difference_update(v) + v = v - visitor.disabled + + if k.startswith('__') and k.endswith('__'): + pass # skip magic methods, probably an interface + elif k in {'cls', 'self'}: + pass # ignore conventional cls / self + elif k not in scope.reads and not v: + pass # all references disabled + elif k not in scope.reads and k not in scope.reads_tests: + print(f'{k} is never read, defined in {", ".join(sorted(v))}') + retv = 1 + elif k not in scope.reads: + print( + f'{k} is only referenced in tests, ' + f'defined in {", ".join(sorted(v))}', + ) + retv = 1 if unused_ignores: for ignore in sorted(unused_ignores):
asottile/dead
f2c49508937f64f13cf650bfb11c29aba2d8aa36
diff --git a/tests/dead_test.py b/tests/dead_test.py index 9ee3a09..f8b63ba 100644 --- a/tests/dead_test.py +++ b/tests/dead_test.py @@ -140,3 +140,71 @@ def test_partially_disabled(git_dir, capsys): assert dead.main(()) out, _ = capsys.readouterr() assert out == 'x is never read, defined in f.py:1, f.py:3\n' + + +def test_unused_argument(git_dir, capsys): + git_dir.join('f.py').write('def f(a, *b, c, **d): return 1\nf') + subprocess.check_call(('git', 'add', '.')) + assert dead.main(()) + out, _ = capsys.readouterr() + assert out == ( + 'a is never read, defined in f.py:1\n' + 'b is never read, defined in f.py:1\n' + 'c is never read, defined in f.py:1\n' + 'd is never read, defined in f.py:1\n' + ) + + +def test_unused_argument_in_scope(git_dir, capsys): + git_dir.join('f.py').write('def f(g): return 1\ndef g(): pass\ng\nf\n') + subprocess.check_call(('git', 'add', '.')) + assert dead.main(()) + out, _ = capsys.readouterr() + assert out == 'g is never read, defined in f.py:1\n' + + +def test_using_an_argument(git_dir): + git_dir.join('f.py').write('def f(g): return g\nf') + subprocess.check_call(('git', 'add', '.')) + assert not dead.main(()) + + +def test_ignore_unused_arguments_stubs(git_dir): + git_dir.join('f.py').write( + 'import abc\n' + 'from typing import overload\n' + 'class C:\n' + ' @abc.abstractmethod\n' + ' def func(self, arg1):\n' + ' pass\n' + 'def func2(arg2):\n' + ' pass\n' + 'def func3(arg3):\n' + ' pass\n' + '@overload\n' + 'def func4(arg4):\n' + ' ...\n' + 'def func5(arg5):\n' + ' """docstring but trivial"""\n' + 'def func6(arg6):\n' + ' raise NotImplementedError\n' + 'def func7(arg7):\n' + ' raise NotImplementedError()\n' + 'def func8(arg8):\n' + ' """docstring plus raise"""\n' + ' raise NotImplementedError()\n' + 'C.func, func2, func3, func4, func5, func6, func7, func8\n', + ) + subprocess.check_call(('git', 'add', '.')) + assert not dead.main(()) + + +def test_ignored_arguments(git_dir): + git_dir.join('f.py').write( + 'class C:\n' + ' @classmethod\n' + ' def f(cls): return 1\n' # allow conventional `cls` method + 'C.f', + ) + subprocess.check_call(('git', 'add', '.')) + assert not dead.main(())
Detect unused arguments A related feature that could be useful would be to detect "dead arguments," or function arguments not used by the function body. Here is an example of a dead argument found in pip: https://github.com/pypa/pip/pull/7015
0.0
f2c49508937f64f13cf650bfb11c29aba2d8aa36
[ "tests/dead_test.py::test_unused_argument", "tests/dead_test.py::test_unused_argument_in_scope" ]
[ "tests/dead_test.py::test_dead_disable_regex_matching[#", "tests/dead_test.py::test_dead_disable_regex_matching[#dead:disable]", "tests/dead_test.py::test_dead_disable_regex_not_matching[#", "tests/dead_test.py::test_is_marked_as_used[x", "tests/dead_test.py::test_is_marked_as_used[def", "tests/dead_test.py::test_is_marked_as_used[async", "tests/dead_test.py::test_is_marked_as_used[class", "tests/dead_test.py::test_is_marked_as_used[from", "tests/dead_test.py::test_is_marked_as_used[import", "tests/dead_test.py::test_is_marked_as_used[MyStr", "tests/dead_test.py::test_setup_py_entrypoints_mark_as_used", "tests/dead_test.py::test_never_referenced", "tests/dead_test.py::test_assignment_not_counted_as_reference", "tests/dead_test.py::test_only_referenced_in_tests", "tests/dead_test.py::test_unused_dead_disable_comment", "tests/dead_test.py::test_partially_disabled", "tests/dead_test.py::test_using_an_argument", "tests/dead_test.py::test_ignore_unused_arguments_stubs", "tests/dead_test.py::test_ignored_arguments" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-09-14 10:29:02+00:00
mit
1,124
asottile__dead-31
diff --git a/dead.py b/dead.py index 969acac..03695bb 100644 --- a/dead.py +++ b/dead.py @@ -210,6 +210,7 @@ def _filenames( if ( not files_re.search(filename) or exclude_re.search(filename) or + not os.path.exists(filename) or 'python' not in tags_from_path(filename) ): continue
asottile/dead
8988defd1097006c49c73fad4a55425c5862b104
diff --git a/tests/dead_test.py b/tests/dead_test.py index 3dee231..15917bf 100644 --- a/tests/dead_test.py +++ b/tests/dead_test.py @@ -76,6 +76,14 @@ def test_is_marked_as_used(git_dir, capsys, s): assert not any(capsys.readouterr()) +def test_deleted_file_dont_raise_error(git_dir): + module = git_dir.join('test-module.py') + module.write('print(1)') + subprocess.check_call(('git', 'add', '.')) + module.remove() + assert not dead.main(()) + + def test_setup_py_entrypoints_mark_as_used(git_dir, capsys): git_dir.join('setup.py').write( 'from setuptools import setup\n'
dead raises ValueError in case a file is deleted (since it remains listed with "git ls-files") Hi, Just hit this twice in a week. I'm using `dead` to clean up a large codebase and realized that as soon as you delete a file, `dead` starts complaining that it can't find that same file in subsequent run ``` Traceback (most recent call last): File "/home/***/.pyenv/versions/3.6.5/envs/cmp/bin/dead", line 8, in <module> sys.exit(main()) File "/home/***/.pyenv/versions/3.6.5/envs/cmp/lib/python3.6/site-packages/dead.py", line 302, in main for filename, is_test in _filenames(files_re, exclude_re, tests_re): File "/home/***/.pyenv/versions/3.6.5/envs/cmp/lib/python3.6/site-packages/dead.py", line 213, in _filenames 'python' not in tags_from_path(filename) File "/home/***/.pyenv/versions/3.6.5/envs/cmp/lib/python3.6/site-packages/identify/identify.py", line 38, in tags_from_path raise ValueError('{} does not exist.'.format(path)) ValueError: myapp/lib/helpers.py does not exist. ``` I quickly check and the problem is that it relies on `git ls-files`, which lists also the deleted files. The workaround is to commit the change, then re-execute `dead` but I thought it is worth fixing this. I havn't seen an option in `git ls-files` to lists everything except the deleted file but I see that I can list the deleted files with `git ls-files --deleted` so I guess we can use that to subtract the deleted files. Let me know your thoughts and if that seems like a good approach, I'd be happy to implement it.
0.0
8988defd1097006c49c73fad4a55425c5862b104
[ "tests/dead_test.py::test_deleted_file_dont_raise_error" ]
[ "tests/dead_test.py::test_dead_disable_regex_matching[#", "tests/dead_test.py::test_dead_disable_regex_matching[#dead:disable]", "tests/dead_test.py::test_dead_disable_regex_not_matching[#", "tests/dead_test.py::test_is_marked_as_used[x", "tests/dead_test.py::test_is_marked_as_used[def", "tests/dead_test.py::test_is_marked_as_used[async", "tests/dead_test.py::test_is_marked_as_used[class", "tests/dead_test.py::test_is_marked_as_used[from", "tests/dead_test.py::test_is_marked_as_used[import", "tests/dead_test.py::test_is_marked_as_used[MyStr", "tests/dead_test.py::test_setup_py_entrypoints_mark_as_used", "tests/dead_test.py::test_setup_cfg_entry_points_marked_as_used", "tests/dead_test.py::test_setup_cfg_without_entry_points", "tests/dead_test.py::test_setup_cfg_without_attribute_entry_point", "tests/dead_test.py::test_never_referenced", "tests/dead_test.py::test_assignment_not_counted_as_reference", "tests/dead_test.py::test_only_referenced_in_tests", "tests/dead_test.py::test_unused_dead_disable_comment", "tests/dead_test.py::test_partially_disabled", "tests/dead_test.py::test_unused_argument", "tests/dead_test.py::test_unused_argument_in_scope", "tests/dead_test.py::test_using_an_argument", "tests/dead_test.py::test_ignore_unused_arguments_stubs", "tests/dead_test.py::test_ignored_arguments" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-02-06 21:25:25+00:00
mit
1,125
asottile__dead-37
diff --git a/dead.py b/dead.py index 5b3fdbc..a9f48c0 100644 --- a/dead.py +++ b/dead.py @@ -131,6 +131,7 @@ class Visitor(ast.NodeVisitor): with self.scope(): if not self._is_stub_function(node): for arg in ( + *getattr(node.args, 'posonlyargs', ()), *node.args.args, node.args.vararg, *node.args.kwonlyargs,
asottile/dead
8817aa412121e319fc45dd5e269b0d009e7c2c06
diff --git a/tests/dead_test.py b/tests/dead_test.py index 73aa8b2..9de3213 100644 --- a/tests/dead_test.py +++ b/tests/dead_test.py @@ -1,4 +1,5 @@ import subprocess +import sys import pytest @@ -247,3 +248,16 @@ def test_ignored_arguments(git_dir): ) subprocess.check_call(('git', 'add', '.')) assert not dead.main(()) + + [email protected](sys.version_info < (3, 8), reason='py38+') +def test_unused_positional_only_argument(git_dir, capsys): # pragma: no cover + git_dir.join('f.py').write( + 'def f(unused, /):\n' + ' return 1\n' + 'print(f)\n', + ) + subprocess.check_call(('git', 'add', '.')) + assert dead.main(()) + out, _ = capsys.readouterr() + assert out == 'unused is never read, defined in f.py:1\n'
Support posonlyargs they are notably missing in [this code](https://github.com/asottile/dead/blob/8817aa412121e319fc45dd5e269b0d009e7c2c06/dead.py#L133-L140)
0.0
8817aa412121e319fc45dd5e269b0d009e7c2c06
[ "tests/dead_test.py::test_unused_positional_only_argument" ]
[ "tests/dead_test.py::test_dead_disable_regex_matching[#", "tests/dead_test.py::test_dead_disable_regex_matching[#dead:disable]", "tests/dead_test.py::test_dead_disable_regex_not_matching[#", "tests/dead_test.py::test_is_marked_as_used[x", "tests/dead_test.py::test_is_marked_as_used[def", "tests/dead_test.py::test_is_marked_as_used[async", "tests/dead_test.py::test_is_marked_as_used[class", "tests/dead_test.py::test_is_marked_as_used[from", "tests/dead_test.py::test_is_marked_as_used[import", "tests/dead_test.py::test_is_marked_as_used[MyStr", "tests/dead_test.py::test_deleted_file_dont_raise_error", "tests/dead_test.py::test_setup_py_entrypoints_mark_as_used", "tests/dead_test.py::test_setup_cfg_entry_points_marked_as_used", "tests/dead_test.py::test_setup_cfg_without_entry_points", "tests/dead_test.py::test_setup_cfg_without_attribute_entry_point", "tests/dead_test.py::test_never_referenced", "tests/dead_test.py::test_assignment_not_counted_as_reference", "tests/dead_test.py::test_only_referenced_in_tests", "tests/dead_test.py::test_unused_dead_disable_comment", "tests/dead_test.py::test_partially_disabled", "tests/dead_test.py::test_unused_argument", "tests/dead_test.py::test_unused_argument_in_scope", "tests/dead_test.py::test_using_an_argument", "tests/dead_test.py::test_ignore_unused_arguments_stubs", "tests/dead_test.py::test_ignored_arguments" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2020-03-10 02:46:12+00:00
mit
1,126
asottile__git-code-debt-85
diff --git a/git_code_debt/generate.py b/git_code_debt/generate.py index cbc7de4..270966a 100644 --- a/git_code_debt/generate.py +++ b/git_code_debt/generate.py @@ -55,11 +55,19 @@ def _get_metrics_inner(m_args): return get_metrics(commit, diff, metric_parsers) +def mapper(jobs): + if jobs == 1: + return map + else: + return multiprocessing.Pool(jobs).imap + + def load_data( database_file, repo, package_names, skip_defaults, + jobs, ): metric_parsers = get_metric_parsers_from_args(package_names, skip_defaults) @@ -94,9 +102,9 @@ def load_data( itertools.repeat(repo_parser), itertools.repeat(metric_parsers), ) - pool = multiprocessing.pool.Pool(15) + do_map = mapper(jobs) for commit, metrics in six.moves.zip( - commits, pool.imap(_get_metrics_inner, mp_args), + commits, do_map(_get_metrics_inner, mp_args), ): increment_metric_values(metric_values, metrics) insert_metric_values( @@ -152,6 +160,9 @@ def get_options_from_config(config_filename): def main(argv=None): parser = argparse.ArgumentParser() options.add_generate_config_filename(parser) + parser.add_argument( + '-j', '--jobs', type=int, default=multiprocessing.cpu_count(), + ) parsed_args = parser.parse_args(argv) args = get_options_from_config(parsed_args.config_filename) @@ -163,6 +174,7 @@ def main(argv=None): args.repo, args.metric_package_names, args.skip_default_metrics, + parsed_args.jobs, )
asottile/git-code-debt
6a1bd3f95a1449bda391e16edbdeaf4e4091e9b4
diff --git a/tests/generate_test.py b/tests/generate_test.py index b99b85a..2f05015 100644 --- a/tests/generate_test.py +++ b/tests/generate_test.py @@ -17,6 +17,7 @@ from git_code_debt.generate import get_metric_ids from git_code_debt.generate import get_options_from_config from git_code_debt.generate import increment_metric_values from git_code_debt.generate import main +from git_code_debt.generate import mapper from git_code_debt.generate import populate_metric_ids from git_code_debt.metric import Metric from git_code_debt.metrics.lines import LinesOfCodeParser @@ -58,6 +59,16 @@ def test_get_metrics_inner_nth_commit(cloneable_with_commits): assert Metric(name='TotalLinesOfCode', value=2) in metrics +def square(x): + return x * x + + [email protected]('jobs', (1, 4)) +def test_mapper(jobs): + ret = tuple(mapper(jobs)(square, (3, 5, 9))) + assert ret == (9, 25, 81) + + def test_generate_integration(sandbox, cloneable): main(('-C', sandbox.gen_config(repo=cloneable)))
Multiprocessing eats tracebacks Multiprocessing eats the traceback from errors raised in debt metrics which makes it look like the underlying issue might be in git-code-debt and not our metric: I have redacted some things that are env specific for reasons. Here is the tb with multiprocessing: ```(venv) master ✗ 🦄 make generate venv/bin/git-code-debt-generate \ <codebase> \ database.db \ code_debt_metrics Cloning into '/tmp/tmp8XDrXvtemp-repo'... done. Traceback (most recent call last): File "venv/bin/git-code-debt-generate", line 11, in <module> sys.exit(main()) File "/code-debt/venv/local/lib/python2.7/site-packages/git_code_debt/generate.py", line 181, in main args.skip_default_metrics, File "/code-debt/venv/local/lib/python2.7/site-packages/git_code_debt/generate.py", line 98, in load_data commits, pool.imap(_get_metrics_inner, mp_args), File "/usr/lib/python2.7/multiprocessing/pool.py", line 668, in next raise value UnicodeDecodeError: 'ascii' codec can't decode byte 0xd5 in position 41: ordinal not in range(128) Makefile:26: recipe for target 'generate' failed make: *** [generate] Error 1 ``` Here is the tb when `pool.imap` is replaced with `map` in `generate.py`: ```(venv) master ✗ 🍪 make generate venv/bin/git-code-debt-generate \ <codebase> \ database.db \ code_debt_metrics Cloning into '/tmp/tmpxGxnB9temp-repo'... done. Traceback (most recent call last): File "venv/bin/git-code-debt-generate", line 11, in <module> sys.exit(main()) File "/code-debt/venv/local/lib/python2.7/site-packages/git_code_debt/generate.py", line 181, in main args.skip_default_metrics, File "/code-debt/venv/local/lib/python2.7/site-packages/git_code_debt/generate.py", line 98, in load_data commits, map(_get_metrics_inner, mp_args), File "/code-debt/venv/local/lib/python2.7/site-packages/git_code_debt/generate.py", line 54, in _get_metrics_inner return get_metrics(commit, diff, metric_parsers) File "/code-debt/venv/local/lib/python2.7/site-packages/git_code_debt/generate.py", line 40, in get_metrics return list(get_all_metrics(file_diff_stats)) File "/code-debt/venv/local/lib/python2.7/site-packages/git_code_debt/generate.py", line 35, in get_all_metrics commit, file_diff_stats, File "/code-debt/venv/local/lib/python2.7/site-packages/git_code_debt/metrics/base.py", line 39, in get_metrics_from_stat if self.line_matches_metric(line, file_diff_stat): File "/code-debt/venv/local/lib/python2.7/site-packages/code_debt_metrics/<metric>.py", line 29, in line_matches_metric return '<thing> = True' in line UnicodeDecodeError: 'ascii' codec can't decode byte 0xd5 in position 41: ordinal not in range(128) Makefile:26: recipe for target 'generate' failed make: *** [generate] Error 1 ```
0.0
6a1bd3f95a1449bda391e16edbdeaf4e4091e9b4
[ "tests/generate_test.py::test_increment_metrics_first_time", "tests/generate_test.py::test_increment_metrics_already_there", "tests/generate_test.py::test_mapper[1]", "tests/generate_test.py::test_mapper[4]", "tests/generate_test.py::test_get_options_from_config_no_config_file", "tests/generate_test.py::test_create_schema", "tests/generate_test.py::test_populate_metric_ids" ]
[]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-01-21 00:35:37+00:00
mit
1,127
asottile__git-code-debt-91
diff --git a/git_code_debt/generate.py b/git_code_debt/generate.py index 90d72da..283b26c 100644 --- a/git_code_debt/generate.py +++ b/git_code_debt/generate.py @@ -29,7 +29,7 @@ from git_code_debt.write_logic import insert_metric_values from git_code_debt.write_logic import update_has_data -def get_metrics(commit, diff, metric_parsers): +def get_metrics(commit, diff, metric_parsers, exclude): def get_all_metrics(file_diff_stats): for metric_parser_cls in metric_parsers: metric_parser = metric_parser_cls() @@ -39,6 +39,10 @@ def get_metrics(commit, diff, metric_parsers): yield metric file_diff_stats = get_file_diff_stats_from_output(diff) + file_diff_stats = tuple( + x for x in file_diff_stats + if not exclude.search(x.path) + ) return tuple(get_all_metrics(file_diff_stats)) @@ -47,13 +51,13 @@ def increment_metric_values(metric_values, metrics): metric_values[metric.name] += metric.value -def _get_metrics_inner(m_args): - compare_commit, commit, repo_parser, metric_parsers = m_args +def _get_metrics_inner(mp_args): + compare_commit, commit, repo_parser, metric_parsers, exclude = mp_args if compare_commit is None: diff = repo_parser.get_original_commit(commit.sha) else: diff = repo_parser.get_commit_diff(compare_commit.sha, commit.sha) - return get_metrics(commit, diff, metric_parsers) + return get_metrics(commit, diff, metric_parsers, exclude) def mapper(jobs): @@ -68,6 +72,7 @@ def load_data( repo, package_names, skip_defaults, + exclude, jobs, ): metric_parsers = get_metric_parsers_from_args(package_names, skip_defaults) @@ -102,6 +107,7 @@ def load_data( commits, itertools.repeat(repo_parser), itertools.repeat(metric_parsers), + itertools.repeat(exclude), ) do_map = mapper(jobs) for commit, metrics in six.moves.zip( @@ -176,6 +182,7 @@ def main(argv=None): args.repo, args.metric_package_names, args.skip_default_metrics, + args.exclude, parsed_args.jobs, ) diff --git a/git_code_debt/generate_config.py b/git_code_debt/generate_config.py index ad9fce6..302a8ca 100644 --- a/git_code_debt/generate_config.py +++ b/git_code_debt/generate_config.py @@ -2,6 +2,7 @@ from __future__ import absolute_import from __future__ import unicode_literals import collections +import re import jsonschema @@ -17,6 +18,7 @@ GENERATE_OPTIONS_SCHEMA = { 'metric_package_names': {'type': 'array', 'items': {'type': 'string'}}, 'repo': {'type': 'string'}, 'database': {'type': 'string'}, + 'exclude': {'type': 'string'}, }, } @@ -28,6 +30,7 @@ class GenerateOptions(collections.namedtuple( 'metric_package_names', 'repo', 'database', + 'exclude', ), )): @classmethod @@ -38,4 +41,5 @@ class GenerateOptions(collections.namedtuple( metric_package_names=yaml_dict.get('metric_package_names', []), repo=yaml_dict['repo'], database=yaml_dict['database'], + exclude=re.compile(yaml_dict.get('exclude', '^$').encode()), ) diff --git a/git_code_debt/server/servlets/widget.py b/git_code_debt/server/servlets/widget.py index a023861..6264a09 100644 --- a/git_code_debt/server/servlets/widget.py +++ b/git_code_debt/server/servlets/widget.py @@ -35,7 +35,7 @@ def data(): parsers = get_metric_parsers_from_args( metric_config.metric_package_names, skip_defaults=False, ) - metrics = get_metrics(Commit.blank, diff, parsers) + metrics = get_metrics(Commit.blank, diff, parsers, metric_config.exclude) metrics = [ metric for metric in metrics if metric.value and metric.name in metric_names
asottile/git-code-debt
44b090434a24fe945747a98fddde5a051f0c7b1d
diff --git a/tests/generate_config_test.py b/tests/generate_config_test.py index 889b074..3449297 100644 --- a/tests/generate_config_test.py +++ b/tests/generate_config_test.py @@ -1,6 +1,8 @@ from __future__ import absolute_import from __future__ import unicode_literals +import re + import jsonschema.exceptions import pytest @@ -18,12 +20,14 @@ def test_with_all_options_specified(): 'metric_package_names': ['my_package'], 'repo': '.', 'database': 'database.db', + 'exclude': '^vendor/', }) assert ret == GenerateOptions( skip_default_metrics=True, metric_package_names=['my_package'], repo='.', database='database.db', + exclude=re.compile(b'^vendor/'), ) @@ -34,17 +38,5 @@ def test_minimal_defaults(): metric_package_names=[], repo='./', database='database.db', - ) - - -def test_none_for_tempdir_allowed(): - ret = GenerateOptions.from_yaml({ - 'repo': 'repo', - 'database': 'database.db', - }) - assert ret == GenerateOptions( - skip_default_metrics=False, - metric_package_names=[], - repo='repo', - database='database.db', + exclude=re.compile(b'^$'), ) diff --git a/tests/generate_test.py b/tests/generate_test.py index 2f05015..62eb1c6 100644 --- a/tests/generate_test.py +++ b/tests/generate_test.py @@ -3,12 +3,11 @@ from __future__ import unicode_literals import collections import io -import os import os.path +import re import sqlite3 import pytest -import yaml from git_code_debt.discovery import get_metric_parsers_from_args from git_code_debt.generate import _get_metrics_inner @@ -43,7 +42,7 @@ def test_get_metrics_inner_first_commit(cloneable_with_commits): with repo_parser.repo_checked_out(): metrics = _get_metrics_inner(( None, cloneable_with_commits.commits[0], - repo_parser, [LinesOfCodeParser], + repo_parser, [LinesOfCodeParser], re.compile(b'^$'), )) assert Metric(name='TotalLinesOfCode', value=0) in metrics @@ -54,7 +53,7 @@ def test_get_metrics_inner_nth_commit(cloneable_with_commits): metrics = _get_metrics_inner(( cloneable_with_commits.commits[-2], cloneable_with_commits.commits[-1], - repo_parser, [LinesOfCodeParser], + repo_parser, [LinesOfCodeParser], re.compile(b'^$'), )) assert Metric(name='TotalLinesOfCode', value=2) in metrics @@ -73,18 +72,6 @@ def test_generate_integration(sandbox, cloneable): main(('-C', sandbox.gen_config(repo=cloneable))) -def test_generate_integration_config_file(sandbox, cloneable, tempdir_factory): - tmpdir = tempdir_factory.get() - config_filename = os.path.join(tmpdir, 'generate_config.yaml') - with io.open(config_filename, 'w') as config_file: - yaml.dump( - {'repo': cloneable, 'database': sandbox.db_path}, - stream=config_file, - ) - with cwd(tmpdir): - main([]) - - def test_main_database_does_not_exist(sandbox, cloneable): new_db_path = os.path.join(sandbox.directory, 'new.db') cfg = sandbox.gen_config(database=new_db_path, repo=cloneable) @@ -157,6 +144,25 @@ def test_moves_handled_properly(sandbox, cloneable): assert not main(('-C', sandbox.gen_config(repo=cloneable))) +def test_exclude_pattern(sandbox, cloneable_with_commits): + cfg = sandbox.gen_config( + repo=cloneable_with_commits.path, exclude='\.tmpl$', + ) + assert not main(('-C', cfg)) + with sandbox.db() as db: + query = ( + 'SELECT running_value\n' + 'FROM metric_data\n' + 'INNER JOIN metric_names ON\n' + ' metric_data.metric_id == metric_names.id\n' + 'WHERE sha = ? AND name = "TotalLinesOfCode"\n' + ) + sha = cloneable_with_commits.commits[-1].sha + val, = db.execute(query, (sha,)).fetchone() + # 2 lines of code from test.py, 0 lines from foo.tmpl (2 lines) + assert val == 2 + + def test_get_options_from_config_no_config_file(): with pytest.raises(SystemExit): get_options_from_config('i-dont-exist')
Add `exclude` pattern Add the ability to remove checked in files from the pattern which are not part of the codebase. For example: ```yaml exclude: '^vendor/' ```
0.0
44b090434a24fe945747a98fddde5a051f0c7b1d
[ "tests/generate_config_test.py::test_with_all_options_specified", "tests/generate_config_test.py::test_minimal_defaults" ]
[ "tests/generate_config_test.py::test_empty_config_invalid", "tests/generate_test.py::test_increment_metrics_first_time", "tests/generate_test.py::test_increment_metrics_already_there", "tests/generate_test.py::test_mapper[1]", "tests/generate_test.py::test_mapper[4]", "tests/generate_test.py::test_get_options_from_config_no_config_file", "tests/generate_test.py::test_create_schema", "tests/generate_test.py::test_populate_metric_ids" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-01-22 04:17:54+00:00
mit
1,128
asottile__pyupgrade-104
diff --git a/pyupgrade.py b/pyupgrade.py index cdf8c14..f41fa13 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -429,7 +429,7 @@ ESCAPE_STARTS = frozenset(( 'N', 'u', 'U', )) ESCAPE_STARTS_BYTES = ESCAPE_STARTS - frozenset(('N', 'u', 'U')) -ESCAPE_RE = re.compile(r'\\.') +ESCAPE_RE = re.compile(r'\\.', re.DOTALL) def _fix_escape_sequences(contents_text):
asottile/pyupgrade
ce50197308d00f85aa728ad6afba33f3f1383544
diff --git a/tests/pyupgrade_test.py b/tests/pyupgrade_test.py index 183903f..685571c 100644 --- a/tests/pyupgrade_test.py +++ b/tests/pyupgrade_test.py @@ -370,6 +370,10 @@ def test_fix_escape_sequences_noop(s): (r'"\8"', r'r"\8"'), (r'"\9"', r'r"\9"'), # explicit byte strings should not honor string-specific escapes ('b"\\u2603"', 'br"\\u2603"'), + # do not make a raw string for escaped newlines + ('"""\\\n\\q"""', '"""\\\n\\\\q"""'), + ('"""\\\r\n\\q"""', '"""\\\r\n\\\\q"""'), + ('"""\\\r\\q"""', '"""\\\r\\\\q"""'), ), ) def test_fix_escape_sequences(s, expected):
raw-string rewrite with escaped newlines incorrect ```console $ cat t.py x = """\ foo\s """ print(x) $ python t.py foo\s $ pyupgrade t.py Rewriting t.py $ cat t.py x = r"""\ foo\s """ print(x) $ python t.py \ foo\s ```
0.0
ce50197308d00f85aa728ad6afba33f3f1383544
[ "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\n\\\\q\"\"\"-\"\"\"\\\\\\n\\\\\\\\q\"\"\"]" ]
[ "tests/pyupgrade_test.py::test_roundtrip_text[]", "tests/pyupgrade_test.py::test_roundtrip_text[foo]", "tests/pyupgrade_test.py::test_roundtrip_text[{}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0}]", "tests/pyupgrade_test.py::test_roundtrip_text[{named}]", "tests/pyupgrade_test.py::test_roundtrip_text[{!r}]", "tests/pyupgrade_test.py::test_roundtrip_text[{:>5}]", "tests/pyupgrade_test.py::test_roundtrip_text[{{]", "tests/pyupgrade_test.py::test_roundtrip_text[}}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0!s:15}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/pyupgrade_test.py::test_sets[set()-set()]", "tests/pyupgrade_test.py::test_sets[set((\\n))-set((\\n))]", "tests/pyupgrade_test.py::test_sets[set", "tests/pyupgrade_test.py::test_sets[set(())-set()]", "tests/pyupgrade_test.py::test_sets[set([])-set()]", "tests/pyupgrade_test.py::test_sets[set((", "tests/pyupgrade_test.py::test_sets[set((1,", "tests/pyupgrade_test.py::test_sets[set([1,", "tests/pyupgrade_test.py::test_sets[set(x", "tests/pyupgrade_test.py::test_sets[set([x", "tests/pyupgrade_test.py::test_sets[set((x", "tests/pyupgrade_test.py::test_sets[set(((1,", "tests/pyupgrade_test.py::test_sets[set((a,", "tests/pyupgrade_test.py::test_sets[set([(1,", "tests/pyupgrade_test.py::test_sets[set(\\n", "tests/pyupgrade_test.py::test_sets[set([((1,", "tests/pyupgrade_test.py::test_sets[set((((1,", "tests/pyupgrade_test.py::test_sets[set(\\n(1,", "tests/pyupgrade_test.py::test_sets[set((\\n1,\\n2,\\n))\\n-{\\n1,\\n2,\\n}\\n]", "tests/pyupgrade_test.py::test_sets[set((frozenset(set((1,", "tests/pyupgrade_test.py::test_sets[set((1,))-{1}]", "tests/pyupgrade_test.py::test_dictcomps[x", "tests/pyupgrade_test.py::test_dictcomps[dict()-dict()]", "tests/pyupgrade_test.py::test_dictcomps[(-(]", "tests/pyupgrade_test.py::test_dictcomps[dict", "tests/pyupgrade_test.py::test_dictcomps[dict((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([(a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a),", "tests/pyupgrade_test.py::test_dictcomps[dict((k,", "tests/pyupgrade_test.py::test_dictcomps[dict(\\n", "tests/pyupgrade_test.py::test_dictcomps[x(\\n", "tests/pyupgrade_test.py::test_format_literals[\"{0}\"format(1)-\"{0}\"format(1)]", "tests/pyupgrade_test.py::test_format_literals['{}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{'.format(1)-'{'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['}'.format(1)-'}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals[x", "tests/pyupgrade_test.py::test_format_literals['{0}", "tests/pyupgrade_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{0:x}'.format(30)-'{:x}'.format(30)]", "tests/pyupgrade_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/pyupgrade_test.py::test_format_literals['{0}'", "tests/pyupgrade_test.py::test_format_literals[print(\\n", "tests/pyupgrade_test.py::test_format_literals['{0:<{1}}'.format(1,", "tests/pyupgrade_test.py::test_imports_unicode_literals[import", "tests/pyupgrade_test.py::test_imports_unicode_literals[from", "tests/pyupgrade_test.py::test_imports_unicode_literals[x", "tests/pyupgrade_test.py::test_imports_unicode_literals[\"\"\"docstring\"\"\"\\nfrom", "tests/pyupgrade_test.py::test_unicode_literals[(-False-(]", "tests/pyupgrade_test.py::test_unicode_literals[u''-False-u'']", "tests/pyupgrade_test.py::test_unicode_literals[u''-True-'']", "tests/pyupgrade_test.py::test_unicode_literals[from", "tests/pyupgrade_test.py::test_unicode_literals[\"\"\"with", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'\\\\d']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\"\"\\\\d\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'''\\\\d''']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[rb\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\r\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\d\"-r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\n\\\\d\"-\"\\\\n\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[u\"\\\\d\"-u\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\d\"-br\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\8\"-r\"\\\\8\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\9\"-r\"\\\\9\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\u2603\"-br\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\n\\\\q\"\"\"-\"\"\"\\\\\\r\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\\\q\"\"\"-\"\"\"\\\\\\r\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_noop_octal_literals[0]", "tests/pyupgrade_test.py::test_noop_octal_literals[00]", "tests/pyupgrade_test.py::test_noop_octal_literals[1]", "tests/pyupgrade_test.py::test_noop_octal_literals[12345]", "tests/pyupgrade_test.py::test_noop_octal_literals[1.2345]", "tests/pyupgrade_test.py::test_is_bytestring_true[b'']", "tests/pyupgrade_test.py::test_is_bytestring_true[b\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B'']", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''0]", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''1]", "tests/pyupgrade_test.py::test_is_bytestring_false[]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false['']", "tests/pyupgrade_test.py::test_is_bytestring_false[u\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"b\"]", "tests/pyupgrade_test.py::test_parse_percent_format[\"\"-expected0]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%%\"-expected1]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s\"-expected2]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(hi)s\"-expected4]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%()s\"-expected5]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%#o\"-expected6]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%", "tests/pyupgrade_test.py::test_parse_percent_format[\"%5d\"-expected8]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%*d\"-expected9]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.f\"-expected10]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.5f\"-expected11]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.*f\"-expected12]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%ld\"-expected13]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(complete)#4.4f\"-expected14]", "tests/pyupgrade_test.py::test_percent_to_format[%s-{}]", "tests/pyupgrade_test.py::test_percent_to_format[%%%s-%{}]", "tests/pyupgrade_test.py::test_percent_to_format[%(foo)s-{foo}]", "tests/pyupgrade_test.py::test_percent_to_format[%2f-{:2f}]", "tests/pyupgrade_test.py::test_percent_to_format[%r-{!r}]", "tests/pyupgrade_test.py::test_percent_to_format[%a-{!a}]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[-]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[", "tests/pyupgrade_test.py::test_simplify_conversion_flag[#0-", "tests/pyupgrade_test.py::test_simplify_conversion_flag[--<]", "tests/pyupgrade_test.py::test_percent_format_noop[\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[b\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%d\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%i\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%u\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%c\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%#o\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%()s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%4%\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2r\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2a\"", "tests/pyupgrade_test.py::test_percent_format_noop[i", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(1)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(a)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(ab)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(and)s\"", "tests/pyupgrade_test.py::test_percent_format[\"trivial\"", "tests/pyupgrade_test.py::test_percent_format[\"%s\"", "tests/pyupgrade_test.py::test_percent_format[\"%s%%", "tests/pyupgrade_test.py::test_percent_format[\"%3f\"", "tests/pyupgrade_test.py::test_percent_format[\"%-5s\"", "tests/pyupgrade_test.py::test_percent_format[\"%9s\"", "tests/pyupgrade_test.py::test_percent_format[\"brace", "tests/pyupgrade_test.py::test_percent_format[\"%(k)s\"", "tests/pyupgrade_test.py::test_percent_format[\"%(to_list)s\"", "tests/pyupgrade_test.py::test_fix_super_noop[x(]", "tests/pyupgrade_test.py::test_fix_super_noop[class", "tests/pyupgrade_test.py::test_fix_super_noop[def", "tests/pyupgrade_test.py::test_fix_super[class", "tests/pyupgrade_test.py::test_fix_new_style_classes_noop[x", "tests/pyupgrade_test.py::test_fix_new_style_classes_noop[class", "tests/pyupgrade_test.py::test_fix_new_style_classes[class", "tests/pyupgrade_test.py::test_fix_six_noop[x", "tests/pyupgrade_test.py::test_fix_six_noop[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six_noop[@", "tests/pyupgrade_test.py::test_fix_six_noop[from", "tests/pyupgrade_test.py::test_fix_six_noop[@mydec\\nclass", "tests/pyupgrade_test.py::test_fix_six_noop[six.u", "tests/pyupgrade_test.py::test_fix_six_noop[six.raise_from", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six[issubclass(tp,", "tests/pyupgrade_test.py::test_fix_six[STRING_TYPES", "tests/pyupgrade_test.py::test_fix_six[from", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/pyupgrade_test.py::test_fix_six[six.get_unbound_method(meth)\\n-meth\\n]", "tests/pyupgrade_test.py::test_fix_six[six.indexbytes(bs,", "tests/pyupgrade_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/pyupgrade_test.py::test_fix_six[six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(tp,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(\\n", "tests/pyupgrade_test.py::test_fix_new_style_classes_py3only[class", "tests/pyupgrade_test.py::test_fix_fstrings_noop[(]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\"", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{foo}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{0}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[b\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{1}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{.x}", "tests/pyupgrade_test.py::test_fix_fstrings[\"hello", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped,", "tests/pyupgrade_test.py::test_main_trivial", "tests/pyupgrade_test.py::test_main_noop", "tests/pyupgrade_test.py::test_main_changes_a_file", "tests/pyupgrade_test.py::test_main_keeps_line_endings", "tests/pyupgrade_test.py::test_main_syntax_error", "tests/pyupgrade_test.py::test_main_non_utf8_bytes", "tests/pyupgrade_test.py::test_keep_percent_format", "tests/pyupgrade_test.py::test_py3_plus_argument_unicode_literals", "tests/pyupgrade_test.py::test_py3_plus_super", "tests/pyupgrade_test.py::test_py3_plus_new_style_classes", "tests/pyupgrade_test.py::test_py36_plus_fstrings" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2019-02-17 19:30:52+00:00
mit
1,129
asottile__pyupgrade-112
diff --git a/README.md b/README.md index 42f687b..7d0d7c9 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,18 @@ u'\d' # u'\\d' # but in python3.x, that's our friend ☃ ``` +### `ur` string literals + +`ur'...'` literals are not valid in python 3.x + +```python +ur'foo' # u'foo' +ur'\s' # u'\\s' +# unicode escapes are left alone +ur'\u2603' # u'\u2603' +ur'\U0001f643' # u'\U0001f643' +``` + ### Long literals Availability: diff --git a/pyupgrade.py b/pyupgrade.py index 52db3b9..5f9c1aa 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -415,15 +415,14 @@ ESCAPE_STARTS_BYTES = ESCAPE_STARTS - frozenset(('N', 'u', 'U')) ESCAPE_RE = re.compile(r'\\.', re.DOTALL) -def _fix_escape_sequences(last_name, token): - match = STRING_PREFIXES_RE.match(token.src) - prefix = match.group(1) - rest = match.group(2) +def _parse_string_literal(s): + match = STRING_PREFIXES_RE.match(s) + return match.group(1), match.group(2) - if last_name is not None: # pragma: no cover (py2 bug) - actual_prefix = (last_name.src + prefix).lower() - else: # pragma: no cover (py3 only) - actual_prefix = prefix.lower() + +def _fix_escape_sequences(token): + prefix, rest = _parse_string_literal(token.src) + actual_prefix = prefix.lower() if 'r' in actual_prefix or '\\' not in rest: return token @@ -452,36 +451,53 @@ def _fix_escape_sequences(last_name, token): return token -def _remove_u_prefix(last_name, token): - match = STRING_PREFIXES_RE.match(token.src) - prefix = match.group(1) +def _remove_u_prefix(token): + prefix, rest = _parse_string_literal(token.src) if 'u' not in prefix.lower(): return token else: - rest = match.group(2) new_prefix = prefix.replace('u', '').replace('U', '') return Token('STRING', new_prefix + rest) +def _fix_ur_literals(token): + prefix, rest = _parse_string_literal(token.src) + if prefix.lower() != 'ur': + return token + else: + def cb(match): + escape = match.group() + if escape[1].lower() == 'u': + return escape + else: + return '\\' + match.group() + + rest = ESCAPE_RE.sub(cb, rest) + prefix = prefix.replace('r', '').replace('R', '') + return token._replace(src=prefix + rest) + + def _fix_strings(contents_text, py3_plus): remove_u_prefix = py3_plus or _imports_unicode_literals(contents_text) - last_name = None try: tokens = src_to_tokens(contents_text) except tokenize.TokenError: return contents_text for i, token in enumerate(tokens): - if token.name == 'NAME': - last_name = token - continue - elif token.name != 'STRING': - last_name = None + if token.name != 'STRING': continue + # when a string prefix is not recognized, the tokenizer produces a + # NAME token followed by a STRING token + if i > 0 and tokens[i - 1].name == 'NAME': + tokens[i] = token._replace(src=tokens[i - 1].src + token.src) + tokens[i - 1] = tokens[i - 1]._replace(src='') + + tokens[i] = _fix_ur_literals(tokens[i]) if remove_u_prefix: - tokens[i] = _remove_u_prefix(last_name, tokens[i]) - tokens[i] = _fix_escape_sequences(last_name, tokens[i]) + tokens[i] = _remove_u_prefix(tokens[i]) + tokens[i] = _fix_escape_sequences(tokens[i]) return tokens_to_src(tokens)
asottile/pyupgrade
74925d02fe09e37a8aa7705cc1f3fd2a5248fe9b
diff --git a/tests/pyupgrade_test.py b/tests/pyupgrade_test.py index b9e975d..37b28cb 100644 --- a/tests/pyupgrade_test.py +++ b/tests/pyupgrade_test.py @@ -331,6 +331,25 @@ def test_unicode_literals(s, py3_plus, expected): assert ret == expected [email protected]( + ('s', 'expected'), + ( + pytest.param('ur"hi"', 'u"hi"', id='basic case'), + pytest.param('UR"hi"', 'U"hi"', id='upper case raw'), + pytest.param(r'ur"\s"', r'u"\\s"', id='with an escape'), + pytest.param('ur"\\u2603"', 'u"\\u2603"', id='with unicode escapes'), + pytest.param('ur"\\U0001f643"', 'u"\\U0001f643"', id='emoji'), + ), +) +def test_fix_ur_literals(s, expected): + ret = _fix_strings(s, py3_plus=False) + assert ret == expected + + +def test_fix_ur_literals_gets_fixed_before_u_removed(): + assert _fix_strings("ur'\\s\\u2603'", py3_plus=True) == "'\\\\s\\u2603'" + + @pytest.mark.parametrize( 's', (
Rewrite `ur` literals `ur` literals are invalid syntax in python3.x
0.0
74925d02fe09e37a8aa7705cc1f3fd2a5248fe9b
[ "tests/pyupgrade_test.py::test_fix_ur_literals[basic", "tests/pyupgrade_test.py::test_fix_ur_literals[upper", "tests/pyupgrade_test.py::test_fix_ur_literals[with", "tests/pyupgrade_test.py::test_fix_ur_literals[emoji]", "tests/pyupgrade_test.py::test_fix_ur_literals_gets_fixed_before_u_removed" ]
[ "tests/pyupgrade_test.py::test_roundtrip_text[]", "tests/pyupgrade_test.py::test_roundtrip_text[foo]", "tests/pyupgrade_test.py::test_roundtrip_text[{}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0}]", "tests/pyupgrade_test.py::test_roundtrip_text[{named}]", "tests/pyupgrade_test.py::test_roundtrip_text[{!r}]", "tests/pyupgrade_test.py::test_roundtrip_text[{:>5}]", "tests/pyupgrade_test.py::test_roundtrip_text[{{]", "tests/pyupgrade_test.py::test_roundtrip_text[}}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0!s:15}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/pyupgrade_test.py::test_sets[set()-set()]", "tests/pyupgrade_test.py::test_sets[set((\\n))-set((\\n))]", "tests/pyupgrade_test.py::test_sets[set", "tests/pyupgrade_test.py::test_sets[set(())-set()]", "tests/pyupgrade_test.py::test_sets[set([])-set()]", "tests/pyupgrade_test.py::test_sets[set((", "tests/pyupgrade_test.py::test_sets[set((1,", "tests/pyupgrade_test.py::test_sets[set([1,", "tests/pyupgrade_test.py::test_sets[set(x", "tests/pyupgrade_test.py::test_sets[set([x", "tests/pyupgrade_test.py::test_sets[set((x", "tests/pyupgrade_test.py::test_sets[set(((1,", "tests/pyupgrade_test.py::test_sets[set((a,", "tests/pyupgrade_test.py::test_sets[set([(1,", "tests/pyupgrade_test.py::test_sets[set(\\n", "tests/pyupgrade_test.py::test_sets[set([((1,", "tests/pyupgrade_test.py::test_sets[set((((1,", "tests/pyupgrade_test.py::test_sets[set(\\n(1,", "tests/pyupgrade_test.py::test_sets[set((\\n1,\\n2,\\n))\\n-{\\n1,\\n2,\\n}\\n]", "tests/pyupgrade_test.py::test_sets[set((frozenset(set((1,", "tests/pyupgrade_test.py::test_sets[set((1,))-{1}]", "tests/pyupgrade_test.py::test_dictcomps[x", "tests/pyupgrade_test.py::test_dictcomps[dict()-dict()]", "tests/pyupgrade_test.py::test_dictcomps[(-(]", "tests/pyupgrade_test.py::test_dictcomps[dict", "tests/pyupgrade_test.py::test_dictcomps[dict((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([(a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a),", "tests/pyupgrade_test.py::test_dictcomps[dict((k,", "tests/pyupgrade_test.py::test_dictcomps[dict(\\n", "tests/pyupgrade_test.py::test_dictcomps[x(\\n", "tests/pyupgrade_test.py::test_format_literals[\"{0}\"format(1)-\"{0}\"format(1)]", "tests/pyupgrade_test.py::test_format_literals['{}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{'.format(1)-'{'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['}'.format(1)-'}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals[x", "tests/pyupgrade_test.py::test_format_literals['{0}", "tests/pyupgrade_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{0:x}'.format(30)-'{:x}'.format(30)]", "tests/pyupgrade_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/pyupgrade_test.py::test_format_literals['{0}'", "tests/pyupgrade_test.py::test_format_literals[print(\\n", "tests/pyupgrade_test.py::test_format_literals['{0:<{1}}'.format(1,", "tests/pyupgrade_test.py::test_imports_unicode_literals[import", "tests/pyupgrade_test.py::test_imports_unicode_literals[from", "tests/pyupgrade_test.py::test_imports_unicode_literals[x", "tests/pyupgrade_test.py::test_imports_unicode_literals[\"\"\"docstring\"\"\"\\nfrom", "tests/pyupgrade_test.py::test_unicode_literals[(-False-(]", "tests/pyupgrade_test.py::test_unicode_literals[u''-False-u'']", "tests/pyupgrade_test.py::test_unicode_literals[u''-True-'']", "tests/pyupgrade_test.py::test_unicode_literals[from", "tests/pyupgrade_test.py::test_unicode_literals[\"\"\"with", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'\\\\d']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\"\"\\\\d\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'''\\\\d''']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[rb\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\r\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\d\"-r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\n\\\\d\"-\"\\\\n\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[u\"\\\\d\"-u\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\d\"-br\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\8\"-r\"\\\\8\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\9\"-r\"\\\\9\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\u2603\"-br\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\n\\\\q\"\"\"-\"\"\"\\\\\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\n\\\\q\"\"\"-\"\"\"\\\\\\r\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\\\q\"\"\"-\"\"\"\\\\\\r\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_noop_octal_literals[0]", "tests/pyupgrade_test.py::test_noop_octal_literals[00]", "tests/pyupgrade_test.py::test_noop_octal_literals[1]", "tests/pyupgrade_test.py::test_noop_octal_literals[12345]", "tests/pyupgrade_test.py::test_noop_octal_literals[1.2345]", "tests/pyupgrade_test.py::test_is_bytestring_true[b'']", "tests/pyupgrade_test.py::test_is_bytestring_true[b\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B'']", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''0]", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''1]", "tests/pyupgrade_test.py::test_is_bytestring_false[]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false['']", "tests/pyupgrade_test.py::test_is_bytestring_false[u\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"b\"]", "tests/pyupgrade_test.py::test_parse_percent_format[\"\"-expected0]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%%\"-expected1]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s\"-expected2]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(hi)s\"-expected4]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%()s\"-expected5]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%#o\"-expected6]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%", "tests/pyupgrade_test.py::test_parse_percent_format[\"%5d\"-expected8]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%*d\"-expected9]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.f\"-expected10]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.5f\"-expected11]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.*f\"-expected12]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%ld\"-expected13]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(complete)#4.4f\"-expected14]", "tests/pyupgrade_test.py::test_percent_to_format[%s-{}]", "tests/pyupgrade_test.py::test_percent_to_format[%%%s-%{}]", "tests/pyupgrade_test.py::test_percent_to_format[%(foo)s-{foo}]", "tests/pyupgrade_test.py::test_percent_to_format[%2f-{:2f}]", "tests/pyupgrade_test.py::test_percent_to_format[%r-{!r}]", "tests/pyupgrade_test.py::test_percent_to_format[%a-{!a}]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[-]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[", "tests/pyupgrade_test.py::test_simplify_conversion_flag[#0-", "tests/pyupgrade_test.py::test_simplify_conversion_flag[--<]", "tests/pyupgrade_test.py::test_percent_format_noop[\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[b\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%d\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%i\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%u\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%c\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%#o\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%()s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%4%\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2r\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2a\"", "tests/pyupgrade_test.py::test_percent_format_noop[i", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(1)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(a)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(ab)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(and)s\"", "tests/pyupgrade_test.py::test_percent_format[\"trivial\"", "tests/pyupgrade_test.py::test_percent_format[\"%s\"", "tests/pyupgrade_test.py::test_percent_format[\"%s%%", "tests/pyupgrade_test.py::test_percent_format[\"%3f\"", "tests/pyupgrade_test.py::test_percent_format[\"%-5s\"", "tests/pyupgrade_test.py::test_percent_format[\"%9s\"", "tests/pyupgrade_test.py::test_percent_format[\"brace", "tests/pyupgrade_test.py::test_percent_format[\"%(k)s\"", "tests/pyupgrade_test.py::test_percent_format[\"%(to_list)s\"", "tests/pyupgrade_test.py::test_fix_super_noop[x(]", "tests/pyupgrade_test.py::test_fix_super_noop[class", "tests/pyupgrade_test.py::test_fix_super_noop[def", "tests/pyupgrade_test.py::test_fix_super[class", "tests/pyupgrade_test.py::test_fix_new_style_classes_noop[x", "tests/pyupgrade_test.py::test_fix_new_style_classes_noop[class", "tests/pyupgrade_test.py::test_fix_new_style_classes[class", "tests/pyupgrade_test.py::test_fix_six_noop[x", "tests/pyupgrade_test.py::test_fix_six_noop[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six_noop[@", "tests/pyupgrade_test.py::test_fix_six_noop[from", "tests/pyupgrade_test.py::test_fix_six_noop[@mydec\\nclass", "tests/pyupgrade_test.py::test_fix_six_noop[six.u", "tests/pyupgrade_test.py::test_fix_six_noop[six.raise_from", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six[issubclass(tp,", "tests/pyupgrade_test.py::test_fix_six[STRING_TYPES", "tests/pyupgrade_test.py::test_fix_six[from", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/pyupgrade_test.py::test_fix_six[six.get_unbound_method(meth)\\n-meth\\n]", "tests/pyupgrade_test.py::test_fix_six[six.indexbytes(bs,", "tests/pyupgrade_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/pyupgrade_test.py::test_fix_six[six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(tp,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(\\n", "tests/pyupgrade_test.py::test_fix_new_style_classes_py3only[class", "tests/pyupgrade_test.py::test_fix_fstrings_noop[(]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\"", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{foo}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{0}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[b\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{1}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{.x}", "tests/pyupgrade_test.py::test_fix_fstrings[\"hello", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped,", "tests/pyupgrade_test.py::test_main_trivial", "tests/pyupgrade_test.py::test_main_noop", "tests/pyupgrade_test.py::test_main_changes_a_file", "tests/pyupgrade_test.py::test_main_keeps_line_endings", "tests/pyupgrade_test.py::test_main_syntax_error", "tests/pyupgrade_test.py::test_main_non_utf8_bytes", "tests/pyupgrade_test.py::test_keep_percent_format", "tests/pyupgrade_test.py::test_py3_plus_argument_unicode_literals", "tests/pyupgrade_test.py::test_py3_plus_super", "tests/pyupgrade_test.py::test_py3_plus_new_style_classes", "tests/pyupgrade_test.py::test_py36_plus_fstrings" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2019-03-16 22:46:26+00:00
mit
1,130
asottile__pyupgrade-120
diff --git a/pyupgrade.py b/pyupgrade.py index a9c6cd5..0dcc2e0 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -490,6 +490,10 @@ def _fix_octal(s): return '0o' + s[1:] +def _is_string_prefix(token): + return token.name == 'NAME' and set(token.src.lower()) <= set('bfru') + + def _fix_tokens(contents_text, py3_plus): remove_u_prefix = py3_plus or _imports_unicode_literals(contents_text) @@ -503,7 +507,7 @@ def _fix_tokens(contents_text, py3_plus): elif token.name == 'STRING': # when a string prefix is not recognized, the tokenizer produces a # NAME token followed by a STRING token - if i > 0 and tokens[i - 1].name == 'NAME': + if i > 0 and _is_string_prefix(tokens[i - 1]): tokens[i] = token._replace(src=tokens[i - 1].src + token.src) tokens[i - 1] = tokens[i - 1]._replace(src='')
asottile/pyupgrade
0df1eac05c9c37e2bfecf11895aee53a34c33afd
diff --git a/tests/pyupgrade_test.py b/tests/pyupgrade_test.py index 9c6db3d..4c56411 100644 --- a/tests/pyupgrade_test.py +++ b/tests/pyupgrade_test.py @@ -323,6 +323,14 @@ def test_imports_unicode_literals(s, expected): ), # Regression: string containing newline ('"""with newline\n"""', True, '"""with newline\n"""'), + pytest.param( + 'def f():\n' + ' return"foo"\n', + True, + 'def f():\n' + ' return"foo"\n', + id='Regression: no space between return and string', + ), ), ) def test_unicode_literals(s, py3_plus, expected):
unicode literal fixer `return'foo'` Mistakenly does the following: ```diff - return'foo' + retrn'foo' ```
0.0
0df1eac05c9c37e2bfecf11895aee53a34c33afd
[ "tests/pyupgrade_test.py::test_unicode_literals[Regression:" ]
[ "tests/pyupgrade_test.py::test_roundtrip_text[]", "tests/pyupgrade_test.py::test_roundtrip_text[foo]", "tests/pyupgrade_test.py::test_roundtrip_text[{}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0}]", "tests/pyupgrade_test.py::test_roundtrip_text[{named}]", "tests/pyupgrade_test.py::test_roundtrip_text[{!r}]", "tests/pyupgrade_test.py::test_roundtrip_text[{:>5}]", "tests/pyupgrade_test.py::test_roundtrip_text[{{]", "tests/pyupgrade_test.py::test_roundtrip_text[}}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0!s:15}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/pyupgrade_test.py::test_sets[set()-set()]", "tests/pyupgrade_test.py::test_sets[set((\\n))-set((\\n))]", "tests/pyupgrade_test.py::test_sets[set", "tests/pyupgrade_test.py::test_sets[set(())-set()]", "tests/pyupgrade_test.py::test_sets[set([])-set()]", "tests/pyupgrade_test.py::test_sets[set((", "tests/pyupgrade_test.py::test_sets[set((1,", "tests/pyupgrade_test.py::test_sets[set([1,", "tests/pyupgrade_test.py::test_sets[set(x", "tests/pyupgrade_test.py::test_sets[set([x", "tests/pyupgrade_test.py::test_sets[set((x", "tests/pyupgrade_test.py::test_sets[set(((1,", "tests/pyupgrade_test.py::test_sets[set((a,", "tests/pyupgrade_test.py::test_sets[set([(1,", "tests/pyupgrade_test.py::test_sets[set(\\n", "tests/pyupgrade_test.py::test_sets[set([((1,", "tests/pyupgrade_test.py::test_sets[set((((1,", "tests/pyupgrade_test.py::test_sets[set(\\n(1,", "tests/pyupgrade_test.py::test_sets[set((\\n1,\\n2,\\n))\\n-{\\n1,\\n2,\\n}\\n]", "tests/pyupgrade_test.py::test_sets[set((frozenset(set((1,", "tests/pyupgrade_test.py::test_sets[set((1,))-{1}]", "tests/pyupgrade_test.py::test_dictcomps[x", "tests/pyupgrade_test.py::test_dictcomps[dict()-dict()]", "tests/pyupgrade_test.py::test_dictcomps[(-(]", "tests/pyupgrade_test.py::test_dictcomps[dict", "tests/pyupgrade_test.py::test_dictcomps[dict((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([(a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a),", "tests/pyupgrade_test.py::test_dictcomps[dict((k,", "tests/pyupgrade_test.py::test_dictcomps[dict(\\n", "tests/pyupgrade_test.py::test_dictcomps[x(\\n", "tests/pyupgrade_test.py::test_format_literals[\"{0}\"format(1)-\"{0}\"format(1)]", "tests/pyupgrade_test.py::test_format_literals['{}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{'.format(1)-'{'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['}'.format(1)-'}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals[x", "tests/pyupgrade_test.py::test_format_literals['{0}", "tests/pyupgrade_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{0:x}'.format(30)-'{:x}'.format(30)]", "tests/pyupgrade_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/pyupgrade_test.py::test_format_literals['{0}'", "tests/pyupgrade_test.py::test_format_literals[print(\\n", "tests/pyupgrade_test.py::test_format_literals['{0:<{1}}'.format(1,", "tests/pyupgrade_test.py::test_imports_unicode_literals[import", "tests/pyupgrade_test.py::test_imports_unicode_literals[from", "tests/pyupgrade_test.py::test_imports_unicode_literals[x", "tests/pyupgrade_test.py::test_imports_unicode_literals[\"\"\"docstring\"\"\"\\nfrom", "tests/pyupgrade_test.py::test_unicode_literals[(-False-(]", "tests/pyupgrade_test.py::test_unicode_literals[u''-False-u'']", "tests/pyupgrade_test.py::test_unicode_literals[u''-True-'']", "tests/pyupgrade_test.py::test_unicode_literals[from", "tests/pyupgrade_test.py::test_unicode_literals[\"\"\"with", "tests/pyupgrade_test.py::test_fix_ur_literals[basic", "tests/pyupgrade_test.py::test_fix_ur_literals[upper", "tests/pyupgrade_test.py::test_fix_ur_literals[with", "tests/pyupgrade_test.py::test_fix_ur_literals[emoji]", "tests/pyupgrade_test.py::test_fix_ur_literals_gets_fixed_before_u_removed", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'\\\\d']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\"\"\\\\d\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'''\\\\d''']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[rb\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\r\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\d\"-r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\n\\\\d\"-\"\\\\n\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[u\"\\\\d\"-u\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\d\"-br\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\8\"-r\"\\\\8\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\9\"-r\"\\\\9\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\u2603\"-br\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\n\\\\q\"\"\"-\"\"\"\\\\\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\n\\\\q\"\"\"-\"\"\"\\\\\\r\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\\\q\"\"\"-\"\"\"\\\\\\r\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_noop_octal_literals[0]", "tests/pyupgrade_test.py::test_noop_octal_literals[00]", "tests/pyupgrade_test.py::test_noop_octal_literals[1]", "tests/pyupgrade_test.py::test_noop_octal_literals[12345]", "tests/pyupgrade_test.py::test_noop_octal_literals[1.2345]", "tests/pyupgrade_test.py::test_is_bytestring_true[b'']", "tests/pyupgrade_test.py::test_is_bytestring_true[b\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B'']", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''0]", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''1]", "tests/pyupgrade_test.py::test_is_bytestring_false[]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false['']", "tests/pyupgrade_test.py::test_is_bytestring_false[u\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"b\"]", "tests/pyupgrade_test.py::test_parse_percent_format[\"\"-expected0]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%%\"-expected1]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s\"-expected2]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(hi)s\"-expected4]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%()s\"-expected5]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%#o\"-expected6]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%", "tests/pyupgrade_test.py::test_parse_percent_format[\"%5d\"-expected8]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%*d\"-expected9]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.f\"-expected10]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.5f\"-expected11]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.*f\"-expected12]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%ld\"-expected13]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(complete)#4.4f\"-expected14]", "tests/pyupgrade_test.py::test_percent_to_format[%s-{}]", "tests/pyupgrade_test.py::test_percent_to_format[%%%s-%{}]", "tests/pyupgrade_test.py::test_percent_to_format[%(foo)s-{foo}]", "tests/pyupgrade_test.py::test_percent_to_format[%2f-{:2f}]", "tests/pyupgrade_test.py::test_percent_to_format[%r-{!r}]", "tests/pyupgrade_test.py::test_percent_to_format[%a-{!a}]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[-]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[", "tests/pyupgrade_test.py::test_simplify_conversion_flag[#0-", "tests/pyupgrade_test.py::test_simplify_conversion_flag[--<]", "tests/pyupgrade_test.py::test_percent_format_noop[\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[b\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%d\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%i\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%u\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%c\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%#o\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%()s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%4%\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2r\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2a\"", "tests/pyupgrade_test.py::test_percent_format_noop[i", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(1)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(a)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(ab)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(and)s\"", "tests/pyupgrade_test.py::test_percent_format[\"trivial\"", "tests/pyupgrade_test.py::test_percent_format[\"%s\"", "tests/pyupgrade_test.py::test_percent_format[\"%s%%", "tests/pyupgrade_test.py::test_percent_format[\"%3f\"", "tests/pyupgrade_test.py::test_percent_format[\"%-5s\"", "tests/pyupgrade_test.py::test_percent_format[\"%9s\"", "tests/pyupgrade_test.py::test_percent_format[\"brace", "tests/pyupgrade_test.py::test_percent_format[\"%(k)s\"", "tests/pyupgrade_test.py::test_percent_format[\"%(to_list)s\"", "tests/pyupgrade_test.py::test_fix_super_noop[x(]", "tests/pyupgrade_test.py::test_fix_super_noop[class", "tests/pyupgrade_test.py::test_fix_super_noop[def", "tests/pyupgrade_test.py::test_fix_super[class", "tests/pyupgrade_test.py::test_fix_new_style_classes_noop[x", "tests/pyupgrade_test.py::test_fix_new_style_classes_noop[class", "tests/pyupgrade_test.py::test_fix_new_style_classes[class", "tests/pyupgrade_test.py::test_fix_six_noop[x", "tests/pyupgrade_test.py::test_fix_six_noop[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six_noop[@", "tests/pyupgrade_test.py::test_fix_six_noop[from", "tests/pyupgrade_test.py::test_fix_six_noop[@mydec\\nclass", "tests/pyupgrade_test.py::test_fix_six_noop[six.u", "tests/pyupgrade_test.py::test_fix_six_noop[six.raise_from", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six[issubclass(tp,", "tests/pyupgrade_test.py::test_fix_six[STRING_TYPES", "tests/pyupgrade_test.py::test_fix_six[from", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/pyupgrade_test.py::test_fix_six[six.get_unbound_method(meth)\\n-meth\\n]", "tests/pyupgrade_test.py::test_fix_six[six.indexbytes(bs,", "tests/pyupgrade_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/pyupgrade_test.py::test_fix_six[six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(tp,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(\\n", "tests/pyupgrade_test.py::test_fix_new_style_classes_py3only[class", "tests/pyupgrade_test.py::test_fix_fstrings_noop[(]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\"", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{foo}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{0}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[b\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{1}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{.x}", "tests/pyupgrade_test.py::test_fix_fstrings[\"hello", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped,", "tests/pyupgrade_test.py::test_main_trivial", "tests/pyupgrade_test.py::test_main_noop", "tests/pyupgrade_test.py::test_main_changes_a_file", "tests/pyupgrade_test.py::test_main_keeps_line_endings", "tests/pyupgrade_test.py::test_main_syntax_error", "tests/pyupgrade_test.py::test_main_non_utf8_bytes", "tests/pyupgrade_test.py::test_keep_percent_format", "tests/pyupgrade_test.py::test_py3_plus_argument_unicode_literals", "tests/pyupgrade_test.py::test_py3_plus_super", "tests/pyupgrade_test.py::test_py3_plus_new_style_classes", "tests/pyupgrade_test.py::test_py36_plus_fstrings" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2019-03-21 00:59:46+00:00
mit
1,131
asottile__pyupgrade-125
diff --git a/README.md b/README.md index d7d5e9c..dff27e7 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,17 @@ u'\d' # u'\\d' # but in python3.x, that's our friend ☃ ``` +### `is` / `is not` comparison to constant literals + +In python3.8+, comparison to literals becomes a `SyntaxWarning` as the success +of those comparisons is implementation specific (due to common object caching). + +```python +x is 5 # x == 5 +x is not 5 # x != 5 +x is 'foo' # x == foo +``` + ### `ur` string literals `ur'...'` literals are not valid in python 3.x diff --git a/pyupgrade.py b/pyupgrade.py index 221c87f..b67cbf7 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -324,13 +324,34 @@ def _process_dict_comp(tokens, start, arg): tokens[start:start + 2] = [Token('OP', '{')] -class FindDictsSetsVisitor(ast.NodeVisitor): - def __init__(self): +def _process_is_literal(tokens, i, compare): + while tokens[i].src != 'is': + i -= 1 + if isinstance(compare, ast.Is): + tokens[i] = tokens[i]._replace(src='==') + else: + tokens[i] = tokens[i]._replace(src='!=') + # since we iterate backward, the dummy tokens keep the same length + i += 1 + while tokens[i].src != 'not': + tokens[i] = Token('DUMMY', '') + i += 1 + tokens[i] = Token('DUMMY', '') + + +LITERAL_TYPES = (ast.Str, ast.Num) +if sys.version_info >= (3,): # pragma: no cover (py3+) + LITERAL_TYPES += (ast.Bytes,) + + +class Py2CompatibleVisitor(ast.NodeVisitor): + def __init__(self): # type: () -> None self.dicts = {} self.sets = {} self.set_empty_literals = {} + self.is_literal = {} - def visit_Call(self, node): + def visit_Call(self, node): # type: (ast.AST) -> None if ( isinstance(node.func, ast.Name) and node.func.id == 'set' and @@ -357,15 +378,35 @@ class FindDictsSetsVisitor(ast.NodeVisitor): self.dicts[_ast_to_offset(node.func)] = arg self.generic_visit(node) + def visit_Compare(self, node): # type: (ast.AST) -> None + left = node.left + for op, right in zip(node.ops, node.comparators): + if ( + isinstance(op, (ast.Is, ast.IsNot)) and + ( + isinstance(left, LITERAL_TYPES) or + isinstance(right, LITERAL_TYPES) + ) + ): + self.is_literal[_ast_to_offset(right)] = op + left = right -def _fix_dict_set(contents_text): + self.generic_visit(node) + + +def _fix_py2_compatible(contents_text): try: ast_obj = ast_parse(contents_text) except SyntaxError: return contents_text - visitor = FindDictsSetsVisitor() + visitor = Py2CompatibleVisitor() visitor.visit(ast_obj) - if not any((visitor.dicts, visitor.sets, visitor.set_empty_literals)): + if not any(( + visitor.dicts, + visitor.sets, + visitor.set_empty_literals, + visitor.is_literal, + )): return contents_text tokens = src_to_tokens(contents_text) @@ -376,6 +417,8 @@ def _fix_dict_set(contents_text): _process_set_empty_literal(tokens, i) elif token.offset in visitor.sets: _process_set_literal(tokens, i, visitor.sets[token.offset]) + elif token.offset in visitor.is_literal: + _process_is_literal(tokens, i, visitor.is_literal[token.offset]) return tokens_to_src(tokens) @@ -1401,7 +1444,7 @@ def fix_file(filename, args): print('{} is non-utf-8 (not supported)'.format(filename)) return 1 - contents_text = _fix_dict_set(contents_text) + contents_text = _fix_py2_compatible(contents_text) contents_text = _fix_format_literals(contents_text) contents_text = _fix_tokens(contents_text, args.py3_plus) if not args.keep_percent_format:
asottile/pyupgrade
6a991655df104322aa5e650f34fde0a031d0f788
diff --git a/tests/pyupgrade_test.py b/tests/pyupgrade_test.py index 8282b62..9ab97d3 100644 --- a/tests/pyupgrade_test.py +++ b/tests/pyupgrade_test.py @@ -7,10 +7,10 @@ import sys import pytest -from pyupgrade import _fix_dict_set from pyupgrade import _fix_format_literals from pyupgrade import _fix_fstrings from pyupgrade import _fix_percent_format +from pyupgrade import _fix_py2_compatible from pyupgrade import _fix_six_and_classes from pyupgrade import _fix_super from pyupgrade import _fix_tokens @@ -120,7 +120,7 @@ def test_intentionally_not_round_trip(s, expected): ), ) def test_sets(s, expected): - ret = _fix_dict_set(s) + ret = _fix_py2_compatible(s) assert ret == expected @@ -139,8 +139,8 @@ def test_sets(s, expected): ), ), ) -def test_sets_generators_trailing_comas(s, expected): - ret = _fix_dict_set(s) +def test_sets_generators_trailing_commas(s, expected): + ret = _fix_py2_compatible(s) assert ret == expected @@ -216,7 +216,69 @@ def test_sets_generators_trailing_comas(s, expected): ), ) def test_dictcomps(s, expected): - ret = _fix_dict_set(s) + ret = _fix_py2_compatible(s) + assert ret == expected + + [email protected]( + 's', + ( + 'x is True', + 'x is False', + 'x is None', + 'x is (not 5)', + 'x is 5 + 5', + # pyupgrade is timid about containers since the original can be + # always-False, but the rewritten code could be `True`. + 'x is ()', + 'x is []', + 'x is {}', + 'x is {1}', + ), +) +def test_fix_is_compare_to_literal_noop(s): + assert _fix_py2_compatible(s) == s + + [email protected]( + ('s', 'expected'), + ( + pytest.param('x is 5', 'x == 5', id='`is`'), + pytest.param('x is not 5', 'x != 5', id='`is not`'), + pytest.param('x is ""', 'x == ""', id='string'), + pytest.param('x is u""', 'x == u""', id='unicode string'), + pytest.param('x is b""', 'x == b""', id='bytes'), + pytest.param('x is 1.5', 'x == 1.5', id='float'), + pytest.param('x == 5 is 5', 'x == 5 == 5', id='compound compare'), + pytest.param( + 'if (\n' + ' x is\n' + ' 5\n' + '): pass\n', + + 'if (\n' + ' x ==\n' + ' 5\n' + '): pass\n', + + id='multi-line `is`', + ), + pytest.param( + 'if (\n' + ' x is\n' + ' not 5\n' + '): pass\n', + + 'if (\n' + ' x != 5\n' + '): pass\n', + + id='multi-line `is not`', + ), + ), +) +def test_fix_is_compare_to_literal(s, expected): + ret = _fix_py2_compatible(s) assert ret == expected
Fix `is (int, float, bytes, str)` automatically Similar to #47, let's automatically fix this as it becomes a `SyntaxWarning` in python3.8 ```pycon $ python3.8 -Werror Python 3.8.0a3 (default, Mar 27 2019, 03:46:44) [GCC 7.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> x = 5 >>> x is 5 File "<stdin>", line 1 SyntaxError: "is" with a literal. Did you mean "=="? >>> ```
0.0
6a991655df104322aa5e650f34fde0a031d0f788
[ "tests/pyupgrade_test.py::test_roundtrip_text[]", "tests/pyupgrade_test.py::test_roundtrip_text[foo]", "tests/pyupgrade_test.py::test_roundtrip_text[{}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0}]", "tests/pyupgrade_test.py::test_roundtrip_text[{named}]", "tests/pyupgrade_test.py::test_roundtrip_text[{!r}]", "tests/pyupgrade_test.py::test_roundtrip_text[{:>5}]", "tests/pyupgrade_test.py::test_roundtrip_text[{{]", "tests/pyupgrade_test.py::test_roundtrip_text[}}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0!s:15}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/pyupgrade_test.py::test_sets[set()-set()]", "tests/pyupgrade_test.py::test_sets[set((\\n))-set((\\n))]", "tests/pyupgrade_test.py::test_sets[set", "tests/pyupgrade_test.py::test_sets[set(())-set()]", "tests/pyupgrade_test.py::test_sets[set([])-set()]", "tests/pyupgrade_test.py::test_sets[set((", "tests/pyupgrade_test.py::test_sets[set((1,", "tests/pyupgrade_test.py::test_sets[set([1,", "tests/pyupgrade_test.py::test_sets[set(x", "tests/pyupgrade_test.py::test_sets[set([x", "tests/pyupgrade_test.py::test_sets[set((x", "tests/pyupgrade_test.py::test_sets[set(((1,", "tests/pyupgrade_test.py::test_sets[set((a,", "tests/pyupgrade_test.py::test_sets[set([(1,", "tests/pyupgrade_test.py::test_sets[set(\\n", "tests/pyupgrade_test.py::test_sets[set([((1,", "tests/pyupgrade_test.py::test_sets[set((((1,", "tests/pyupgrade_test.py::test_sets[set(\\n(1,", "tests/pyupgrade_test.py::test_sets[set((\\n1,\\n2,\\n))\\n-{\\n1,\\n2,\\n}\\n]", "tests/pyupgrade_test.py::test_sets[set((frozenset(set((1,", "tests/pyupgrade_test.py::test_sets[set((1,))-{1}]", "tests/pyupgrade_test.py::test_dictcomps[x", "tests/pyupgrade_test.py::test_dictcomps[dict()-dict()]", "tests/pyupgrade_test.py::test_dictcomps[(-(]", "tests/pyupgrade_test.py::test_dictcomps[dict", "tests/pyupgrade_test.py::test_dictcomps[dict((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([(a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a),", "tests/pyupgrade_test.py::test_dictcomps[dict((k,", "tests/pyupgrade_test.py::test_dictcomps[dict(\\n", "tests/pyupgrade_test.py::test_dictcomps[x(\\n", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal_noop[x", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is`]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[string]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[unicode", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[bytes]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[float]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[compound", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[multi-line", "tests/pyupgrade_test.py::test_format_literals[\"{0}\"format(1)-\"{0}\"format(1)]", "tests/pyupgrade_test.py::test_format_literals['{}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{'.format(1)-'{'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['}'.format(1)-'}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals[x", "tests/pyupgrade_test.py::test_format_literals['{0}", "tests/pyupgrade_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{0:x}'.format(30)-'{:x}'.format(30)]", "tests/pyupgrade_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/pyupgrade_test.py::test_format_literals['{0}'", "tests/pyupgrade_test.py::test_format_literals[print(\\n", "tests/pyupgrade_test.py::test_format_literals['{0:<{1}}'.format(1,", "tests/pyupgrade_test.py::test_imports_unicode_literals[import", "tests/pyupgrade_test.py::test_imports_unicode_literals[from", "tests/pyupgrade_test.py::test_imports_unicode_literals[x", "tests/pyupgrade_test.py::test_imports_unicode_literals[\"\"\"docstring\"\"\"\\nfrom", "tests/pyupgrade_test.py::test_unicode_literals[(-False-(]", "tests/pyupgrade_test.py::test_unicode_literals[u''-False-u'']", "tests/pyupgrade_test.py::test_unicode_literals[u''-True-'']", "tests/pyupgrade_test.py::test_unicode_literals[from", "tests/pyupgrade_test.py::test_unicode_literals[\"\"\"with", "tests/pyupgrade_test.py::test_unicode_literals[Regression:", "tests/pyupgrade_test.py::test_fix_ur_literals[basic", "tests/pyupgrade_test.py::test_fix_ur_literals[upper", "tests/pyupgrade_test.py::test_fix_ur_literals[with", "tests/pyupgrade_test.py::test_fix_ur_literals[emoji]", "tests/pyupgrade_test.py::test_fix_ur_literals_gets_fixed_before_u_removed", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'\\\\d']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\"\"\\\\d\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'''\\\\d''']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[rb\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\r\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\d\"-r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\n\\\\d\"-\"\\\\n\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[u\"\\\\d\"-u\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\d\"-br\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\8\"-r\"\\\\8\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\9\"-r\"\\\\9\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\u2603\"-br\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\n\\\\q\"\"\"-\"\"\"\\\\\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\n\\\\q\"\"\"-\"\"\"\\\\\\r\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\\\q\"\"\"-\"\"\"\\\\\\r\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_noop_octal_literals[0]", "tests/pyupgrade_test.py::test_noop_octal_literals[00]", "tests/pyupgrade_test.py::test_noop_octal_literals[1]", "tests/pyupgrade_test.py::test_noop_octal_literals[12345]", "tests/pyupgrade_test.py::test_noop_octal_literals[1.2345]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((1,", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(())]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((\\n))]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[sum((block.code", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"foo{}\".format(1)))-print(\"foo{}\".format(1))]", "tests/pyupgrade_test.py::test_fix_extra_parens[print((((1))))-print(1)]", "tests/pyupgrade_test.py::test_fix_extra_parens[print(\\n", "tests/pyupgrade_test.py::test_is_bytestring_true[b'']", "tests/pyupgrade_test.py::test_is_bytestring_true[b\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B'']", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''0]", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''1]", "tests/pyupgrade_test.py::test_is_bytestring_false[]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false['']", "tests/pyupgrade_test.py::test_is_bytestring_false[u\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"b\"]", "tests/pyupgrade_test.py::test_parse_percent_format[\"\"-expected0]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%%\"-expected1]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s\"-expected2]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(hi)s\"-expected4]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%()s\"-expected5]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%#o\"-expected6]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%", "tests/pyupgrade_test.py::test_parse_percent_format[\"%5d\"-expected8]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%*d\"-expected9]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.f\"-expected10]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.5f\"-expected11]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.*f\"-expected12]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%ld\"-expected13]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(complete)#4.4f\"-expected14]", "tests/pyupgrade_test.py::test_percent_to_format[%s-{}]", "tests/pyupgrade_test.py::test_percent_to_format[%%%s-%{}]", "tests/pyupgrade_test.py::test_percent_to_format[%(foo)s-{foo}]", "tests/pyupgrade_test.py::test_percent_to_format[%2f-{:2f}]", "tests/pyupgrade_test.py::test_percent_to_format[%r-{!r}]", "tests/pyupgrade_test.py::test_percent_to_format[%a-{!a}]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[-]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[", "tests/pyupgrade_test.py::test_simplify_conversion_flag[#0-", "tests/pyupgrade_test.py::test_simplify_conversion_flag[--<]", "tests/pyupgrade_test.py::test_percent_format_noop[\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[b\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%d\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%i\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%u\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%c\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%#o\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%()s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%4%\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2r\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2a\"", "tests/pyupgrade_test.py::test_percent_format_noop[i", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(1)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(a)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(ab)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(and)s\"", "tests/pyupgrade_test.py::test_percent_format[\"trivial\"", "tests/pyupgrade_test.py::test_percent_format[\"%s\"", "tests/pyupgrade_test.py::test_percent_format[\"%s%%", "tests/pyupgrade_test.py::test_percent_format[\"%3f\"", "tests/pyupgrade_test.py::test_percent_format[\"%-5s\"", "tests/pyupgrade_test.py::test_percent_format[\"%9s\"", "tests/pyupgrade_test.py::test_percent_format[\"brace", "tests/pyupgrade_test.py::test_percent_format[\"%(k)s\"", "tests/pyupgrade_test.py::test_percent_format[\"%(to_list)s\"", "tests/pyupgrade_test.py::test_fix_super_noop[x(]", "tests/pyupgrade_test.py::test_fix_super_noop[class", "tests/pyupgrade_test.py::test_fix_super_noop[def", "tests/pyupgrade_test.py::test_fix_super[class", "tests/pyupgrade_test.py::test_fix_classes_noop[x", "tests/pyupgrade_test.py::test_fix_classes_noop[class", "tests/pyupgrade_test.py::test_fix_classes[class", "tests/pyupgrade_test.py::test_fix_classes[import", "tests/pyupgrade_test.py::test_fix_classes[from", "tests/pyupgrade_test.py::test_fix_six_noop[x", "tests/pyupgrade_test.py::test_fix_six_noop[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six_noop[@", "tests/pyupgrade_test.py::test_fix_six_noop[from", "tests/pyupgrade_test.py::test_fix_six_noop[@mydec\\nclass", "tests/pyupgrade_test.py::test_fix_six_noop[six.u", "tests/pyupgrade_test.py::test_fix_six_noop[six.raise_from", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(\"\\xa3\"))]", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(", "tests/pyupgrade_test.py::test_fix_six[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six[from", "tests/pyupgrade_test.py::test_fix_six[issubclass(tp,", "tests/pyupgrade_test.py::test_fix_six[STRING_TYPES", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/pyupgrade_test.py::test_fix_six[six.get_unbound_method(meth)\\n-meth\\n]", "tests/pyupgrade_test.py::test_fix_six[six.indexbytes(bs,", "tests/pyupgrade_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/pyupgrade_test.py::test_fix_six[six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(tp,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(\\n", "tests/pyupgrade_test.py::test_fix_classes_py3only[class", "tests/pyupgrade_test.py::test_fix_classes_py3only[from", "tests/pyupgrade_test.py::test_fix_fstrings_noop[(]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\"", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{foo}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{0}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[b\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{1}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{.x}", "tests/pyupgrade_test.py::test_fix_fstrings[\"hello", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped,", "tests/pyupgrade_test.py::test_main_trivial", "tests/pyupgrade_test.py::test_main_noop", "tests/pyupgrade_test.py::test_main_changes_a_file", "tests/pyupgrade_test.py::test_main_keeps_line_endings", "tests/pyupgrade_test.py::test_main_syntax_error", "tests/pyupgrade_test.py::test_main_non_utf8_bytes", "tests/pyupgrade_test.py::test_keep_percent_format", "tests/pyupgrade_test.py::test_py3_plus_argument_unicode_literals", "tests/pyupgrade_test.py::test_py3_plus_super", "tests/pyupgrade_test.py::test_py3_plus_new_style_classes", "tests/pyupgrade_test.py::test_py36_plus_fstrings" ]
[]
{ "failed_lite_validators": [ "has_issue_reference", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-04-13 22:21:57+00:00
mit
1,132
asottile__pyupgrade-133
diff --git a/pyupgrade.py b/pyupgrade.py index d3d7a55..6f2669b 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -914,7 +914,8 @@ SIX_CALLS = { 'assertRegex': '{args[0]}.assertRegex({rest})', } SIX_B_TMPL = 'b{args[0]}' -WITH_METACLASS_TMPL = '{rest}, metaclass={args[0]}' +WITH_METACLASS_NO_BASES_TMPL = 'metaclass={args[0]}' +WITH_METACLASS_BASES_TMPL = '{rest}, metaclass={args[0]}' SIX_RAISES = { 'raise_from': 'raise {args[0]} from {rest}', 'reraise': 'raise {args[1]}.with_traceback({args[2]})', @@ -1221,7 +1222,11 @@ def _fix_py3_plus(contents_text): elif token.offset in visitor.six_with_metaclass: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j) - _replace_call(tokens, i, end, func_args, WITH_METACLASS_TMPL) + if len(func_args) == 1: + tmpl = WITH_METACLASS_NO_BASES_TMPL + else: + tmpl = WITH_METACLASS_BASES_TMPL + _replace_call(tokens, i, end, func_args, tmpl) elif token.offset in visitor.super_calls: i = _find_open_paren(tokens, i) call = visitor.super_calls[token.offset]
asottile/pyupgrade
e19a16efb0f001f55fc96529199d498814016e30
diff --git a/tests/pyupgrade_test.py b/tests/pyupgrade_test.py index 773ac80..b6988d7 100644 --- a/tests/pyupgrade_test.py +++ b/tests/pyupgrade_test.py @@ -1280,6 +1280,11 @@ def test_fix_six_noop(s): 'from six import raise_from\nraise exc from exc_from', id='weird spacing raise_from', ), + ( + 'class C(six.with_metaclass(M)): pass', + + 'class C(metaclass=M): pass', + ), ( 'class C(six.with_metaclass(M, B)): pass',
Syntax errors created when removing with_metaclass Code such as ``` class EventProcessorMeta(six.with_metaclass(abc.ABCMeta)): ``` is being rewritten as invalid Python ``` class EventProcessorMeta(, metaclass=abc.ABCMeta): ```
0.0
e19a16efb0f001f55fc96529199d498814016e30
[ "tests/pyupgrade_test.py::test_fix_six[class" ]
[ "tests/pyupgrade_test.py::test_roundtrip_text[]", "tests/pyupgrade_test.py::test_roundtrip_text[foo]", "tests/pyupgrade_test.py::test_roundtrip_text[{}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0}]", "tests/pyupgrade_test.py::test_roundtrip_text[{named}]", "tests/pyupgrade_test.py::test_roundtrip_text[{!r}]", "tests/pyupgrade_test.py::test_roundtrip_text[{:>5}]", "tests/pyupgrade_test.py::test_roundtrip_text[{{]", "tests/pyupgrade_test.py::test_roundtrip_text[}}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0!s:15}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/pyupgrade_test.py::test_sets[set()-set()]", "tests/pyupgrade_test.py::test_sets[set((\\n))-set((\\n))]", "tests/pyupgrade_test.py::test_sets[set", "tests/pyupgrade_test.py::test_sets[set(())-set()]", "tests/pyupgrade_test.py::test_sets[set([])-set()]", "tests/pyupgrade_test.py::test_sets[set((", "tests/pyupgrade_test.py::test_sets[set((1,", "tests/pyupgrade_test.py::test_sets[set([1,", "tests/pyupgrade_test.py::test_sets[set(x", "tests/pyupgrade_test.py::test_sets[set([x", "tests/pyupgrade_test.py::test_sets[set((x", "tests/pyupgrade_test.py::test_sets[set(((1,", "tests/pyupgrade_test.py::test_sets[set((a,", "tests/pyupgrade_test.py::test_sets[set([(1,", "tests/pyupgrade_test.py::test_sets[set(\\n", "tests/pyupgrade_test.py::test_sets[set([((1,", "tests/pyupgrade_test.py::test_sets[set((((1,", "tests/pyupgrade_test.py::test_sets[set(\\n(1,", "tests/pyupgrade_test.py::test_sets[set((\\n1,\\n2,\\n))\\n-{\\n1,\\n2,\\n}\\n]", "tests/pyupgrade_test.py::test_sets[set((frozenset(set((1,", "tests/pyupgrade_test.py::test_sets[set((1,))-{1}]", "tests/pyupgrade_test.py::test_dictcomps[x", "tests/pyupgrade_test.py::test_dictcomps[dict()-dict()]", "tests/pyupgrade_test.py::test_dictcomps[(-(]", "tests/pyupgrade_test.py::test_dictcomps[dict", "tests/pyupgrade_test.py::test_dictcomps[dict((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([(a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a),", "tests/pyupgrade_test.py::test_dictcomps[dict((k,", "tests/pyupgrade_test.py::test_dictcomps[dict(\\n", "tests/pyupgrade_test.py::test_dictcomps[x(\\n", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal_noop[x", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is`]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[string]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[unicode", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[bytes]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[float]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[compound", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[multi-line", "tests/pyupgrade_test.py::test_format_literals[\"{0}\"format(1)-\"{0}\"format(1)]", "tests/pyupgrade_test.py::test_format_literals['{}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{'.format(1)-'{'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['}'.format(1)-'}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals[x", "tests/pyupgrade_test.py::test_format_literals['{0}", "tests/pyupgrade_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{0:x}'.format(30)-'{:x}'.format(30)]", "tests/pyupgrade_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/pyupgrade_test.py::test_format_literals['{0}'", "tests/pyupgrade_test.py::test_format_literals[print(\\n", "tests/pyupgrade_test.py::test_format_literals['{0:<{1}}'.format(1,", "tests/pyupgrade_test.py::test_imports_unicode_literals[import", "tests/pyupgrade_test.py::test_imports_unicode_literals[from", "tests/pyupgrade_test.py::test_imports_unicode_literals[x", "tests/pyupgrade_test.py::test_imports_unicode_literals[\"\"\"docstring\"\"\"\\nfrom", "tests/pyupgrade_test.py::test_unicode_literals[(-False-(]", "tests/pyupgrade_test.py::test_unicode_literals[u''-False-u'']", "tests/pyupgrade_test.py::test_unicode_literals[u''-True-'']", "tests/pyupgrade_test.py::test_unicode_literals[from", "tests/pyupgrade_test.py::test_unicode_literals[\"\"\"with", "tests/pyupgrade_test.py::test_unicode_literals[Regression:", "tests/pyupgrade_test.py::test_fix_ur_literals[basic", "tests/pyupgrade_test.py::test_fix_ur_literals[upper", "tests/pyupgrade_test.py::test_fix_ur_literals[with", "tests/pyupgrade_test.py::test_fix_ur_literals[emoji]", "tests/pyupgrade_test.py::test_fix_ur_literals_gets_fixed_before_u_removed", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'\\\\d']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\"\"\\\\d\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'''\\\\d''']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[rb\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\r\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\d\"-r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\n\\\\d\"-\"\\\\n\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[u\"\\\\d\"-u\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\d\"-br\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\8\"-r\"\\\\8\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\9\"-r\"\\\\9\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\u2603\"-br\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\n\\\\q\"\"\"-\"\"\"\\\\\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\n\\\\q\"\"\"-\"\"\"\\\\\\r\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\\\q\"\"\"-\"\"\"\\\\\\r\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_noop_octal_literals[0]", "tests/pyupgrade_test.py::test_noop_octal_literals[00]", "tests/pyupgrade_test.py::test_noop_octal_literals[1]", "tests/pyupgrade_test.py::test_noop_octal_literals[12345]", "tests/pyupgrade_test.py::test_noop_octal_literals[1.2345]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((1,", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(())]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((\\n))]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[sum((block.code", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[def", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"foo{}\".format(1)))-print(\"foo{}\".format(1))]", "tests/pyupgrade_test.py::test_fix_extra_parens[print((((1))))-print(1)]", "tests/pyupgrade_test.py::test_fix_extra_parens[print(\\n", "tests/pyupgrade_test.py::test_fix_extra_parens[extra", "tests/pyupgrade_test.py::test_is_bytestring_true[b'']", "tests/pyupgrade_test.py::test_is_bytestring_true[b\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B'']", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''0]", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''1]", "tests/pyupgrade_test.py::test_is_bytestring_false[]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false['']", "tests/pyupgrade_test.py::test_is_bytestring_false[u\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"b\"]", "tests/pyupgrade_test.py::test_parse_percent_format[\"\"-expected0]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%%\"-expected1]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s\"-expected2]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(hi)s\"-expected4]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%()s\"-expected5]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%#o\"-expected6]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%", "tests/pyupgrade_test.py::test_parse_percent_format[\"%5d\"-expected8]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%*d\"-expected9]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.f\"-expected10]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.5f\"-expected11]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.*f\"-expected12]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%ld\"-expected13]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(complete)#4.4f\"-expected14]", "tests/pyupgrade_test.py::test_percent_to_format[%s-{}]", "tests/pyupgrade_test.py::test_percent_to_format[%%%s-%{}]", "tests/pyupgrade_test.py::test_percent_to_format[%(foo)s-{foo}]", "tests/pyupgrade_test.py::test_percent_to_format[%2f-{:2f}]", "tests/pyupgrade_test.py::test_percent_to_format[%r-{!r}]", "tests/pyupgrade_test.py::test_percent_to_format[%a-{!a}]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[-]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[", "tests/pyupgrade_test.py::test_simplify_conversion_flag[#0-", "tests/pyupgrade_test.py::test_simplify_conversion_flag[--<]", "tests/pyupgrade_test.py::test_percent_format_noop[\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[b\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%d\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%i\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%u\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%c\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%#o\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%()s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%4%\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2r\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2a\"", "tests/pyupgrade_test.py::test_percent_format_noop[i", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(1)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(a)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(ab)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(and)s\"", "tests/pyupgrade_test.py::test_percent_format[\"trivial\"", "tests/pyupgrade_test.py::test_percent_format[\"%s\"", "tests/pyupgrade_test.py::test_percent_format[\"%s%%", "tests/pyupgrade_test.py::test_percent_format[\"%3f\"", "tests/pyupgrade_test.py::test_percent_format[\"%-5s\"", "tests/pyupgrade_test.py::test_percent_format[\"%9s\"", "tests/pyupgrade_test.py::test_percent_format[\"brace", "tests/pyupgrade_test.py::test_percent_format[\"%(k)s\"", "tests/pyupgrade_test.py::test_percent_format[\"%(to_list)s\"", "tests/pyupgrade_test.py::test_fix_super_noop[x(]", "tests/pyupgrade_test.py::test_fix_super_noop[class", "tests/pyupgrade_test.py::test_fix_super_noop[def", "tests/pyupgrade_test.py::test_fix_super[class", "tests/pyupgrade_test.py::test_fix_classes_noop[x", "tests/pyupgrade_test.py::test_fix_classes_noop[class", "tests/pyupgrade_test.py::test_fix_classes[class", "tests/pyupgrade_test.py::test_fix_classes[import", "tests/pyupgrade_test.py::test_fix_classes[from", "tests/pyupgrade_test.py::test_fix_six_noop[x", "tests/pyupgrade_test.py::test_fix_six_noop[@", "tests/pyupgrade_test.py::test_fix_six_noop[from", "tests/pyupgrade_test.py::test_fix_six_noop[@mydec\\nclass", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(\"\\xa3\"))]", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(", "tests/pyupgrade_test.py::test_fix_six_noop[class", "tests/pyupgrade_test.py::test_fix_six[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six[weird", "tests/pyupgrade_test.py::test_fix_six[issubclass(tp,", "tests/pyupgrade_test.py::test_fix_six[STRING_TYPES", "tests/pyupgrade_test.py::test_fix_six[from", "tests/pyupgrade_test.py::test_fix_six[six.b(\"123\")-b\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(r\"123\")-br\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(\"\\\\x12\\\\xef\")-b\"\\\\x12\\\\xef\"]", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/pyupgrade_test.py::test_fix_six[six.get_unbound_method(meth)\\n-meth\\n]", "tests/pyupgrade_test.py::test_fix_six[six.indexbytes(bs,", "tests/pyupgrade_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/pyupgrade_test.py::test_fix_six[six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(tp,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(\\n", "tests/pyupgrade_test.py::test_fix_classes_py3only[class", "tests/pyupgrade_test.py::test_fix_classes_py3only[from", "tests/pyupgrade_test.py::test_fix_fstrings_noop[(]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\"", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{foo}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{0}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[b\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{1}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{.x}", "tests/pyupgrade_test.py::test_fix_fstrings[\"hello", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped,", "tests/pyupgrade_test.py::test_main_trivial", "tests/pyupgrade_test.py::test_main_noop", "tests/pyupgrade_test.py::test_main_changes_a_file", "tests/pyupgrade_test.py::test_main_keeps_line_endings", "tests/pyupgrade_test.py::test_main_syntax_error", "tests/pyupgrade_test.py::test_main_non_utf8_bytes", "tests/pyupgrade_test.py::test_keep_percent_format", "tests/pyupgrade_test.py::test_py3_plus_argument_unicode_literals", "tests/pyupgrade_test.py::test_py3_plus_super", "tests/pyupgrade_test.py::test_py3_plus_new_style_classes", "tests/pyupgrade_test.py::test_py36_plus_fstrings" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2019-04-22 19:34:55+00:00
mit
1,133
asottile__pyupgrade-135
diff --git a/pyupgrade.py b/pyupgrade.py index 6f2669b..bf04191 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -1279,6 +1279,9 @@ class FindSimpleFormats(ast.NodeVisitor): # timid: could make the f-string longer if candidate and candidate in seen: break + # timid: bracketed + elif '[' in candidate: + break seen.add(candidate) else: self.found[_ast_to_offset(node)] = node
asottile/pyupgrade
088722a3e5a9062f2173a5185bbb32eb466ac62e
diff --git a/tests/pyupgrade_test.py b/tests/pyupgrade_test.py index b6988d7..dbf747a 100644 --- a/tests/pyupgrade_test.py +++ b/tests/pyupgrade_test.py @@ -1366,6 +1366,7 @@ def test_fix_classes_py3only(s, expected): 'b"{} {}".format(a, b)', # for now, too difficult to rewrite correctly '"{:{}}".format(x, y)', + '"{a[b]}".format(a=a)', ), ) def test_fix_fstrings_noop(s):
Doesn't handle indexed format strings The following code which I tried to reduce (which I had no idea was possible): ```python thing = {'a': 1, 'b': 2} print('{0[a]} and {0[b]}'.format(thing)) ``` leads to ``` Traceback (most recent call last): File "/home/ethan/venv/bin/pyupgrade", line 10, in <module> sys.exit(main()) File "/home/ethan/venv/lib/python3.7/site-packages/pyupgrade.py", line 1396, in main ret |= fix_file(filename, args) File "/home/ethan/venv/lib/python3.7/site-packages/pyupgrade.py", line 1372, in fix_file contents_text = _fix_fstrings(contents_text) File "/home/ethan/venv/lib/python3.7/site-packages/pyupgrade.py", line 1348, in _fix_fstrings tokens[i] = token._replace(src=_to_fstring(token.src, node)) File "/home/ethan/venv/lib/python3.7/site-packages/pyupgrade.py", line 1310, in _to_fstring name = ''.join((params[k or str(i)], dot, rest)) KeyError: '0[a]' ``` This is a very esoteric format string usage, but 🤷‍♂️
0.0
088722a3e5a9062f2173a5185bbb32eb466ac62e
[ "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]" ]
[ "tests/pyupgrade_test.py::test_roundtrip_text[]", "tests/pyupgrade_test.py::test_roundtrip_text[foo]", "tests/pyupgrade_test.py::test_roundtrip_text[{}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0}]", "tests/pyupgrade_test.py::test_roundtrip_text[{named}]", "tests/pyupgrade_test.py::test_roundtrip_text[{!r}]", "tests/pyupgrade_test.py::test_roundtrip_text[{:>5}]", "tests/pyupgrade_test.py::test_roundtrip_text[{{]", "tests/pyupgrade_test.py::test_roundtrip_text[}}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0!s:15}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/pyupgrade_test.py::test_sets[set()-set()]", "tests/pyupgrade_test.py::test_sets[set((\\n))-set((\\n))]", "tests/pyupgrade_test.py::test_sets[set", "tests/pyupgrade_test.py::test_sets[set(())-set()]", "tests/pyupgrade_test.py::test_sets[set([])-set()]", "tests/pyupgrade_test.py::test_sets[set((", "tests/pyupgrade_test.py::test_sets[set((1,", "tests/pyupgrade_test.py::test_sets[set([1,", "tests/pyupgrade_test.py::test_sets[set(x", "tests/pyupgrade_test.py::test_sets[set([x", "tests/pyupgrade_test.py::test_sets[set((x", "tests/pyupgrade_test.py::test_sets[set(((1,", "tests/pyupgrade_test.py::test_sets[set((a,", "tests/pyupgrade_test.py::test_sets[set([(1,", "tests/pyupgrade_test.py::test_sets[set(\\n", "tests/pyupgrade_test.py::test_sets[set([((1,", "tests/pyupgrade_test.py::test_sets[set((((1,", "tests/pyupgrade_test.py::test_sets[set(\\n(1,", "tests/pyupgrade_test.py::test_sets[set((\\n1,\\n2,\\n))\\n-{\\n1,\\n2,\\n}\\n]", "tests/pyupgrade_test.py::test_sets[set((frozenset(set((1,", "tests/pyupgrade_test.py::test_sets[set((1,))-{1}]", "tests/pyupgrade_test.py::test_dictcomps[x", "tests/pyupgrade_test.py::test_dictcomps[dict()-dict()]", "tests/pyupgrade_test.py::test_dictcomps[(-(]", "tests/pyupgrade_test.py::test_dictcomps[dict", "tests/pyupgrade_test.py::test_dictcomps[dict((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([(a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a),", "tests/pyupgrade_test.py::test_dictcomps[dict((k,", "tests/pyupgrade_test.py::test_dictcomps[dict(\\n", "tests/pyupgrade_test.py::test_dictcomps[x(\\n", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal_noop[x", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is`]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[string]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[unicode", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[bytes]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[float]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[compound", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[multi-line", "tests/pyupgrade_test.py::test_format_literals[\"{0}\"format(1)-\"{0}\"format(1)]", "tests/pyupgrade_test.py::test_format_literals['{}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{'.format(1)-'{'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['}'.format(1)-'}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals[x", "tests/pyupgrade_test.py::test_format_literals['{0}", "tests/pyupgrade_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{0:x}'.format(30)-'{:x}'.format(30)]", "tests/pyupgrade_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/pyupgrade_test.py::test_format_literals['{0}'", "tests/pyupgrade_test.py::test_format_literals[print(\\n", "tests/pyupgrade_test.py::test_format_literals['{0:<{1}}'.format(1,", "tests/pyupgrade_test.py::test_imports_unicode_literals[import", "tests/pyupgrade_test.py::test_imports_unicode_literals[from", "tests/pyupgrade_test.py::test_imports_unicode_literals[x", "tests/pyupgrade_test.py::test_imports_unicode_literals[\"\"\"docstring\"\"\"\\nfrom", "tests/pyupgrade_test.py::test_unicode_literals[(-False-(]", "tests/pyupgrade_test.py::test_unicode_literals[u''-False-u'']", "tests/pyupgrade_test.py::test_unicode_literals[u''-True-'']", "tests/pyupgrade_test.py::test_unicode_literals[from", "tests/pyupgrade_test.py::test_unicode_literals[\"\"\"with", "tests/pyupgrade_test.py::test_unicode_literals[Regression:", "tests/pyupgrade_test.py::test_fix_ur_literals[basic", "tests/pyupgrade_test.py::test_fix_ur_literals[upper", "tests/pyupgrade_test.py::test_fix_ur_literals[with", "tests/pyupgrade_test.py::test_fix_ur_literals[emoji]", "tests/pyupgrade_test.py::test_fix_ur_literals_gets_fixed_before_u_removed", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'\\\\d']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\"\"\\\\d\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'''\\\\d''']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[rb\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\r\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\d\"-r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\n\\\\d\"-\"\\\\n\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[u\"\\\\d\"-u\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\d\"-br\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\8\"-r\"\\\\8\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\9\"-r\"\\\\9\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\u2603\"-br\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\n\\\\q\"\"\"-\"\"\"\\\\\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\n\\\\q\"\"\"-\"\"\"\\\\\\r\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\\\q\"\"\"-\"\"\"\\\\\\r\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_noop_octal_literals[0]", "tests/pyupgrade_test.py::test_noop_octal_literals[00]", "tests/pyupgrade_test.py::test_noop_octal_literals[1]", "tests/pyupgrade_test.py::test_noop_octal_literals[12345]", "tests/pyupgrade_test.py::test_noop_octal_literals[1.2345]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((1,", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(())]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((\\n))]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[sum((block.code", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[def", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"foo{}\".format(1)))-print(\"foo{}\".format(1))]", "tests/pyupgrade_test.py::test_fix_extra_parens[print((((1))))-print(1)]", "tests/pyupgrade_test.py::test_fix_extra_parens[print(\\n", "tests/pyupgrade_test.py::test_fix_extra_parens[extra", "tests/pyupgrade_test.py::test_is_bytestring_true[b'']", "tests/pyupgrade_test.py::test_is_bytestring_true[b\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B'']", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''0]", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''1]", "tests/pyupgrade_test.py::test_is_bytestring_false[]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false['']", "tests/pyupgrade_test.py::test_is_bytestring_false[u\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"b\"]", "tests/pyupgrade_test.py::test_parse_percent_format[\"\"-expected0]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%%\"-expected1]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s\"-expected2]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(hi)s\"-expected4]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%()s\"-expected5]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%#o\"-expected6]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%", "tests/pyupgrade_test.py::test_parse_percent_format[\"%5d\"-expected8]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%*d\"-expected9]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.f\"-expected10]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.5f\"-expected11]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.*f\"-expected12]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%ld\"-expected13]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(complete)#4.4f\"-expected14]", "tests/pyupgrade_test.py::test_percent_to_format[%s-{}]", "tests/pyupgrade_test.py::test_percent_to_format[%%%s-%{}]", "tests/pyupgrade_test.py::test_percent_to_format[%(foo)s-{foo}]", "tests/pyupgrade_test.py::test_percent_to_format[%2f-{:2f}]", "tests/pyupgrade_test.py::test_percent_to_format[%r-{!r}]", "tests/pyupgrade_test.py::test_percent_to_format[%a-{!a}]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[-]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[", "tests/pyupgrade_test.py::test_simplify_conversion_flag[#0-", "tests/pyupgrade_test.py::test_simplify_conversion_flag[--<]", "tests/pyupgrade_test.py::test_percent_format_noop[\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[b\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%d\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%i\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%u\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%c\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%#o\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%()s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%4%\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2r\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2a\"", "tests/pyupgrade_test.py::test_percent_format_noop[i", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(1)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(a)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(ab)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(and)s\"", "tests/pyupgrade_test.py::test_percent_format[\"trivial\"", "tests/pyupgrade_test.py::test_percent_format[\"%s\"", "tests/pyupgrade_test.py::test_percent_format[\"%s%%", "tests/pyupgrade_test.py::test_percent_format[\"%3f\"", "tests/pyupgrade_test.py::test_percent_format[\"%-5s\"", "tests/pyupgrade_test.py::test_percent_format[\"%9s\"", "tests/pyupgrade_test.py::test_percent_format[\"brace", "tests/pyupgrade_test.py::test_percent_format[\"%(k)s\"", "tests/pyupgrade_test.py::test_percent_format[\"%(to_list)s\"", "tests/pyupgrade_test.py::test_fix_super_noop[x(]", "tests/pyupgrade_test.py::test_fix_super_noop[class", "tests/pyupgrade_test.py::test_fix_super_noop[def", "tests/pyupgrade_test.py::test_fix_super[class", "tests/pyupgrade_test.py::test_fix_classes_noop[x", "tests/pyupgrade_test.py::test_fix_classes_noop[class", "tests/pyupgrade_test.py::test_fix_classes[class", "tests/pyupgrade_test.py::test_fix_classes[import", "tests/pyupgrade_test.py::test_fix_classes[from", "tests/pyupgrade_test.py::test_fix_six_noop[x", "tests/pyupgrade_test.py::test_fix_six_noop[@", "tests/pyupgrade_test.py::test_fix_six_noop[from", "tests/pyupgrade_test.py::test_fix_six_noop[@mydec\\nclass", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(\"\\xa3\"))]", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(", "tests/pyupgrade_test.py::test_fix_six_noop[class", "tests/pyupgrade_test.py::test_fix_six[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six[weird", "tests/pyupgrade_test.py::test_fix_six[issubclass(tp,", "tests/pyupgrade_test.py::test_fix_six[STRING_TYPES", "tests/pyupgrade_test.py::test_fix_six[from", "tests/pyupgrade_test.py::test_fix_six[six.b(\"123\")-b\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(r\"123\")-br\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(\"\\\\x12\\\\xef\")-b\"\\\\x12\\\\xef\"]", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/pyupgrade_test.py::test_fix_six[six.get_unbound_method(meth)\\n-meth\\n]", "tests/pyupgrade_test.py::test_fix_six[six.indexbytes(bs,", "tests/pyupgrade_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/pyupgrade_test.py::test_fix_six[six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(tp,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(\\n", "tests/pyupgrade_test.py::test_fix_six[class", "tests/pyupgrade_test.py::test_fix_classes_py3only[class", "tests/pyupgrade_test.py::test_fix_classes_py3only[from", "tests/pyupgrade_test.py::test_fix_fstrings_noop[(]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\"", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{foo}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{0}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[b\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{1}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{.x}", "tests/pyupgrade_test.py::test_fix_fstrings[\"hello", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped,", "tests/pyupgrade_test.py::test_main_trivial", "tests/pyupgrade_test.py::test_main_noop", "tests/pyupgrade_test.py::test_main_changes_a_file", "tests/pyupgrade_test.py::test_main_keeps_line_endings", "tests/pyupgrade_test.py::test_main_syntax_error", "tests/pyupgrade_test.py::test_main_non_utf8_bytes", "tests/pyupgrade_test.py::test_keep_percent_format", "tests/pyupgrade_test.py::test_py3_plus_argument_unicode_literals", "tests/pyupgrade_test.py::test_py3_plus_super", "tests/pyupgrade_test.py::test_py3_plus_new_style_classes", "tests/pyupgrade_test.py::test_py36_plus_fstrings" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-04-25 23:05:57+00:00
mit
1,134
asottile__pyupgrade-142
diff --git a/README.md b/README.md index 8c379f5..4d842dd 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,9 @@ u'''foo''' # '''foo''' # `ur` is not a valid string prefix in python3 u'\d' # u'\\d' +# this fixes a syntax error in python3.3+ +'\N' # r'\N' + # note: pyupgrade is timid in one case (that's usually a mistake) # in python2.x `'\u2603'` is the same as `'\\u2603'` without `unicode_literals` # but in python3.x, that's our friend ☃ diff --git a/pyupgrade.py b/pyupgrade.py index 2a55816..f1d25ec 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -456,11 +456,9 @@ ESCAPE_STARTS = frozenset(( '\n', '\r', '\\', "'", '"', 'a', 'b', 'f', 'n', 'r', 't', 'v', '0', '1', '2', '3', '4', '5', '6', '7', # octal escapes 'x', # hex escapes - # only valid in non-bytestrings - 'N', 'u', 'U', )) -ESCAPE_STARTS_BYTES = ESCAPE_STARTS - frozenset(('N', 'u', 'U')) ESCAPE_RE = re.compile(r'\\.', re.DOTALL) +NAMED_ESCAPE_NAME = re.compile(r'\{[^}]+\}') def _parse_string_literal(s): @@ -475,18 +473,31 @@ def _fix_escape_sequences(token): if 'r' in actual_prefix or '\\' not in rest: return token - if 'b' in actual_prefix: - valid_escapes = ESCAPE_STARTS_BYTES - else: - valid_escapes = ESCAPE_STARTS + is_bytestring = 'b' in actual_prefix + + def _is_valid_escape(match): + c = match.group()[1] + return ( + c in ESCAPE_STARTS or + (not is_bytestring and c in 'uU') or + ( + not is_bytestring and + c == 'N' and + bool(NAMED_ESCAPE_NAME.match(rest, match.end())) + ) + ) - escape_sequences = {m[1] for m in ESCAPE_RE.findall(rest)} - has_valid_escapes = escape_sequences & valid_escapes - has_invalid_escapes = escape_sequences - valid_escapes + has_valid_escapes = False + has_invalid_escapes = False + for match in ESCAPE_RE.finditer(rest): + if _is_valid_escape(match): + has_valid_escapes = True + else: + has_invalid_escapes = True def cb(match): matched = match.group() - if matched[1] in valid_escapes: + if _is_valid_escape(match): return matched else: return r'\{}'.format(matched)
asottile/pyupgrade
09ab4b1c47f4b1e10d3f12e65c46fb77b47a9fe2
diff --git a/tests/pyupgrade_test.py b/tests/pyupgrade_test.py index fa8edc4..a3f75cb 100644 --- a/tests/pyupgrade_test.py +++ b/tests/pyupgrade_test.py @@ -432,6 +432,8 @@ def test_fix_ur_literals_gets_fixed_before_u_removed(): '"\\u2603"', # don't touch already valid escapes r'"\r\n"', + # python3.3+ named unicode escapes + r'"\N{SNOWMAN}"', # don't touch escaped newlines '"""\\\n"""', '"""\\\r\n"""', '"""\\\r"""', ), @@ -459,6 +461,10 @@ def test_fix_escape_sequences_noop(s): ('"""\\\n\\q"""', '"""\\\n\\\\q"""'), ('"""\\\r\n\\q"""', '"""\\\r\n\\\\q"""'), ('"""\\\r\\q"""', '"""\\\r\\\\q"""'), + # python2.x allows \N, in python3.3+ this is a syntax error + (r'"\N"', r'r"\N"'), (r'"\N\n"', r'"\\N\n"'), + (r'"\N{SNOWMAN}\q"', r'"\N{SNOWMAN}\\q"'), + (r'b"\N{SNOWMAN}"', r'br"\N{SNOWMAN}"'), ), ) def test_fix_escape_sequences(s, expected):
py2-py3 invalid escape sequence: '\N' should get rewritten This is a syntax error in python3.x: ```python '\N' ```
0.0
09ab4b1c47f4b1e10d3f12e65c46fb77b47a9fe2
[ "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N\"-r\"\\\\N\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N\\\\n\"-\"\\\\\\\\N\\\\n\"]" ]
[ "tests/pyupgrade_test.py::test_roundtrip_text[]", "tests/pyupgrade_test.py::test_roundtrip_text[foo]", "tests/pyupgrade_test.py::test_roundtrip_text[{}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0}]", "tests/pyupgrade_test.py::test_roundtrip_text[{named}]", "tests/pyupgrade_test.py::test_roundtrip_text[{!r}]", "tests/pyupgrade_test.py::test_roundtrip_text[{:>5}]", "tests/pyupgrade_test.py::test_roundtrip_text[{{]", "tests/pyupgrade_test.py::test_roundtrip_text[}}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0!s:15}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/pyupgrade_test.py::test_sets[set()-set()]", "tests/pyupgrade_test.py::test_sets[set((\\n))-set((\\n))]", "tests/pyupgrade_test.py::test_sets[set", "tests/pyupgrade_test.py::test_sets[set(())-set()]", "tests/pyupgrade_test.py::test_sets[set([])-set()]", "tests/pyupgrade_test.py::test_sets[set((", "tests/pyupgrade_test.py::test_sets[set((1,", "tests/pyupgrade_test.py::test_sets[set([1,", "tests/pyupgrade_test.py::test_sets[set(x", "tests/pyupgrade_test.py::test_sets[set([x", "tests/pyupgrade_test.py::test_sets[set((x", "tests/pyupgrade_test.py::test_sets[set(((1,", "tests/pyupgrade_test.py::test_sets[set((a,", "tests/pyupgrade_test.py::test_sets[set([(1,", "tests/pyupgrade_test.py::test_sets[set(\\n", "tests/pyupgrade_test.py::test_sets[set([((1,", "tests/pyupgrade_test.py::test_sets[set((((1,", "tests/pyupgrade_test.py::test_sets[set(\\n(1,", "tests/pyupgrade_test.py::test_sets[set((\\n1,\\n2,\\n))\\n-{\\n1,\\n2,\\n}\\n]", "tests/pyupgrade_test.py::test_sets[set((frozenset(set((1,", "tests/pyupgrade_test.py::test_sets[set((1,))-{1}]", "tests/pyupgrade_test.py::test_dictcomps[x", "tests/pyupgrade_test.py::test_dictcomps[dict()-dict()]", "tests/pyupgrade_test.py::test_dictcomps[(-(]", "tests/pyupgrade_test.py::test_dictcomps[dict", "tests/pyupgrade_test.py::test_dictcomps[dict((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([(a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a),", "tests/pyupgrade_test.py::test_dictcomps[dict((k,", "tests/pyupgrade_test.py::test_dictcomps[dict(\\n", "tests/pyupgrade_test.py::test_dictcomps[x(\\n", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal_noop[x", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is`]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[string]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[unicode", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[bytes]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[float]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[compound", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[multi-line", "tests/pyupgrade_test.py::test_format_literals[\"{0}\"format(1)-\"{0}\"format(1)]", "tests/pyupgrade_test.py::test_format_literals['{}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{'.format(1)-'{'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['}'.format(1)-'}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals[x", "tests/pyupgrade_test.py::test_format_literals['{0}", "tests/pyupgrade_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{0:x}'.format(30)-'{:x}'.format(30)]", "tests/pyupgrade_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/pyupgrade_test.py::test_format_literals['{0}'", "tests/pyupgrade_test.py::test_format_literals[print(\\n", "tests/pyupgrade_test.py::test_format_literals['{0:<{1}}'.format(1,", "tests/pyupgrade_test.py::test_imports_unicode_literals[import", "tests/pyupgrade_test.py::test_imports_unicode_literals[from", "tests/pyupgrade_test.py::test_imports_unicode_literals[x", "tests/pyupgrade_test.py::test_imports_unicode_literals[\"\"\"docstring\"\"\"\\nfrom", "tests/pyupgrade_test.py::test_unicode_literals[(-False-(]", "tests/pyupgrade_test.py::test_unicode_literals[u''-False-u'']", "tests/pyupgrade_test.py::test_unicode_literals[u''-True-'']", "tests/pyupgrade_test.py::test_unicode_literals[from", "tests/pyupgrade_test.py::test_unicode_literals[\"\"\"with", "tests/pyupgrade_test.py::test_unicode_literals[Regression:", "tests/pyupgrade_test.py::test_fix_ur_literals[basic", "tests/pyupgrade_test.py::test_fix_ur_literals[upper", "tests/pyupgrade_test.py::test_fix_ur_literals[with", "tests/pyupgrade_test.py::test_fix_ur_literals[emoji]", "tests/pyupgrade_test.py::test_fix_ur_literals_gets_fixed_before_u_removed", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'\\\\d']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\"\"\\\\d\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'''\\\\d''']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[rb\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\r\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\N{SNOWMAN}\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\d\"-r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\n\\\\d\"-\"\\\\n\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[u\"\\\\d\"-u\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\d\"-br\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\8\"-r\"\\\\8\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\9\"-r\"\\\\9\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\u2603\"-br\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\n\\\\q\"\"\"-\"\"\"\\\\\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\n\\\\q\"\"\"-\"\"\"\\\\\\r\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\\\q\"\"\"-\"\"\"\\\\\\r\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N{SNOWMAN}\\\\q\"-\"\\\\N{SNOWMAN}\\\\\\\\q\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\N{SNOWMAN}\"-br\"\\\\N{SNOWMAN}\"]", "tests/pyupgrade_test.py::test_noop_octal_literals[0]", "tests/pyupgrade_test.py::test_noop_octal_literals[00]", "tests/pyupgrade_test.py::test_noop_octal_literals[1]", "tests/pyupgrade_test.py::test_noop_octal_literals[12345]", "tests/pyupgrade_test.py::test_noop_octal_literals[1.2345]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((1,", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(())]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((\\n))]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[sum((block.code", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[def", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"foo{}\".format(1)))-print(\"foo{}\".format(1))]", "tests/pyupgrade_test.py::test_fix_extra_parens[print((((1))))-print(1)]", "tests/pyupgrade_test.py::test_fix_extra_parens[print(\\n", "tests/pyupgrade_test.py::test_fix_extra_parens[extra", "tests/pyupgrade_test.py::test_is_bytestring_true[b'']", "tests/pyupgrade_test.py::test_is_bytestring_true[b\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B'']", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''0]", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''1]", "tests/pyupgrade_test.py::test_is_bytestring_false[]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false['']", "tests/pyupgrade_test.py::test_is_bytestring_false[u\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"b\"]", "tests/pyupgrade_test.py::test_parse_percent_format[\"\"-expected0]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%%\"-expected1]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s\"-expected2]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(hi)s\"-expected4]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%()s\"-expected5]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%#o\"-expected6]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%", "tests/pyupgrade_test.py::test_parse_percent_format[\"%5d\"-expected8]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%*d\"-expected9]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.f\"-expected10]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.5f\"-expected11]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.*f\"-expected12]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%ld\"-expected13]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(complete)#4.4f\"-expected14]", "tests/pyupgrade_test.py::test_percent_to_format[%s-{}]", "tests/pyupgrade_test.py::test_percent_to_format[%%%s-%{}]", "tests/pyupgrade_test.py::test_percent_to_format[%(foo)s-{foo}]", "tests/pyupgrade_test.py::test_percent_to_format[%2f-{:2f}]", "tests/pyupgrade_test.py::test_percent_to_format[%r-{!r}]", "tests/pyupgrade_test.py::test_percent_to_format[%a-{!a}]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[-]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[", "tests/pyupgrade_test.py::test_simplify_conversion_flag[#0-", "tests/pyupgrade_test.py::test_simplify_conversion_flag[--<]", "tests/pyupgrade_test.py::test_percent_format_noop[\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[b\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%d\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%i\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%u\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%c\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%#o\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%()s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%4%\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2r\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2a\"", "tests/pyupgrade_test.py::test_percent_format_noop[i", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(1)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(a)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(ab)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(and)s\"", "tests/pyupgrade_test.py::test_percent_format[\"trivial\"", "tests/pyupgrade_test.py::test_percent_format[\"%s\"", "tests/pyupgrade_test.py::test_percent_format[\"%s%%", "tests/pyupgrade_test.py::test_percent_format[\"%3f\"", "tests/pyupgrade_test.py::test_percent_format[\"%-5s\"", "tests/pyupgrade_test.py::test_percent_format[\"%9s\"", "tests/pyupgrade_test.py::test_percent_format[\"brace", "tests/pyupgrade_test.py::test_percent_format[\"%(k)s\"", "tests/pyupgrade_test.py::test_percent_format[\"%(to_list)s\"", "tests/pyupgrade_test.py::test_fix_super_noop[x(]", "tests/pyupgrade_test.py::test_fix_super_noop[class", "tests/pyupgrade_test.py::test_fix_super_noop[def", "tests/pyupgrade_test.py::test_fix_super[class", "tests/pyupgrade_test.py::test_fix_classes_noop[x", "tests/pyupgrade_test.py::test_fix_classes_noop[class", "tests/pyupgrade_test.py::test_fix_classes[class", "tests/pyupgrade_test.py::test_fix_classes[import", "tests/pyupgrade_test.py::test_fix_classes[from", "tests/pyupgrade_test.py::test_fix_six_noop[x", "tests/pyupgrade_test.py::test_fix_six_noop[@", "tests/pyupgrade_test.py::test_fix_six_noop[from", "tests/pyupgrade_test.py::test_fix_six_noop[@mydec\\nclass", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(\"\\xa3\"))]", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(", "tests/pyupgrade_test.py::test_fix_six_noop[class", "tests/pyupgrade_test.py::test_fix_six[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six[weird", "tests/pyupgrade_test.py::test_fix_six[issubclass(tp,", "tests/pyupgrade_test.py::test_fix_six[STRING_TYPES", "tests/pyupgrade_test.py::test_fix_six[from", "tests/pyupgrade_test.py::test_fix_six[six.b(\"123\")-b\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(r\"123\")-br\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(\"\\\\x12\\\\xef\")-b\"\\\\x12\\\\xef\"]", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/pyupgrade_test.py::test_fix_six[six.get_unbound_method(meth)\\n-meth\\n]", "tests/pyupgrade_test.py::test_fix_six[six.indexbytes(bs,", "tests/pyupgrade_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/pyupgrade_test.py::test_fix_six[six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(tp,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(\\n", "tests/pyupgrade_test.py::test_fix_six[class", "tests/pyupgrade_test.py::test_fix_classes_py3only[class", "tests/pyupgrade_test.py::test_fix_classes_py3only[from", "tests/pyupgrade_test.py::test_fix_fstrings_noop[(]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\"", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{foo}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{0}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[b\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{1}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{.x}", "tests/pyupgrade_test.py::test_fix_fstrings[\"hello", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped,", "tests/pyupgrade_test.py::test_main_trivial", "tests/pyupgrade_test.py::test_main_noop", "tests/pyupgrade_test.py::test_main_changes_a_file", "tests/pyupgrade_test.py::test_main_keeps_line_endings", "tests/pyupgrade_test.py::test_main_syntax_error", "tests/pyupgrade_test.py::test_main_non_utf8_bytes", "tests/pyupgrade_test.py::test_keep_percent_format", "tests/pyupgrade_test.py::test_py3_plus_argument_unicode_literals", "tests/pyupgrade_test.py::test_py3_plus_super", "tests/pyupgrade_test.py::test_py3_plus_new_style_classes", "tests/pyupgrade_test.py::test_py36_plus_fstrings" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2019-05-11 22:57:47+00:00
mit
1,135
asottile__pyupgrade-143
diff --git a/pyupgrade.py b/pyupgrade.py index f1d25ec..2b251f4 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -904,7 +904,7 @@ SIX_TYPE_CTX_ATTRS = { } SIX_CALLS = { 'u': '{args[0]}', - 'byte2int': '{arg0}[0]', + 'byte2int': '{args[0]}[0]', 'indexbytes': '{args[0]}[{rest}]', 'iteritems': '{args[0]}.items()', 'iterkeys': '{args[0]}.keys()', @@ -943,6 +943,8 @@ class FindPy3Plus(ast.NodeVisitor): def __init__(self): self.bases_to_remove = set() + self.native_literals = set() + self._six_from_imports = set() self.six_b = set() self.six_calls = {} @@ -1055,6 +1057,15 @@ class FindPy3Plus(ast.NodeVisitor): node.args[1].id == self._class_info_stack[-1].first_arg_name ): self.super_calls[_ast_to_offset(node)] = node + elif ( + isinstance(node.func, ast.Name) and + node.func.id == 'str' and + len(node.args) == 1 and + isinstance(node.args[0], ast.Str) and + not node.keywords and + not _starargs(node) + ): + self.native_literals.add(_ast_to_offset(node)) self.generic_visit(node) @@ -1172,6 +1183,7 @@ def _fix_py3_plus(contents_text): if not any(( visitor.bases_to_remove, + visitor.native_literals, visitor.six_b, visitor.six_calls, visitor.six_raises, @@ -1243,6 +1255,12 @@ def _fix_py3_plus(contents_text): call = visitor.super_calls[token.offset] victims = _victims(tokens, i, call, gen=False) del tokens[victims.starts[0] + 1:victims.ends[-1]] + elif token.offset in visitor.native_literals: + j = _find_open_paren(tokens, i) + func_args, end = _parse_call_args(tokens, j) + if any(tok.name == 'NL' for tok in tokens[i:end]): + continue + _replace_call(tokens, i, end, func_args, '{args[0]}') return tokens_to_src(tokens)
asottile/pyupgrade
d138fbaf32bb2f659a2d1c96417950a1efd58903
diff --git a/tests/pyupgrade_test.py b/tests/pyupgrade_test.py index a3f75cb..8de1903 100644 --- a/tests/pyupgrade_test.py +++ b/tests/pyupgrade_test.py @@ -1158,6 +1158,10 @@ def test_fix_six_noop(s): 'from six import b\n\n' r'b("\x12\xef")', 'from six import b\n\n' r'b"\x12\xef"', ), + ( + 'six.byte2int(b"f")', + 'b"f"[0]', + ), ( '@six.python_2_unicode_compatible\n' 'class C: pass', @@ -1353,6 +1357,31 @@ def test_fix_classes_py3only(s, expected): assert _fix_py3_plus(s) == expected [email protected]( + 's', + ( + 'str(1)', + 'str("foo"\n"bar")', # creates a syntax error + 'str(*a)', 'str("foo", *a)', + 'str(**k)', 'str("foo", **k)', + 'str("foo", encoding="UTF-8")', + ), +) +def test_fix_native_literals_noop(s): + assert _fix_py3_plus(s) == s + + [email protected]( + ('s', 'expected'), + ( + ('str("foo")', '"foo"'), + ('str("""\nfoo""")', '"""\nfoo"""'), + ), +) +def test_fix_native_literals(s, expected): + assert _fix_py3_plus(s) == expected + + @pytest.mark.parametrize( 's', (
--py3-plus: `str('native literal')` -> 'native literal' In 2+3 code, a native literal (py2: bytes, py3: str) is often written as `str('foo')` -- this can be cleaned up automatically
0.0
d138fbaf32bb2f659a2d1c96417950a1efd58903
[ "tests/pyupgrade_test.py::test_fix_six[six.byte2int(b\"f\")-b\"f\"[0]]", "tests/pyupgrade_test.py::test_fix_native_literals[str(\"foo\")-\"foo\"]", "tests/pyupgrade_test.py::test_fix_native_literals[str(\"\"\"\\nfoo\"\"\")-\"\"\"\\nfoo\"\"\"]" ]
[ "tests/pyupgrade_test.py::test_roundtrip_text[]", "tests/pyupgrade_test.py::test_roundtrip_text[foo]", "tests/pyupgrade_test.py::test_roundtrip_text[{}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0}]", "tests/pyupgrade_test.py::test_roundtrip_text[{named}]", "tests/pyupgrade_test.py::test_roundtrip_text[{!r}]", "tests/pyupgrade_test.py::test_roundtrip_text[{:>5}]", "tests/pyupgrade_test.py::test_roundtrip_text[{{]", "tests/pyupgrade_test.py::test_roundtrip_text[}}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0!s:15}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/pyupgrade_test.py::test_sets[set()-set()]", "tests/pyupgrade_test.py::test_sets[set((\\n))-set((\\n))]", "tests/pyupgrade_test.py::test_sets[set", "tests/pyupgrade_test.py::test_sets[set(())-set()]", "tests/pyupgrade_test.py::test_sets[set([])-set()]", "tests/pyupgrade_test.py::test_sets[set((", "tests/pyupgrade_test.py::test_sets[set((1,", "tests/pyupgrade_test.py::test_sets[set([1,", "tests/pyupgrade_test.py::test_sets[set(x", "tests/pyupgrade_test.py::test_sets[set([x", "tests/pyupgrade_test.py::test_sets[set((x", "tests/pyupgrade_test.py::test_sets[set(((1,", "tests/pyupgrade_test.py::test_sets[set((a,", "tests/pyupgrade_test.py::test_sets[set([(1,", "tests/pyupgrade_test.py::test_sets[set(\\n", "tests/pyupgrade_test.py::test_sets[set([((1,", "tests/pyupgrade_test.py::test_sets[set((((1,", "tests/pyupgrade_test.py::test_sets[set(\\n(1,", "tests/pyupgrade_test.py::test_sets[set((\\n1,\\n2,\\n))\\n-{\\n1,\\n2,\\n}\\n]", "tests/pyupgrade_test.py::test_sets[set((frozenset(set((1,", "tests/pyupgrade_test.py::test_sets[set((1,))-{1}]", "tests/pyupgrade_test.py::test_dictcomps[x", "tests/pyupgrade_test.py::test_dictcomps[dict()-dict()]", "tests/pyupgrade_test.py::test_dictcomps[(-(]", "tests/pyupgrade_test.py::test_dictcomps[dict", "tests/pyupgrade_test.py::test_dictcomps[dict((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([(a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a),", "tests/pyupgrade_test.py::test_dictcomps[dict((k,", "tests/pyupgrade_test.py::test_dictcomps[dict(\\n", "tests/pyupgrade_test.py::test_dictcomps[x(\\n", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal_noop[x", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is`]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[string]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[unicode", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[bytes]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[float]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[compound", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[multi-line", "tests/pyupgrade_test.py::test_format_literals[\"{0}\"format(1)-\"{0}\"format(1)]", "tests/pyupgrade_test.py::test_format_literals['{}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{'.format(1)-'{'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['}'.format(1)-'}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals[x", "tests/pyupgrade_test.py::test_format_literals['{0}", "tests/pyupgrade_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{0:x}'.format(30)-'{:x}'.format(30)]", "tests/pyupgrade_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/pyupgrade_test.py::test_format_literals['{0}'", "tests/pyupgrade_test.py::test_format_literals[print(\\n", "tests/pyupgrade_test.py::test_format_literals['{0:<{1}}'.format(1,", "tests/pyupgrade_test.py::test_imports_unicode_literals[import", "tests/pyupgrade_test.py::test_imports_unicode_literals[from", "tests/pyupgrade_test.py::test_imports_unicode_literals[x", "tests/pyupgrade_test.py::test_imports_unicode_literals[\"\"\"docstring\"\"\"\\nfrom", "tests/pyupgrade_test.py::test_unicode_literals[(-False-(]", "tests/pyupgrade_test.py::test_unicode_literals[u''-False-u'']", "tests/pyupgrade_test.py::test_unicode_literals[u''-True-'']", "tests/pyupgrade_test.py::test_unicode_literals[from", "tests/pyupgrade_test.py::test_unicode_literals[\"\"\"with", "tests/pyupgrade_test.py::test_unicode_literals[Regression:", "tests/pyupgrade_test.py::test_fix_ur_literals[basic", "tests/pyupgrade_test.py::test_fix_ur_literals[upper", "tests/pyupgrade_test.py::test_fix_ur_literals[with", "tests/pyupgrade_test.py::test_fix_ur_literals[emoji]", "tests/pyupgrade_test.py::test_fix_ur_literals_gets_fixed_before_u_removed", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'\\\\d']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\"\"\\\\d\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'''\\\\d''']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[rb\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\r\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\N{SNOWMAN}\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\d\"-r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\n\\\\d\"-\"\\\\n\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[u\"\\\\d\"-u\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\d\"-br\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\8\"-r\"\\\\8\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\9\"-r\"\\\\9\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\u2603\"-br\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\n\\\\q\"\"\"-\"\"\"\\\\\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\n\\\\q\"\"\"-\"\"\"\\\\\\r\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\\\q\"\"\"-\"\"\"\\\\\\r\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N\"-r\"\\\\N\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N\\\\n\"-\"\\\\\\\\N\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N{SNOWMAN}\\\\q\"-\"\\\\N{SNOWMAN}\\\\\\\\q\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\N{SNOWMAN}\"-br\"\\\\N{SNOWMAN}\"]", "tests/pyupgrade_test.py::test_noop_octal_literals[0]", "tests/pyupgrade_test.py::test_noop_octal_literals[00]", "tests/pyupgrade_test.py::test_noop_octal_literals[1]", "tests/pyupgrade_test.py::test_noop_octal_literals[12345]", "tests/pyupgrade_test.py::test_noop_octal_literals[1.2345]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((1,", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(())]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((\\n))]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[sum((block.code", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[def", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"foo{}\".format(1)))-print(\"foo{}\".format(1))]", "tests/pyupgrade_test.py::test_fix_extra_parens[print((((1))))-print(1)]", "tests/pyupgrade_test.py::test_fix_extra_parens[print(\\n", "tests/pyupgrade_test.py::test_fix_extra_parens[extra", "tests/pyupgrade_test.py::test_is_bytestring_true[b'']", "tests/pyupgrade_test.py::test_is_bytestring_true[b\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B'']", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''0]", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''1]", "tests/pyupgrade_test.py::test_is_bytestring_false[]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false['']", "tests/pyupgrade_test.py::test_is_bytestring_false[u\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"b\"]", "tests/pyupgrade_test.py::test_parse_percent_format[\"\"-expected0]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%%\"-expected1]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s\"-expected2]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(hi)s\"-expected4]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%()s\"-expected5]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%#o\"-expected6]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%", "tests/pyupgrade_test.py::test_parse_percent_format[\"%5d\"-expected8]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%*d\"-expected9]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.f\"-expected10]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.5f\"-expected11]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.*f\"-expected12]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%ld\"-expected13]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(complete)#4.4f\"-expected14]", "tests/pyupgrade_test.py::test_percent_to_format[%s-{}]", "tests/pyupgrade_test.py::test_percent_to_format[%%%s-%{}]", "tests/pyupgrade_test.py::test_percent_to_format[%(foo)s-{foo}]", "tests/pyupgrade_test.py::test_percent_to_format[%2f-{:2f}]", "tests/pyupgrade_test.py::test_percent_to_format[%r-{!r}]", "tests/pyupgrade_test.py::test_percent_to_format[%a-{!a}]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[-]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[", "tests/pyupgrade_test.py::test_simplify_conversion_flag[#0-", "tests/pyupgrade_test.py::test_simplify_conversion_flag[--<]", "tests/pyupgrade_test.py::test_percent_format_noop[\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[b\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%d\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%i\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%u\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%c\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%#o\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%()s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%4%\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2r\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2a\"", "tests/pyupgrade_test.py::test_percent_format_noop[i", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(1)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(a)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(ab)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(and)s\"", "tests/pyupgrade_test.py::test_percent_format[\"trivial\"", "tests/pyupgrade_test.py::test_percent_format[\"%s\"", "tests/pyupgrade_test.py::test_percent_format[\"%s%%", "tests/pyupgrade_test.py::test_percent_format[\"%3f\"", "tests/pyupgrade_test.py::test_percent_format[\"%-5s\"", "tests/pyupgrade_test.py::test_percent_format[\"%9s\"", "tests/pyupgrade_test.py::test_percent_format[\"brace", "tests/pyupgrade_test.py::test_percent_format[\"%(k)s\"", "tests/pyupgrade_test.py::test_percent_format[\"%(to_list)s\"", "tests/pyupgrade_test.py::test_fix_super_noop[x(]", "tests/pyupgrade_test.py::test_fix_super_noop[class", "tests/pyupgrade_test.py::test_fix_super_noop[def", "tests/pyupgrade_test.py::test_fix_super[class", "tests/pyupgrade_test.py::test_fix_classes_noop[x", "tests/pyupgrade_test.py::test_fix_classes_noop[class", "tests/pyupgrade_test.py::test_fix_classes[class", "tests/pyupgrade_test.py::test_fix_classes[import", "tests/pyupgrade_test.py::test_fix_classes[from", "tests/pyupgrade_test.py::test_fix_six_noop[x", "tests/pyupgrade_test.py::test_fix_six_noop[@", "tests/pyupgrade_test.py::test_fix_six_noop[from", "tests/pyupgrade_test.py::test_fix_six_noop[@mydec\\nclass", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(\"\\xa3\"))]", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(", "tests/pyupgrade_test.py::test_fix_six_noop[class", "tests/pyupgrade_test.py::test_fix_six[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six[weird", "tests/pyupgrade_test.py::test_fix_six[issubclass(tp,", "tests/pyupgrade_test.py::test_fix_six[STRING_TYPES", "tests/pyupgrade_test.py::test_fix_six[from", "tests/pyupgrade_test.py::test_fix_six[six.b(\"123\")-b\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(r\"123\")-br\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(\"\\\\x12\\\\xef\")-b\"\\\\x12\\\\xef\"]", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/pyupgrade_test.py::test_fix_six[six.get_unbound_method(meth)\\n-meth\\n]", "tests/pyupgrade_test.py::test_fix_six[six.indexbytes(bs,", "tests/pyupgrade_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/pyupgrade_test.py::test_fix_six[six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(tp,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(\\n", "tests/pyupgrade_test.py::test_fix_six[class", "tests/pyupgrade_test.py::test_fix_classes_py3only[class", "tests/pyupgrade_test.py::test_fix_classes_py3only[from", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(1)]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(\"foo\"\\n\"bar\")]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(*a)]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(\"foo\",", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(**k)]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[(]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\"", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{foo}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{0}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[b\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{1}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{.x}", "tests/pyupgrade_test.py::test_fix_fstrings[\"hello", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped,", "tests/pyupgrade_test.py::test_main_trivial", "tests/pyupgrade_test.py::test_main_noop", "tests/pyupgrade_test.py::test_main_changes_a_file", "tests/pyupgrade_test.py::test_main_keeps_line_endings", "tests/pyupgrade_test.py::test_main_syntax_error", "tests/pyupgrade_test.py::test_main_non_utf8_bytes", "tests/pyupgrade_test.py::test_keep_percent_format", "tests/pyupgrade_test.py::test_py3_plus_argument_unicode_literals", "tests/pyupgrade_test.py::test_py3_plus_super", "tests/pyupgrade_test.py::test_py3_plus_new_style_classes", "tests/pyupgrade_test.py::test_py36_plus_fstrings" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-05-11 23:52:25+00:00
mit
1,136
asottile__pyupgrade-146
diff --git a/pyupgrade.py b/pyupgrade.py index 2b251f4..31a603e 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -104,7 +104,10 @@ def _rewrite_string_literal(literal): def _fix_format_literals(contents_text): - tokens = src_to_tokens(contents_text) + try: + tokens = src_to_tokens(contents_text) + except tokenize.TokenError: + return contents_text to_replace = [] string_start = None @@ -413,7 +416,10 @@ def _fix_py2_compatible(contents_text): )): return contents_text - tokens = src_to_tokens(contents_text) + try: + tokens = src_to_tokens(contents_text) + except tokenize.TokenError: # pragma: no cover (bpo-2180) + return contents_text for i, token in reversed_enumerate(tokens): if token.offset in visitor.dicts: _process_dict_comp(tokens, i, visitor.dicts[token.offset]) @@ -859,7 +865,10 @@ def _fix_percent_format(contents_text): if not visitor.found: return contents_text - tokens = src_to_tokens(contents_text) + try: + tokens = src_to_tokens(contents_text) + except tokenize.TokenError: # pragma: no cover (bpo-2180) + return contents_text for i, token in reversed_enumerate(tokens): node = visitor.found.get(token.offset) @@ -1195,6 +1204,11 @@ def _fix_py3_plus(contents_text): )): return contents_text + try: + tokens = src_to_tokens(contents_text) + except tokenize.TokenError: # pragma: no cover (bpo-2180) + return contents_text + def _replace(i, mapping, node): new_token = Token('CODE', _get_tmpl(mapping, node)) if isinstance(node, ast.Name): @@ -1205,7 +1219,6 @@ def _fix_py3_plus(contents_text): j += 1 tokens[i:j + 1] = [new_token] - tokens = src_to_tokens(contents_text) for i, token in reversed_enumerate(tokens): if not token.src: continue @@ -1357,7 +1370,10 @@ def _fix_fstrings(contents_text): if not visitor.found: return contents_text - tokens = src_to_tokens(contents_text) + try: + tokens = src_to_tokens(contents_text) + except tokenize.TokenError: # pragma: no cover (bpo-2180) + return contents_text for i, token in reversed_enumerate(tokens): node = visitor.found.get(token.offset) if node is None:
asottile/pyupgrade
b2e4ffe4faa3f3bba12f9e8b7a12d0847f716425
diff --git a/tests/pyupgrade_test.py b/tests/pyupgrade_test.py index 8de1903..102e7b9 100644 --- a/tests/pyupgrade_test.py +++ b/tests/pyupgrade_test.py @@ -1524,3 +1524,18 @@ def test_py36_plus_fstrings(tmpdir): assert f.read() == '"{} {}".format(hello, world)' assert main((f.strpath, '--py36-plus')) == 1 assert f.read() == 'f"{hello} {world}"' + + +def test_noop_token_error(tmpdir): + f = tmpdir.join('f.py') + f.write( + # force some rewrites (ast is ok https://bugs.python.org/issue2180) + 'set(())\n' + '"%s" % (1,)\n' + 'six.b("foo")\n' + '"{}".format(a)\n' + # token error + 'x = \\\n' + '5\\\n' + ) + assert main((f.strpath, '--py36-plus')) == 0
TokenError Thank you very much for writing this tool!! I want to run pyupgrade over a project that probably still contains code that raises a syntax error when imported in a python3 interpreter. ``pyupgrade --py36-plus`` outputs is the following in a python3.7 conda env: ``` filename1.py filename2.py Traceback (most recent call last): File "/home/thomas/miniconda/envs/py37/bin/pyupgrade", line 10, in <module> sys.exit(main()) File "/home/thomas/miniconda/envs/py37/lib/python3.7/site-packages/pyupgrade.py", line 1428, in main ret |= fix_file(filename, args) File "/home/thomas/miniconda/envs/py37/lib/python3.7/site-packages/pyupgrade.py", line 1397, in fix_file contents_text = _fix_format_literals(contents_text) File "/home/thomas/miniconda/envs/py37/lib/python3.7/site-packages/pyupgrade.py", line 107, in _fix_format_literals tokens = src_to_tokens(contents_text) File "/home/thomas/miniconda/envs/py37/lib/python3.7/site-packages/tokenize_rt.py", line 44, in src_to_tokens ) in tokenize.generate_tokens(tokenize_target.readline): File "/home/thomas/miniconda/envs/py37/lib/python3.7/tokenize.py", line 579, in _tokenize raise TokenError("EOF in multi-line statement", (lnum, 0)) tokenize.TokenError: ('EOF in multi-line statement', (350, 0)) ``` Unfortunately this exception is not very helpful, since it doesn't really tell me which file lead to this exception. Note that filename2.py is not the culprit, because it doesn't have a line with number 350. IMO pyupgrade should avoid showning tracebacks by defaults, but instead output filename+linum of the faulty files. Tested it with ``` (py37) > $ conda list pyupgrade [±master ●●] # packages in environment at /home/thomas/miniconda/envs/py37: # # Name Version Build Channel pyupgrade 1.17.0 py_0 conda-forge ``` BTW pyupgrade doesn't have a `--version` cli flag.
0.0
b2e4ffe4faa3f3bba12f9e8b7a12d0847f716425
[ "tests/pyupgrade_test.py::test_noop_token_error" ]
[ "tests/pyupgrade_test.py::test_roundtrip_text[]", "tests/pyupgrade_test.py::test_roundtrip_text[foo]", "tests/pyupgrade_test.py::test_roundtrip_text[{}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0}]", "tests/pyupgrade_test.py::test_roundtrip_text[{named}]", "tests/pyupgrade_test.py::test_roundtrip_text[{!r}]", "tests/pyupgrade_test.py::test_roundtrip_text[{:>5}]", "tests/pyupgrade_test.py::test_roundtrip_text[{{]", "tests/pyupgrade_test.py::test_roundtrip_text[}}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0!s:15}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/pyupgrade_test.py::test_sets[set()-set()]", "tests/pyupgrade_test.py::test_sets[set((\\n))-set((\\n))]", "tests/pyupgrade_test.py::test_sets[set", "tests/pyupgrade_test.py::test_sets[set(())-set()]", "tests/pyupgrade_test.py::test_sets[set([])-set()]", "tests/pyupgrade_test.py::test_sets[set((", "tests/pyupgrade_test.py::test_sets[set((1,", "tests/pyupgrade_test.py::test_sets[set([1,", "tests/pyupgrade_test.py::test_sets[set(x", "tests/pyupgrade_test.py::test_sets[set([x", "tests/pyupgrade_test.py::test_sets[set((x", "tests/pyupgrade_test.py::test_sets[set(((1,", "tests/pyupgrade_test.py::test_sets[set((a,", "tests/pyupgrade_test.py::test_sets[set([(1,", "tests/pyupgrade_test.py::test_sets[set(\\n", "tests/pyupgrade_test.py::test_sets[set([((1,", "tests/pyupgrade_test.py::test_sets[set((((1,", "tests/pyupgrade_test.py::test_sets[set(\\n(1,", "tests/pyupgrade_test.py::test_sets[set((\\n1,\\n2,\\n))\\n-{\\n1,\\n2,\\n}\\n]", "tests/pyupgrade_test.py::test_sets[set((frozenset(set((1,", "tests/pyupgrade_test.py::test_sets[set((1,))-{1}]", "tests/pyupgrade_test.py::test_dictcomps[x", "tests/pyupgrade_test.py::test_dictcomps[dict()-dict()]", "tests/pyupgrade_test.py::test_dictcomps[(-(]", "tests/pyupgrade_test.py::test_dictcomps[dict", "tests/pyupgrade_test.py::test_dictcomps[dict((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([(a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a),", "tests/pyupgrade_test.py::test_dictcomps[dict((k,", "tests/pyupgrade_test.py::test_dictcomps[dict(\\n", "tests/pyupgrade_test.py::test_dictcomps[x(\\n", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal_noop[x", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is`]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[string]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[unicode", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[bytes]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[float]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[compound", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[multi-line", "tests/pyupgrade_test.py::test_format_literals[\"{0}\"format(1)-\"{0}\"format(1)]", "tests/pyupgrade_test.py::test_format_literals['{}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{'.format(1)-'{'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['}'.format(1)-'}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals[x", "tests/pyupgrade_test.py::test_format_literals['{0}", "tests/pyupgrade_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{0:x}'.format(30)-'{:x}'.format(30)]", "tests/pyupgrade_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/pyupgrade_test.py::test_format_literals['{0}'", "tests/pyupgrade_test.py::test_format_literals[print(\\n", "tests/pyupgrade_test.py::test_format_literals['{0:<{1}}'.format(1,", "tests/pyupgrade_test.py::test_imports_unicode_literals[import", "tests/pyupgrade_test.py::test_imports_unicode_literals[from", "tests/pyupgrade_test.py::test_imports_unicode_literals[x", "tests/pyupgrade_test.py::test_imports_unicode_literals[\"\"\"docstring\"\"\"\\nfrom", "tests/pyupgrade_test.py::test_unicode_literals[(-False-(]", "tests/pyupgrade_test.py::test_unicode_literals[u''-False-u'']", "tests/pyupgrade_test.py::test_unicode_literals[u''-True-'']", "tests/pyupgrade_test.py::test_unicode_literals[from", "tests/pyupgrade_test.py::test_unicode_literals[\"\"\"with", "tests/pyupgrade_test.py::test_unicode_literals[Regression:", "tests/pyupgrade_test.py::test_fix_ur_literals[basic", "tests/pyupgrade_test.py::test_fix_ur_literals[upper", "tests/pyupgrade_test.py::test_fix_ur_literals[with", "tests/pyupgrade_test.py::test_fix_ur_literals[emoji]", "tests/pyupgrade_test.py::test_fix_ur_literals_gets_fixed_before_u_removed", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'\\\\d']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\"\"\\\\d\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'''\\\\d''']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[rb\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\r\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\N{SNOWMAN}\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\d\"-r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\n\\\\d\"-\"\\\\n\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[u\"\\\\d\"-u\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\d\"-br\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\8\"-r\"\\\\8\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\9\"-r\"\\\\9\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\u2603\"-br\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\n\\\\q\"\"\"-\"\"\"\\\\\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\n\\\\q\"\"\"-\"\"\"\\\\\\r\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\\\q\"\"\"-\"\"\"\\\\\\r\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N\"-r\"\\\\N\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N\\\\n\"-\"\\\\\\\\N\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N{SNOWMAN}\\\\q\"-\"\\\\N{SNOWMAN}\\\\\\\\q\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\N{SNOWMAN}\"-br\"\\\\N{SNOWMAN}\"]", "tests/pyupgrade_test.py::test_noop_octal_literals[0]", "tests/pyupgrade_test.py::test_noop_octal_literals[00]", "tests/pyupgrade_test.py::test_noop_octal_literals[1]", "tests/pyupgrade_test.py::test_noop_octal_literals[12345]", "tests/pyupgrade_test.py::test_noop_octal_literals[1.2345]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((1,", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(())]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((\\n))]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[sum((block.code", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[def", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"foo{}\".format(1)))-print(\"foo{}\".format(1))]", "tests/pyupgrade_test.py::test_fix_extra_parens[print((((1))))-print(1)]", "tests/pyupgrade_test.py::test_fix_extra_parens[print(\\n", "tests/pyupgrade_test.py::test_fix_extra_parens[extra", "tests/pyupgrade_test.py::test_is_bytestring_true[b'']", "tests/pyupgrade_test.py::test_is_bytestring_true[b\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B'']", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''0]", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''1]", "tests/pyupgrade_test.py::test_is_bytestring_false[]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false['']", "tests/pyupgrade_test.py::test_is_bytestring_false[u\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"b\"]", "tests/pyupgrade_test.py::test_parse_percent_format[\"\"-expected0]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%%\"-expected1]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s\"-expected2]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(hi)s\"-expected4]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%()s\"-expected5]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%#o\"-expected6]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%", "tests/pyupgrade_test.py::test_parse_percent_format[\"%5d\"-expected8]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%*d\"-expected9]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.f\"-expected10]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.5f\"-expected11]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.*f\"-expected12]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%ld\"-expected13]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(complete)#4.4f\"-expected14]", "tests/pyupgrade_test.py::test_percent_to_format[%s-{}]", "tests/pyupgrade_test.py::test_percent_to_format[%%%s-%{}]", "tests/pyupgrade_test.py::test_percent_to_format[%(foo)s-{foo}]", "tests/pyupgrade_test.py::test_percent_to_format[%2f-{:2f}]", "tests/pyupgrade_test.py::test_percent_to_format[%r-{!r}]", "tests/pyupgrade_test.py::test_percent_to_format[%a-{!a}]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[-]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[", "tests/pyupgrade_test.py::test_simplify_conversion_flag[#0-", "tests/pyupgrade_test.py::test_simplify_conversion_flag[--<]", "tests/pyupgrade_test.py::test_percent_format_noop[\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[b\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%d\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%i\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%u\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%c\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%#o\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%()s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%4%\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2r\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2a\"", "tests/pyupgrade_test.py::test_percent_format_noop[i", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(1)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(a)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(ab)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(and)s\"", "tests/pyupgrade_test.py::test_percent_format[\"trivial\"", "tests/pyupgrade_test.py::test_percent_format[\"%s\"", "tests/pyupgrade_test.py::test_percent_format[\"%s%%", "tests/pyupgrade_test.py::test_percent_format[\"%3f\"", "tests/pyupgrade_test.py::test_percent_format[\"%-5s\"", "tests/pyupgrade_test.py::test_percent_format[\"%9s\"", "tests/pyupgrade_test.py::test_percent_format[\"brace", "tests/pyupgrade_test.py::test_percent_format[\"%(k)s\"", "tests/pyupgrade_test.py::test_percent_format[\"%(to_list)s\"", "tests/pyupgrade_test.py::test_fix_super_noop[x(]", "tests/pyupgrade_test.py::test_fix_super_noop[class", "tests/pyupgrade_test.py::test_fix_super_noop[def", "tests/pyupgrade_test.py::test_fix_super[class", "tests/pyupgrade_test.py::test_fix_classes_noop[x", "tests/pyupgrade_test.py::test_fix_classes_noop[class", "tests/pyupgrade_test.py::test_fix_classes[class", "tests/pyupgrade_test.py::test_fix_classes[import", "tests/pyupgrade_test.py::test_fix_classes[from", "tests/pyupgrade_test.py::test_fix_six_noop[x", "tests/pyupgrade_test.py::test_fix_six_noop[@", "tests/pyupgrade_test.py::test_fix_six_noop[from", "tests/pyupgrade_test.py::test_fix_six_noop[@mydec\\nclass", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(\"\\xa3\"))]", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(", "tests/pyupgrade_test.py::test_fix_six_noop[class", "tests/pyupgrade_test.py::test_fix_six[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six[weird", "tests/pyupgrade_test.py::test_fix_six[issubclass(tp,", "tests/pyupgrade_test.py::test_fix_six[STRING_TYPES", "tests/pyupgrade_test.py::test_fix_six[from", "tests/pyupgrade_test.py::test_fix_six[six.b(\"123\")-b\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(r\"123\")-br\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(\"\\\\x12\\\\xef\")-b\"\\\\x12\\\\xef\"]", "tests/pyupgrade_test.py::test_fix_six[six.byte2int(b\"f\")-b\"f\"[0]]", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/pyupgrade_test.py::test_fix_six[six.get_unbound_method(meth)\\n-meth\\n]", "tests/pyupgrade_test.py::test_fix_six[six.indexbytes(bs,", "tests/pyupgrade_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/pyupgrade_test.py::test_fix_six[six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(tp,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(\\n", "tests/pyupgrade_test.py::test_fix_six[class", "tests/pyupgrade_test.py::test_fix_classes_py3only[class", "tests/pyupgrade_test.py::test_fix_classes_py3only[from", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(1)]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(\"foo\"\\n\"bar\")]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(*a)]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(\"foo\",", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(**k)]", "tests/pyupgrade_test.py::test_fix_native_literals[str(\"foo\")-\"foo\"]", "tests/pyupgrade_test.py::test_fix_native_literals[str(\"\"\"\\nfoo\"\"\")-\"\"\"\\nfoo\"\"\"]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[(]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\"", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{foo}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{0}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[b\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{1}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{.x}", "tests/pyupgrade_test.py::test_fix_fstrings[\"hello", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped,", "tests/pyupgrade_test.py::test_main_trivial", "tests/pyupgrade_test.py::test_main_noop", "tests/pyupgrade_test.py::test_main_changes_a_file", "tests/pyupgrade_test.py::test_main_keeps_line_endings", "tests/pyupgrade_test.py::test_main_syntax_error", "tests/pyupgrade_test.py::test_main_non_utf8_bytes", "tests/pyupgrade_test.py::test_keep_percent_format", "tests/pyupgrade_test.py::test_py3_plus_argument_unicode_literals", "tests/pyupgrade_test.py::test_py3_plus_super", "tests/pyupgrade_test.py::test_py3_plus_new_style_classes", "tests/pyupgrade_test.py::test_py36_plus_fstrings" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-05-17 18:23:30+00:00
mit
1,137
asottile__pyupgrade-147
diff --git a/pyupgrade.py b/pyupgrade.py index 31a603e..b3c6f9c 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -1001,7 +1001,8 @@ class FindPy3Plus(ast.NodeVisitor): if ( len(node.bases) == 1 and isinstance(node.bases[0], ast.Call) and - self._is_six(node.bases[0].func, ('with_metaclass',)) + self._is_six(node.bases[0].func, ('with_metaclass',)) and + not _starargs(node.bases[0]) ): self.six_with_metaclass.add(_ast_to_offset(node.bases[0])) @@ -1047,11 +1048,12 @@ class FindPy3Plus(ast.NodeVisitor): self.six_type_ctx[_ast_to_offset(node.args[1])] = node.args[1] elif self._is_six(node.func, ('b',)): self.six_b.add(_ast_to_offset(node)) - elif self._is_six(node.func, SIX_CALLS): + elif self._is_six(node.func, SIX_CALLS) and not _starargs(node): self.six_calls[_ast_to_offset(node)] = node elif ( isinstance(self._previous_node, ast.Expr) and - self._is_six(node.func, SIX_RAISES) + self._is_six(node.func, SIX_RAISES) and + not _starargs(node) ): self.six_raises[_ast_to_offset(node)] = node elif (
asottile/pyupgrade
a7601194da670e55b80dbb6903f7f6727e58f6fb
diff --git a/tests/pyupgrade_test.py b/tests/pyupgrade_test.py index 102e7b9..fcdb2ea 100644 --- a/tests/pyupgrade_test.py +++ b/tests/pyupgrade_test.py @@ -1098,6 +1098,9 @@ def test_fix_classes(s, expected): 'print(six.b( "123"))', # intentionally not handling this case due to it being a bug (?) 'class C(six.with_metaclass(Meta, B), D): pass', + # cannot determine args to rewrite them + 'six.reraise(*err)', 'six.b(*a)', 'six.u(*a)', + 'class C(six.with_metaclass(*a)): pass', ) ) def test_fix_six_noop(s):
IndexError with pytest's fixtures.py ``` % pyupgrade --py3-only --keep-percent-format src/_pytest/fixtures.py Traceback (most recent call last): File "…/Vcs/pytest/.venv/bin/pyupgrade", line 11, in <module> sys.exit(main()) File "…/Vcs/pytest/.venv/lib/python3.7/site-packages/pyupgrade.py", line 1428, in main ret |= fix_file(filename, args) File "…/Vcs/pytest/.venv/lib/python3.7/site-packages/pyupgrade.py", line 1402, in fix_file contents_text = _fix_py3_plus(contents_text) File "…/Vcs/pytest/.venv/lib/python3.7/site-packages/pyupgrade.py", line 1244, in _fix_py3_plus _replace_call(tokens, i, end, func_args, template) File "…/Vcs/pytest/.venv/lib/python3.7/site-packages/pyupgrade.py", line 1171, in _replace_call src = tmpl.format(args=arg_strs, rest=rest) IndexError: list index out of range ``` `print(repr(tmpl), repr(arg_strs), repr(rest))` shows: > 'raise {args[1]}.with_traceback({args[2]})' ['*err'] ''
0.0
a7601194da670e55b80dbb6903f7f6727e58f6fb
[ "tests/pyupgrade_test.py::test_fix_six_noop[class", "tests/pyupgrade_test.py::test_fix_six_noop[six.reraise(*err)]", "tests/pyupgrade_test.py::test_fix_six_noop[six.u(*a)]" ]
[ "tests/pyupgrade_test.py::test_roundtrip_text[]", "tests/pyupgrade_test.py::test_roundtrip_text[foo]", "tests/pyupgrade_test.py::test_roundtrip_text[{}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0}]", "tests/pyupgrade_test.py::test_roundtrip_text[{named}]", "tests/pyupgrade_test.py::test_roundtrip_text[{!r}]", "tests/pyupgrade_test.py::test_roundtrip_text[{:>5}]", "tests/pyupgrade_test.py::test_roundtrip_text[{{]", "tests/pyupgrade_test.py::test_roundtrip_text[}}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0!s:15}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/pyupgrade_test.py::test_sets[set()-set()]", "tests/pyupgrade_test.py::test_sets[set((\\n))-set((\\n))]", "tests/pyupgrade_test.py::test_sets[set", "tests/pyupgrade_test.py::test_sets[set(())-set()]", "tests/pyupgrade_test.py::test_sets[set([])-set()]", "tests/pyupgrade_test.py::test_sets[set((", "tests/pyupgrade_test.py::test_sets[set((1,", "tests/pyupgrade_test.py::test_sets[set([1,", "tests/pyupgrade_test.py::test_sets[set(x", "tests/pyupgrade_test.py::test_sets[set([x", "tests/pyupgrade_test.py::test_sets[set((x", "tests/pyupgrade_test.py::test_sets[set(((1,", "tests/pyupgrade_test.py::test_sets[set((a,", "tests/pyupgrade_test.py::test_sets[set([(1,", "tests/pyupgrade_test.py::test_sets[set(\\n", "tests/pyupgrade_test.py::test_sets[set([((1,", "tests/pyupgrade_test.py::test_sets[set((((1,", "tests/pyupgrade_test.py::test_sets[set(\\n(1,", "tests/pyupgrade_test.py::test_sets[set((\\n1,\\n2,\\n))\\n-{\\n1,\\n2,\\n}\\n]", "tests/pyupgrade_test.py::test_sets[set((frozenset(set((1,", "tests/pyupgrade_test.py::test_sets[set((1,))-{1}]", "tests/pyupgrade_test.py::test_dictcomps[x", "tests/pyupgrade_test.py::test_dictcomps[dict()-dict()]", "tests/pyupgrade_test.py::test_dictcomps[(-(]", "tests/pyupgrade_test.py::test_dictcomps[dict", "tests/pyupgrade_test.py::test_dictcomps[dict((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([(a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a),", "tests/pyupgrade_test.py::test_dictcomps[dict((k,", "tests/pyupgrade_test.py::test_dictcomps[dict(\\n", "tests/pyupgrade_test.py::test_dictcomps[x(\\n", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal_noop[x", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is`]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[string]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[unicode", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[bytes]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[float]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[compound", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[multi-line", "tests/pyupgrade_test.py::test_format_literals[\"{0}\"format(1)-\"{0}\"format(1)]", "tests/pyupgrade_test.py::test_format_literals['{}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{'.format(1)-'{'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['}'.format(1)-'}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals[x", "tests/pyupgrade_test.py::test_format_literals['{0}", "tests/pyupgrade_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{0:x}'.format(30)-'{:x}'.format(30)]", "tests/pyupgrade_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/pyupgrade_test.py::test_format_literals['{0}'", "tests/pyupgrade_test.py::test_format_literals[print(\\n", "tests/pyupgrade_test.py::test_format_literals['{0:<{1}}'.format(1,", "tests/pyupgrade_test.py::test_imports_unicode_literals[import", "tests/pyupgrade_test.py::test_imports_unicode_literals[from", "tests/pyupgrade_test.py::test_imports_unicode_literals[x", "tests/pyupgrade_test.py::test_imports_unicode_literals[\"\"\"docstring\"\"\"\\nfrom", "tests/pyupgrade_test.py::test_unicode_literals[(-False-(]", "tests/pyupgrade_test.py::test_unicode_literals[u''-False-u'']", "tests/pyupgrade_test.py::test_unicode_literals[u''-True-'']", "tests/pyupgrade_test.py::test_unicode_literals[from", "tests/pyupgrade_test.py::test_unicode_literals[\"\"\"with", "tests/pyupgrade_test.py::test_unicode_literals[Regression:", "tests/pyupgrade_test.py::test_fix_ur_literals[basic", "tests/pyupgrade_test.py::test_fix_ur_literals[upper", "tests/pyupgrade_test.py::test_fix_ur_literals[with", "tests/pyupgrade_test.py::test_fix_ur_literals[emoji]", "tests/pyupgrade_test.py::test_fix_ur_literals_gets_fixed_before_u_removed", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'\\\\d']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\"\"\\\\d\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'''\\\\d''']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[rb\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\r\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\N{SNOWMAN}\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\d\"-r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\n\\\\d\"-\"\\\\n\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[u\"\\\\d\"-u\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\d\"-br\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\8\"-r\"\\\\8\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\9\"-r\"\\\\9\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\u2603\"-br\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\n\\\\q\"\"\"-\"\"\"\\\\\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\n\\\\q\"\"\"-\"\"\"\\\\\\r\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\\\q\"\"\"-\"\"\"\\\\\\r\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N\"-r\"\\\\N\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N\\\\n\"-\"\\\\\\\\N\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N{SNOWMAN}\\\\q\"-\"\\\\N{SNOWMAN}\\\\\\\\q\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\N{SNOWMAN}\"-br\"\\\\N{SNOWMAN}\"]", "tests/pyupgrade_test.py::test_noop_octal_literals[0]", "tests/pyupgrade_test.py::test_noop_octal_literals[00]", "tests/pyupgrade_test.py::test_noop_octal_literals[1]", "tests/pyupgrade_test.py::test_noop_octal_literals[12345]", "tests/pyupgrade_test.py::test_noop_octal_literals[1.2345]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((1,", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(())]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((\\n))]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[sum((block.code", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[def", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"foo{}\".format(1)))-print(\"foo{}\".format(1))]", "tests/pyupgrade_test.py::test_fix_extra_parens[print((((1))))-print(1)]", "tests/pyupgrade_test.py::test_fix_extra_parens[print(\\n", "tests/pyupgrade_test.py::test_fix_extra_parens[extra", "tests/pyupgrade_test.py::test_is_bytestring_true[b'']", "tests/pyupgrade_test.py::test_is_bytestring_true[b\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B'']", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''0]", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''1]", "tests/pyupgrade_test.py::test_is_bytestring_false[]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false['']", "tests/pyupgrade_test.py::test_is_bytestring_false[u\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"b\"]", "tests/pyupgrade_test.py::test_parse_percent_format[\"\"-expected0]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%%\"-expected1]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s\"-expected2]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(hi)s\"-expected4]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%()s\"-expected5]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%#o\"-expected6]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%", "tests/pyupgrade_test.py::test_parse_percent_format[\"%5d\"-expected8]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%*d\"-expected9]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.f\"-expected10]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.5f\"-expected11]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.*f\"-expected12]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%ld\"-expected13]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(complete)#4.4f\"-expected14]", "tests/pyupgrade_test.py::test_percent_to_format[%s-{}]", "tests/pyupgrade_test.py::test_percent_to_format[%%%s-%{}]", "tests/pyupgrade_test.py::test_percent_to_format[%(foo)s-{foo}]", "tests/pyupgrade_test.py::test_percent_to_format[%2f-{:2f}]", "tests/pyupgrade_test.py::test_percent_to_format[%r-{!r}]", "tests/pyupgrade_test.py::test_percent_to_format[%a-{!a}]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[-]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[", "tests/pyupgrade_test.py::test_simplify_conversion_flag[#0-", "tests/pyupgrade_test.py::test_simplify_conversion_flag[--<]", "tests/pyupgrade_test.py::test_percent_format_noop[\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[b\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%d\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%i\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%u\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%c\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%#o\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%()s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%4%\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2r\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2a\"", "tests/pyupgrade_test.py::test_percent_format_noop[i", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(1)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(a)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(ab)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(and)s\"", "tests/pyupgrade_test.py::test_percent_format[\"trivial\"", "tests/pyupgrade_test.py::test_percent_format[\"%s\"", "tests/pyupgrade_test.py::test_percent_format[\"%s%%", "tests/pyupgrade_test.py::test_percent_format[\"%3f\"", "tests/pyupgrade_test.py::test_percent_format[\"%-5s\"", "tests/pyupgrade_test.py::test_percent_format[\"%9s\"", "tests/pyupgrade_test.py::test_percent_format[\"brace", "tests/pyupgrade_test.py::test_percent_format[\"%(k)s\"", "tests/pyupgrade_test.py::test_percent_format[\"%(to_list)s\"", "tests/pyupgrade_test.py::test_fix_super_noop[x(]", "tests/pyupgrade_test.py::test_fix_super_noop[class", "tests/pyupgrade_test.py::test_fix_super_noop[def", "tests/pyupgrade_test.py::test_fix_super[class", "tests/pyupgrade_test.py::test_fix_classes_noop[x", "tests/pyupgrade_test.py::test_fix_classes_noop[class", "tests/pyupgrade_test.py::test_fix_classes[class", "tests/pyupgrade_test.py::test_fix_classes[import", "tests/pyupgrade_test.py::test_fix_classes[from", "tests/pyupgrade_test.py::test_fix_six_noop[x", "tests/pyupgrade_test.py::test_fix_six_noop[@", "tests/pyupgrade_test.py::test_fix_six_noop[from", "tests/pyupgrade_test.py::test_fix_six_noop[@mydec\\nclass", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(\"\\xa3\"))]", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(", "tests/pyupgrade_test.py::test_fix_six_noop[six.b(*a)]", "tests/pyupgrade_test.py::test_fix_six[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six[weird", "tests/pyupgrade_test.py::test_fix_six[issubclass(tp,", "tests/pyupgrade_test.py::test_fix_six[STRING_TYPES", "tests/pyupgrade_test.py::test_fix_six[from", "tests/pyupgrade_test.py::test_fix_six[six.b(\"123\")-b\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(r\"123\")-br\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(\"\\\\x12\\\\xef\")-b\"\\\\x12\\\\xef\"]", "tests/pyupgrade_test.py::test_fix_six[six.byte2int(b\"f\")-b\"f\"[0]]", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/pyupgrade_test.py::test_fix_six[six.get_unbound_method(meth)\\n-meth\\n]", "tests/pyupgrade_test.py::test_fix_six[six.indexbytes(bs,", "tests/pyupgrade_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/pyupgrade_test.py::test_fix_six[six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(tp,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(\\n", "tests/pyupgrade_test.py::test_fix_six[class", "tests/pyupgrade_test.py::test_fix_classes_py3only[class", "tests/pyupgrade_test.py::test_fix_classes_py3only[from", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(1)]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(\"foo\"\\n\"bar\")]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(*a)]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(\"foo\",", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(**k)]", "tests/pyupgrade_test.py::test_fix_native_literals[str(\"foo\")-\"foo\"]", "tests/pyupgrade_test.py::test_fix_native_literals[str(\"\"\"\\nfoo\"\"\")-\"\"\"\\nfoo\"\"\"]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[(]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\"", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{foo}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{0}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[b\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{1}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{.x}", "tests/pyupgrade_test.py::test_fix_fstrings[\"hello", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped,", "tests/pyupgrade_test.py::test_main_trivial", "tests/pyupgrade_test.py::test_main_noop", "tests/pyupgrade_test.py::test_main_changes_a_file", "tests/pyupgrade_test.py::test_main_keeps_line_endings", "tests/pyupgrade_test.py::test_main_syntax_error", "tests/pyupgrade_test.py::test_main_non_utf8_bytes", "tests/pyupgrade_test.py::test_keep_percent_format", "tests/pyupgrade_test.py::test_py3_plus_argument_unicode_literals", "tests/pyupgrade_test.py::test_py3_plus_super", "tests/pyupgrade_test.py::test_py3_plus_new_style_classes", "tests/pyupgrade_test.py::test_py36_plus_fstrings", "tests/pyupgrade_test.py::test_noop_token_error" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-05-17 18:51:29+00:00
mit
1,138
asottile__pyupgrade-15
diff --git a/README.md b/README.md index 7374c46..dd1fe44 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,17 @@ u"foo" # 'foo' u'''foo''' # '''foo''' ``` +### Long literals + +Availability: +- If `pyupgrade` is running in python 2. + +```python +5L # 5 +5l # 5 +123456789123456789123456789L # 123456789123456789123456789 +``` + ## Planned features diff --git a/pyupgrade.py b/pyupgrade.py index 5da90af..60ffda7 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -463,6 +463,14 @@ def _fix_unicode_literals(contents_text, py3_only): return untokenize_tokens(tokens) +def _fix_long_literals(contents_text): + tokens = tokenize_src(contents_text) + for i, token in enumerate(tokens): + if token.name == 'NUMBER': + tokens[i] = token._replace(src=token.src.rstrip('lL')) + return untokenize_tokens(tokens) + + def fix_file(filename, args): with open(filename, 'rb') as f: contents_bytes = f.read() @@ -477,6 +485,7 @@ def fix_file(filename, args): contents_text = _fix_sets(contents_text) contents_text = _fix_format_literals(contents_text) contents_text = _fix_unicode_literals(contents_text, args.py3_only) + contents_text = _fix_long_literals(contents_text) if contents_text != contents_text_orig: print('Rewriting {}'.format(filename))
asottile/pyupgrade
c5f1eb3fd850fc793cd0208cc449f3be5718f052
diff --git a/tests/pyupgrade_test.py b/tests/pyupgrade_test.py index 868d7a4..b594486 100644 --- a/tests/pyupgrade_test.py +++ b/tests/pyupgrade_test.py @@ -3,11 +3,13 @@ from __future__ import absolute_import from __future__ import unicode_literals import io +import sys import pytest from pyupgrade import _fix_dictcomps from pyupgrade import _fix_format_literals +from pyupgrade import _fix_long_literals from pyupgrade import _fix_sets from pyupgrade import _fix_unicode_literals from pyupgrade import _imports_unicode_literals @@ -318,6 +320,19 @@ def test_unicode_literals(s, py3_only, expected): assert ret == expected [email protected](sys.version_info >= (3,), reason='python2 "feature"') [email protected]( + ('s', 'expected'), + ( + ('5L', '5'), + ('5l', '5'), + ('123456789123456789123456789L', '123456789123456789123456789'), + ), +) +def test_long_literals(s, expected): + assert _fix_long_literals(s) == expected + + def test_main_trivial(): assert main(()) == 0
123L -> 123 Somewhere between python2.0 and python2.4 the L prefix became unnecessary for long literals
0.0
c5f1eb3fd850fc793cd0208cc449f3be5718f052
[ "tests/pyupgrade_test.py::test_roundtrip_text[]", "tests/pyupgrade_test.py::test_roundtrip_text[foo]", "tests/pyupgrade_test.py::test_roundtrip_text[{}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0}]", "tests/pyupgrade_test.py::test_roundtrip_text[{named}]", "tests/pyupgrade_test.py::test_roundtrip_text[{!r}]", "tests/pyupgrade_test.py::test_roundtrip_text[{:>5}]", "tests/pyupgrade_test.py::test_roundtrip_text[{{]", "tests/pyupgrade_test.py::test_roundtrip_text[}}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0!s:15}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/pyupgrade_test.py::test_tokenize_src_simple", "tests/pyupgrade_test.py::test_roundtrip_tokenize[testing/resources/empty.py]", "tests/pyupgrade_test.py::test_roundtrip_tokenize[testing/resources/unicode_snowman.py]", "tests/pyupgrade_test.py::test_roundtrip_tokenize[testing/resources/backslash_continuation.py]", "tests/pyupgrade_test.py::test_sets[set()-set()]", "tests/pyupgrade_test.py::test_sets[set((\\n))-set((\\n))]", "tests/pyupgrade_test.py::test_sets[set", "tests/pyupgrade_test.py::test_sets[set(())-set()]", "tests/pyupgrade_test.py::test_sets[set([])-set()]", "tests/pyupgrade_test.py::test_sets[set((", "tests/pyupgrade_test.py::test_sets[set([1,", "tests/pyupgrade_test.py::test_sets[set([(1,", "tests/pyupgrade_test.py::test_sets[set([((1,", "tests/pyupgrade_test.py::test_dictcomps[x", "tests/pyupgrade_test.py::test_dictcomps[dict()-dict()]", "tests/pyupgrade_test.py::test_dictcomps[(-(]", "tests/pyupgrade_test.py::test_dictcomps[dict", "tests/pyupgrade_test.py::test_format_literals['{}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{'.format(1)-'{'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['}'.format(1)-'}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals[x", "tests/pyupgrade_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/pyupgrade_test.py::test_format_literals['{0}'", "tests/pyupgrade_test.py::test_format_literals[print(\\n", "tests/pyupgrade_test.py::test_imports_unicode_literals[import", "tests/pyupgrade_test.py::test_imports_unicode_literals[from", "tests/pyupgrade_test.py::test_imports_unicode_literals[x", "tests/pyupgrade_test.py::test_imports_unicode_literals[\"\"\"docstring\"\"\"\\nfrom", "tests/pyupgrade_test.py::test_unicode_literals[(-False-(]", "tests/pyupgrade_test.py::test_unicode_literals[u''-False-u'']", "tests/pyupgrade_test.py::test_unicode_literals[u''-True-'']", "tests/pyupgrade_test.py::test_unicode_literals[from", "tests/pyupgrade_test.py::test_unicode_literals[\"\"\"with", "tests/pyupgrade_test.py::test_main_trivial", "tests/pyupgrade_test.py::test_main_noop", "tests/pyupgrade_test.py::test_main_syntax_error", "tests/pyupgrade_test.py::test_main_non_utf8_bytes", "tests/pyupgrade_test.py::test_py3_only_argument_unicode_literals" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2017-05-07 19:24:04+00:00
mit
1,139
asottile__pyupgrade-151
diff --git a/pyupgrade.py b/pyupgrade.py index b26904c..19d0b61 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -270,12 +270,16 @@ def _victims(tokens, start, arg, gen): return Victims(starts, ends, first_comma_index, arg_index) -def _find_open_paren(tokens, i): - while tokens[i].src != '(': +def _find_token(tokens, i, token): + while tokens[i].src != token: i += 1 return i +def _find_open_paren(tokens, i): + return _find_token(tokens, i, '(') + + def _is_on_a_line_by_self(tokens, i): return ( tokens[i - 2].name == 'NL' and @@ -943,6 +947,43 @@ SIX_RAISES = { } +def _all_isinstance(vals, tp): + return all(isinstance(v, tp) for v in vals) + + +def fields_same(n1, n2): + for (a1, v1), (a2, v2) in zip(ast.iter_fields(n1), ast.iter_fields(n2)): + # ignore ast attributes, they'll be covered by walk + if a1 != a2: + return False + elif _all_isinstance((v1, v2), ast.AST): + continue + elif _all_isinstance((v1, v2), (list, tuple)): + if len(v1) != len(v2): + return False + # ignore sequences which are all-ast, they'll be covered by walk + elif _all_isinstance(v1, ast.AST) and _all_isinstance(v2, ast.AST): + continue + elif v1 != v2: + return False + elif v1 != v2: + return False + return True + + +def targets_same(target, yield_value): + for t1, t2 in zip(ast.walk(target), ast.walk(yield_value)): + # ignore `ast.Load` / `ast.Store` + if _all_isinstance((t1, t2), ast.expr_context): + continue + elif type(t1) != type(t2): + return False + elif not fields_same(t1, t2): + return False + else: + return True + + def _is_utf8_codec(encoding): try: return codecs.lookup(encoding).name == 'utf-8' @@ -981,6 +1022,7 @@ class FindPy3Plus(ast.NodeVisitor): self._class_info_stack = [] self._in_comp = 0 self.super_calls = {} + self.yield_from_fors = set() def _is_six(self, node, names): return ( @@ -1136,6 +1178,18 @@ class FindPy3Plus(ast.NodeVisitor): self.if_py3_blocks.add(_ast_to_offset(node)) self.generic_visit(node) + def visit_For(self, node): # type: (ast.For) -> None + if ( + len(node.body) == 1 and + isinstance(node.body[0], ast.Expr) and + isinstance(node.body[0].value, ast.Yield) and + targets_same(node.target, node.body[0].value.value) and + not node.orelse + ): + self.yield_from_fors.add(_ast_to_offset(node)) + + self.generic_visit(node) + def generic_visit(self, node): # type: (ast.AST) -> None self._previous_node = node super(FindPy3Plus, self).generic_visit(node) @@ -1159,7 +1213,10 @@ def _fixup_dedent_tokens(tokens): def _find_block_start(tokens, i): depth = 0 while depth or tokens[i].src != ':': - depth += {'(': 1, ')': -1}.get(tokens[i].src, 0) + if tokens[i].src in OPENING: + depth += 1 + elif tokens[i].src in CLOSING: + depth -= 1 i += 1 return i @@ -1379,6 +1436,14 @@ def _replace_call(tokens, start, end, args, tmpl): tokens[start:end] = [Token('CODE', src)] +def _replace_yield(tokens, i): + in_token = _find_token(tokens, i, 'in') + colon = _find_block_start(tokens, i) + block = Block.find(tokens, i, trim_end=True) + container = tokens_to_src(tokens[in_token + 1:colon]).strip() + tokens[i:block.end] = [Token('CODE', 'yield from {}\n'.format(container))] + + def _fix_py3_plus(contents_text): try: ast_obj = ast_parse(contents_text) @@ -1403,6 +1468,7 @@ def _fix_py3_plus(contents_text): visitor.six_type_ctx, visitor.six_with_metaclass, visitor.super_calls, + visitor.yield_from_fors, )): return contents_text @@ -1525,6 +1591,8 @@ def _fix_py3_plus(contents_text): if any(tok.name == 'NL' for tok in tokens[i:end]): continue _replace_call(tokens, i, end, func_args, '{args[0]}') + elif token.offset in visitor.yield_from_fors: + _replace_yield(tokens, i) return tokens_to_src(tokens)
asottile/pyupgrade
41b9a46a02c0086c4e8b25eebea8f74304b327c1
diff --git a/tests/pyupgrade_test.py b/tests/pyupgrade_test.py index 070c9fe..90b681b 100644 --- a/tests/pyupgrade_test.py +++ b/tests/pyupgrade_test.py @@ -17,9 +17,11 @@ from pyupgrade import _imports_unicode_literals from pyupgrade import _is_bytestring from pyupgrade import _percent_to_format from pyupgrade import _simplify_conversion_flag +from pyupgrade import fields_same from pyupgrade import main from pyupgrade import parse_format from pyupgrade import parse_percent_format +from pyupgrade import targets_same from pyupgrade import unparse_parsed_string @@ -1433,6 +1435,143 @@ def test_fix_classes_py3only(s, expected): assert _fix_py3_plus(s) == expected [email protected]( + ('s', 'expected'), + ( + ( + 'def f():\n' + ' for x in y:\n' + ' yield x', + 'def f():\n' + ' yield from y\n', + ), + ( + 'def f():\n' + ' for x in [1, 2, 3]:\n' + ' yield x', + 'def f():\n' + ' yield from [1, 2, 3]\n', + ), + ( + 'def f():\n' + ' for x in {x for x in y}:\n' + ' yield x', + 'def f():\n' + ' yield from {x for x in y}\n', + ), + ( + 'def f():\n' + ' for x in (1, 2, 3):\n' + ' yield x', + 'def f():\n' + ' yield from (1, 2, 3)\n', + ), + ( + 'def f():\n' + ' for x, y in {3: "x", 6: "y"}:\n' + ' yield x, y', + 'def f():\n' + ' yield from {3: "x", 6: "y"}\n', + ), + ( + 'def f(): # Comment one\n' + ' # Comment two\n' + ' for x, y in { # Comment three\n' + ' 3: "x", # Comment four\n' + ' # Comment five\n' + ' 6: "y" # Comment six\n' + ' }: # Comment seven\n' + ' # Comment eight\n' + ' yield x, y # Comment nine\n' + ' # Comment ten', + 'def f(): # Comment one\n' + ' # Comment two\n' + ' yield from { # Comment three\n' + ' 3: "x", # Comment four\n' + ' # Comment five\n' + ' 6: "y" # Comment six\n' + ' }\n', + ), + ( + 'def f():\n' + ' for x, y in [{3: (3, [44, "long ss"]), 6: "y"}]:\n' + ' yield x, y', + 'def f():\n' + ' yield from [{3: (3, [44, "long ss"]), 6: "y"}]\n', + ), + ( + 'def f():\n' + ' for x, y in z():\n' + ' yield x, y', + 'def f():\n' + ' yield from z()\n', + ), + ( + 'def f():\n' + ' def func():\n' + ' # This comment is preserved\n' + '\n' + ' for x, y in z(): # Comment one\n' + '\n' + ' # Commment two\n' + ' yield x, y # Comment three\n' + ' # Comment four\n' + '\n\n' + '# Comment\n' + 'def g():\n' + ' print(3)', + 'def f():\n' + ' def func():\n' + ' # This comment is preserved\n' + '\n' + ' yield from z()\n' + '\n\n' + '# Comment\n' + 'def g():\n' + ' print(3)', + ), + ), +) +def test_fix_yield_from(s, expected): + assert _fix_py3_plus(s) == expected + + [email protected]( + 's', + ( + 'def f():\n' + ' for x in z:\n' + ' yield y', + 'def f():\n' + ' for x, y in z:\n' + ' yield x', + 'def f():\n' + ' for x, y in z:\n' + ' yield y', + 'def f():\n' + ' for a, b in z:\n' + ' yield x, y', + 'def f():\n' + ' for x, y in z:\n' + ' yield y, x', + 'def f():\n' + ' for x, y, c in z:\n' + ' yield x, y', + 'def f():\n' + ' for x in z:\n' + ' x = 22\n' + ' yield x', + 'def f():\n' + ' for x in z:\n' + ' yield x\n' + ' else:\n' + ' print("boom!")\n', + ), +) +def test_fix_yield_from_noop(s): + assert _fix_py3_plus(s) == s + + @pytest.mark.parametrize( 's', ( @@ -1918,3 +2057,14 @@ def test_noop_token_error(tmpdir): '5\\\n', ) assert main((f.strpath, '--py36-plus')) == 0 + + +def test_targets_same(): + assert targets_same(ast.parse('global a, b'), ast.parse('global a, b')) + assert not targets_same(ast.parse('global a'), ast.parse('global b')) + + +def test_fields_same(): + def get_body(expr): + return ast.parse(expr).body[0].value + assert not fields_same(get_body('x'), get_body('1'))
for x in y: yield x => yield from y No need for `async for` support according to [this](https://www.python.org/dev/peps/pep-0525/#asynchronous-yield-from) Here's an ast parser to detect this, just need the tokenization to rewrite it: ```python class Visitor(ast.NodeVisitor): def __init__(self, filename): self.filename = filename def visit_For(self, node: ast.For): if ( isinstance(node.target, ast.Name) and len(node.body) == 1 and isinstance(node.body[0], ast.Expr) and isinstance(node.body[0].value, ast.Yield) and isinstance(node.body[0].value.value, ast.Name) and node.target.id == node.body[0].value.value.id ): print(f'{self.filename}:{node.lineno}: could be yield from') self.generic_visit(node) ```
0.0
41b9a46a02c0086c4e8b25eebea8f74304b327c1
[ "tests/pyupgrade_test.py::test_roundtrip_text[]", "tests/pyupgrade_test.py::test_roundtrip_text[foo]", "tests/pyupgrade_test.py::test_roundtrip_text[{}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0}]", "tests/pyupgrade_test.py::test_roundtrip_text[{named}]", "tests/pyupgrade_test.py::test_roundtrip_text[{!r}]", "tests/pyupgrade_test.py::test_roundtrip_text[{:>5}]", "tests/pyupgrade_test.py::test_roundtrip_text[{{]", "tests/pyupgrade_test.py::test_roundtrip_text[}}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0!s:15}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/pyupgrade_test.py::test_sets[set()-set()]", "tests/pyupgrade_test.py::test_sets[set((\\n))-set((\\n))]", "tests/pyupgrade_test.py::test_sets[set", "tests/pyupgrade_test.py::test_sets[set(())-set()]", "tests/pyupgrade_test.py::test_sets[set([])-set()]", "tests/pyupgrade_test.py::test_sets[set((", "tests/pyupgrade_test.py::test_sets[set((1,", "tests/pyupgrade_test.py::test_sets[set([1,", "tests/pyupgrade_test.py::test_sets[set(x", "tests/pyupgrade_test.py::test_sets[set([x", "tests/pyupgrade_test.py::test_sets[set((x", "tests/pyupgrade_test.py::test_sets[set(((1,", "tests/pyupgrade_test.py::test_sets[set((a,", "tests/pyupgrade_test.py::test_sets[set([(1,", "tests/pyupgrade_test.py::test_sets[set(\\n", "tests/pyupgrade_test.py::test_sets[set([((1,", "tests/pyupgrade_test.py::test_sets[set((((1,", "tests/pyupgrade_test.py::test_sets[set(\\n(1,", "tests/pyupgrade_test.py::test_sets[set((\\n1,\\n2,\\n))\\n-{\\n1,\\n2,\\n}\\n]", "tests/pyupgrade_test.py::test_sets[set((frozenset(set((1,", "tests/pyupgrade_test.py::test_sets[set((1,))-{1}]", "tests/pyupgrade_test.py::test_dictcomps[x", "tests/pyupgrade_test.py::test_dictcomps[dict()-dict()]", "tests/pyupgrade_test.py::test_dictcomps[(-(]", "tests/pyupgrade_test.py::test_dictcomps[dict", "tests/pyupgrade_test.py::test_dictcomps[dict((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([(a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a),", "tests/pyupgrade_test.py::test_dictcomps[dict((k,", "tests/pyupgrade_test.py::test_dictcomps[dict(\\n", "tests/pyupgrade_test.py::test_dictcomps[x(\\n", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal_noop[x", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is`]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[string]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[unicode", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[bytes]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[float]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[compound", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[multi-line", "tests/pyupgrade_test.py::test_format_literals[\"{0}\"format(1)-\"{0}\"format(1)]", "tests/pyupgrade_test.py::test_format_literals['{}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{'.format(1)-'{'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['}'.format(1)-'}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals[x", "tests/pyupgrade_test.py::test_format_literals['{0}", "tests/pyupgrade_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{0:x}'.format(30)-'{:x}'.format(30)]", "tests/pyupgrade_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/pyupgrade_test.py::test_format_literals['{0}'", "tests/pyupgrade_test.py::test_format_literals[print(\\n", "tests/pyupgrade_test.py::test_format_literals['{0:<{1}}'.format(1,", "tests/pyupgrade_test.py::test_imports_unicode_literals[import", "tests/pyupgrade_test.py::test_imports_unicode_literals[from", "tests/pyupgrade_test.py::test_imports_unicode_literals[x", "tests/pyupgrade_test.py::test_imports_unicode_literals[\"\"\"docstring\"\"\"\\nfrom", "tests/pyupgrade_test.py::test_unicode_literals[(-False-(]", "tests/pyupgrade_test.py::test_unicode_literals[u''-False-u'']", "tests/pyupgrade_test.py::test_unicode_literals[u''-True-'']", "tests/pyupgrade_test.py::test_unicode_literals[from", "tests/pyupgrade_test.py::test_unicode_literals[\"\"\"with", "tests/pyupgrade_test.py::test_unicode_literals[Regression:", "tests/pyupgrade_test.py::test_fix_ur_literals[basic", "tests/pyupgrade_test.py::test_fix_ur_literals[upper", "tests/pyupgrade_test.py::test_fix_ur_literals[with", "tests/pyupgrade_test.py::test_fix_ur_literals[emoji]", "tests/pyupgrade_test.py::test_fix_ur_literals_gets_fixed_before_u_removed", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'\\\\d']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\"\"\\\\d\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'''\\\\d''']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[rb\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\r\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\N{SNOWMAN}\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\d\"-r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\n\\\\d\"-\"\\\\n\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[u\"\\\\d\"-u\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\d\"-br\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\8\"-r\"\\\\8\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\9\"-r\"\\\\9\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\u2603\"-br\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\n\\\\q\"\"\"-\"\"\"\\\\\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\n\\\\q\"\"\"-\"\"\"\\\\\\r\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\\\q\"\"\"-\"\"\"\\\\\\r\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N\"-r\"\\\\N\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N\\\\n\"-\"\\\\\\\\N\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N{SNOWMAN}\\\\q\"-\"\\\\N{SNOWMAN}\\\\\\\\q\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\N{SNOWMAN}\"-br\"\\\\N{SNOWMAN}\"]", "tests/pyupgrade_test.py::test_noop_octal_literals[0]", "tests/pyupgrade_test.py::test_noop_octal_literals[00]", "tests/pyupgrade_test.py::test_noop_octal_literals[1]", "tests/pyupgrade_test.py::test_noop_octal_literals[12345]", "tests/pyupgrade_test.py::test_noop_octal_literals[1.2345]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((1,", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(())]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((\\n))]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[sum((block.code", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[def", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"foo{}\".format(1)))-print(\"foo{}\".format(1))]", "tests/pyupgrade_test.py::test_fix_extra_parens[print((((1))))-print(1)]", "tests/pyupgrade_test.py::test_fix_extra_parens[print(\\n", "tests/pyupgrade_test.py::test_fix_extra_parens[extra", "tests/pyupgrade_test.py::test_is_bytestring_true[b'']", "tests/pyupgrade_test.py::test_is_bytestring_true[b\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B'']", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''0]", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''1]", "tests/pyupgrade_test.py::test_is_bytestring_false[]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false['']", "tests/pyupgrade_test.py::test_is_bytestring_false[u\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"b\"]", "tests/pyupgrade_test.py::test_parse_percent_format[\"\"-expected0]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%%\"-expected1]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s\"-expected2]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(hi)s\"-expected4]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%()s\"-expected5]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%#o\"-expected6]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%", "tests/pyupgrade_test.py::test_parse_percent_format[\"%5d\"-expected8]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%*d\"-expected9]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.f\"-expected10]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.5f\"-expected11]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.*f\"-expected12]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%ld\"-expected13]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(complete)#4.4f\"-expected14]", "tests/pyupgrade_test.py::test_percent_to_format[%s-{}]", "tests/pyupgrade_test.py::test_percent_to_format[%%%s-%{}]", "tests/pyupgrade_test.py::test_percent_to_format[%(foo)s-{foo}]", "tests/pyupgrade_test.py::test_percent_to_format[%2f-{:2f}]", "tests/pyupgrade_test.py::test_percent_to_format[%r-{!r}]", "tests/pyupgrade_test.py::test_percent_to_format[%a-{!a}]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[-]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[", "tests/pyupgrade_test.py::test_simplify_conversion_flag[#0-", "tests/pyupgrade_test.py::test_simplify_conversion_flag[--<]", "tests/pyupgrade_test.py::test_percent_format_noop[\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[b\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%d\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%i\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%u\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%c\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%#o\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%()s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%4%\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2r\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2a\"", "tests/pyupgrade_test.py::test_percent_format_noop[i", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(1)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(a)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(ab)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(and)s\"", "tests/pyupgrade_test.py::test_percent_format[\"trivial\"", "tests/pyupgrade_test.py::test_percent_format[\"%s\"", "tests/pyupgrade_test.py::test_percent_format[\"%s%%", "tests/pyupgrade_test.py::test_percent_format[\"%3f\"", "tests/pyupgrade_test.py::test_percent_format[\"%-5s\"", "tests/pyupgrade_test.py::test_percent_format[\"%9s\"", "tests/pyupgrade_test.py::test_percent_format[\"brace", "tests/pyupgrade_test.py::test_percent_format[\"%(k)s\"", "tests/pyupgrade_test.py::test_percent_format[\"%(to_list)s\"", "tests/pyupgrade_test.py::test_fix_super_noop[x(]", "tests/pyupgrade_test.py::test_fix_super_noop[class", "tests/pyupgrade_test.py::test_fix_super_noop[def", "tests/pyupgrade_test.py::test_fix_super[class", "tests/pyupgrade_test.py::test_fix_classes_noop[x", "tests/pyupgrade_test.py::test_fix_classes_noop[class", "tests/pyupgrade_test.py::test_fix_classes[class", "tests/pyupgrade_test.py::test_fix_classes[import", "tests/pyupgrade_test.py::test_fix_classes[from", "tests/pyupgrade_test.py::test_fix_six_noop[x", "tests/pyupgrade_test.py::test_fix_six_noop[from", "tests/pyupgrade_test.py::test_fix_six_noop[@mydec\\nclass", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(\"\\xa3\"))]", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(", "tests/pyupgrade_test.py::test_fix_six_noop[class", "tests/pyupgrade_test.py::test_fix_six_noop[six.reraise(*err)]", "tests/pyupgrade_test.py::test_fix_six_noop[six.b(*a)]", "tests/pyupgrade_test.py::test_fix_six_noop[six.u(*a)]", "tests/pyupgrade_test.py::test_fix_six_noop[@six.add_metaclass(*a)\\nclass", "tests/pyupgrade_test.py::test_fix_six[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six[weird", "tests/pyupgrade_test.py::test_fix_six[issubclass(tp,", "tests/pyupgrade_test.py::test_fix_six[STRING_TYPES", "tests/pyupgrade_test.py::test_fix_six[from", "tests/pyupgrade_test.py::test_fix_six[six.b(\"123\")-b\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(r\"123\")-br\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(\"\\\\x12\\\\xef\")-b\"\\\\x12\\\\xef\"]", "tests/pyupgrade_test.py::test_fix_six[six.byte2int(b\"f\")-b\"f\"[0]]", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/pyupgrade_test.py::test_fix_six[six.get_unbound_method(meth)\\n-meth\\n]", "tests/pyupgrade_test.py::test_fix_six[six.indexbytes(bs,", "tests/pyupgrade_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/pyupgrade_test.py::test_fix_six[six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(tp,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(\\n", "tests/pyupgrade_test.py::test_fix_six[class", "tests/pyupgrade_test.py::test_fix_six[basic", "tests/pyupgrade_test.py::test_fix_six[add_metaclass,", "tests/pyupgrade_test.py::test_fix_classes_py3only[class", "tests/pyupgrade_test.py::test_fix_classes_py3only[from", "tests/pyupgrade_test.py::test_fix_yield_from[def", "tests/pyupgrade_test.py::test_fix_yield_from_noop[def", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(1)]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(\"foo\"\\n\"bar\")]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(*a)]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(\"foo\",", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(**k)]", "tests/pyupgrade_test.py::test_fix_native_literals[str(\"foo\")-\"foo\"]", "tests/pyupgrade_test.py::test_fix_native_literals[str(\"\"\"\\nfoo\"\"\")-\"\"\"\\nfoo\"\"\"]", "tests/pyupgrade_test.py::test_fix_encode[\"asd\".encode(\"utf-8\")-\"asd\".encode()]", "tests/pyupgrade_test.py::test_fix_encode[\"asd\".encode(\"utf8\")-\"asd\".encode()]", "tests/pyupgrade_test.py::test_fix_encode[\"asd\".encode(\"UTF-8\")-\"asd\".encode()]", "tests/pyupgrade_test.py::test_fix_encode[sys.stdout.buffer.write(\\n", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(\"unknown-codec\")]", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(\"ascii\")]", "tests/pyupgrade_test.py::test_fix_encode_noop[x=\"asd\"\\nx.encode(\"utf-8\")]", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(\"utf-8\",", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(encoding=\"utf-8\")]", "tests/pyupgrade_test.py::test_fix_py2_block_noop[if", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY2]", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY2,", "tests/pyupgrade_test.py::test_fix_py2_blocks[not", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY3]", "tests/pyupgrade_test.py::test_fix_py2_blocks[indented", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY2", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY3,", "tests/pyupgrade_test.py::test_fix_fstrings_noop[(]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\"", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{foo}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{0}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[b\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{1}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{.x}", "tests/pyupgrade_test.py::test_fix_fstrings[\"hello", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped,", "tests/pyupgrade_test.py::test_main_trivial", "tests/pyupgrade_test.py::test_main_noop", "tests/pyupgrade_test.py::test_main_changes_a_file", "tests/pyupgrade_test.py::test_main_keeps_line_endings", "tests/pyupgrade_test.py::test_main_syntax_error", "tests/pyupgrade_test.py::test_main_non_utf8_bytes", "tests/pyupgrade_test.py::test_keep_percent_format", "tests/pyupgrade_test.py::test_py3_plus_argument_unicode_literals", "tests/pyupgrade_test.py::test_py3_plus_super", "tests/pyupgrade_test.py::test_py3_plus_new_style_classes", "tests/pyupgrade_test.py::test_py36_plus_fstrings", "tests/pyupgrade_test.py::test_noop_token_error", "tests/pyupgrade_test.py::test_targets_same", "tests/pyupgrade_test.py::test_fields_same" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-05-25 17:05:09+00:00
mit
1,140
asottile__pyupgrade-153
diff --git a/pyupgrade.py b/pyupgrade.py index ac8bd70..b26904c 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -961,6 +961,10 @@ class FindPy3Plus(ast.NodeVisitor): self.bases_to_remove = set() self.encode_calls = {} + + self.if_py2_blocks = set() + self.if_py3_blocks = set() + self.native_literals = set() self._six_from_imports = set() @@ -1106,11 +1110,162 @@ class FindPy3Plus(ast.NodeVisitor): self.generic_visit(node) - def generic_visit(self, node): + def visit_If(self, node): # type: (ast.If) -> None + if node.orelse and not isinstance(node.orelse[0], ast.If): + if ( + # if six.PY2: + self._is_six(node.test, ('PY2',)) or + # if not six.PY3: + ( + isinstance(node.test, ast.UnaryOp) and + isinstance(node.test.op, ast.Not) and + self._is_six(node.test.operand, ('PY3',)) + ) + ): + self.if_py2_blocks.add(_ast_to_offset(node)) + elif ( + # if six.PY3: + self._is_six(node.test, 'PY3') or + # if not six.PY2: + ( + isinstance(node.test, ast.UnaryOp) and + isinstance(node.test.op, ast.Not) and + self._is_six(node.test.operand, ('PY2',)) + ) + ): + self.if_py3_blocks.add(_ast_to_offset(node)) + self.generic_visit(node) + + def generic_visit(self, node): # type: (ast.AST) -> None self._previous_node = node super(FindPy3Plus, self).generic_visit(node) +def _fixup_dedent_tokens(tokens): + """For whatever reason the DEDENT / UNIMPORTANT_WS tokens are misordered + + | if True: + | if True: + | pass + | else: + |^ ^- DEDENT + |+----UNIMPORTANT_WS + """ + for i, token in enumerate(tokens): + if token.name == UNIMPORTANT_WS and tokens[i + 1].name == 'DEDENT': + tokens[i], tokens[i + 1] = tokens[i + 1], tokens[i] + + +def _find_block_start(tokens, i): + depth = 0 + while depth or tokens[i].src != ':': + depth += {'(': 1, ')': -1}.get(tokens[i].src, 0) + i += 1 + return i + + +class Block( + collections.namedtuple('Block', ('start', 'block', 'end', 'line')), +): + __slots__ = () + + def _initial_indent(self, tokens): + if tokens[self.start].src.isspace(): + return len(tokens[self.start].src) + else: + return 0 + + def _minimum_indent(self, tokens): + block_indent = None + for i in range(self.block, self.end): + if ( + tokens[i - 1].name in ('NL', 'NEWLINE') and + tokens[i].name in ('INDENT', UNIMPORTANT_WS) + ): + token_indent = len(tokens[i].src) + if block_indent is None: + block_indent = token_indent + else: + block_indent = min(block_indent, token_indent) + return block_indent + + def dedent(self, tokens): + if self.line: + return + diff = self._minimum_indent(tokens) - self._initial_indent(tokens) + for i in range(self.block, self.end): + if ( + tokens[i - 1].name in ('NL', 'NEWLINE') and + tokens[i].name in ('INDENT', UNIMPORTANT_WS) + ): + tokens[i] = tokens[i]._replace(src=tokens[i].src[diff:]) + + def _trim_end(self, tokens): + """the tokenizer reports the end of the block at the beginning of + the next block + """ + i = last_token = self.end - 1 + while tokens[i].name in NON_CODING_TOKENS | {'DEDENT', 'NEWLINE'}: + # if we find an indented comment inside our block, keep it + if ( + tokens[i].name in {'NL', 'NEWLINE'} and + tokens[i + 1].name == UNIMPORTANT_WS and + len(tokens[i + 1].src) > self._initial_indent(tokens) + ): + break + # otherwise we've found another line to remove + elif tokens[i].name in {'NL', 'NEWLINE'}: + last_token = i + i -= 1 + return self._replace(end=last_token + 1) + + @classmethod + def find(cls, tokens, i, trim_end=False): + if i > 0 and tokens[i - 1].name in {'INDENT', UNIMPORTANT_WS}: + i -= 1 + start = i + colon = _find_block_start(tokens, i) + + j = colon + 1 + while ( + tokens[j].name != 'NEWLINE' and + tokens[j].name in NON_CODING_TOKENS + ): + j += 1 + + if tokens[j].name == 'NEWLINE': # multi line block + block = j + 1 + while tokens[j].name != 'INDENT': + j += 1 + level = 1 + j += 1 + while level: + level += {'INDENT': 1, 'DEDENT': -1}.get(tokens[j].name, 0) + j += 1 + if trim_end: + return cls(start, block, j, line=False)._trim_end(tokens) + else: + return cls(start, block, j, line=False) + else: # single line block + block = j + # search forward until the NEWLINE token + while tokens[j].name not in {'NEWLINE', 'ENDMARKER'}: + j += 1 + # we also want to include the newline in the block + if tokens[j].name == 'NEWLINE': # pragma: no branch (PY2 only) + j += 1 + return cls(start, block, j, line=True) + + +def _find_if_else_block(tokens, i): + if_block = Block.find(tokens, i) + i = if_block.end + while tokens[i].src != 'else': + i += 1 + else_block = Block.find(tokens, i, trim_end=True) + return if_block, else_block + + def _remove_decorator(tokens, i): while tokens[i - 1].src != '@': i -= 1 @@ -1236,6 +1391,8 @@ def _fix_py3_plus(contents_text): if not any(( visitor.bases_to_remove, visitor.encode_calls, + visitor.if_py2_blocks, + visitor.if_py3_blocks, visitor.native_literals, visitor.six_add_metaclass, visitor.six_b, @@ -1254,6 +1411,8 @@ def _fix_py3_plus(contents_text): except tokenize.TokenError: # pragma: no cover (bpo-2180) return contents_text + _fixup_dedent_tokens(tokens) + def _replace(i, mapping, node): new_token = Token('CODE', _get_tmpl(mapping, node)) if isinstance(node, ast.Name): @@ -1269,6 +1428,21 @@ def _fix_py3_plus(contents_text): continue elif token.offset in visitor.bases_to_remove: _remove_base_class(tokens, i) + elif token.offset in visitor.if_py2_blocks: + if tokens[i].src != 'if': + continue + if_block, else_block = _find_if_else_block(tokens, i) + + else_block.dedent(tokens) + del tokens[if_block.start:else_block.block] + elif token.offset in visitor.if_py3_blocks: + if tokens[i].src != 'if': + continue + if_block, else_block = _find_if_else_block(tokens, i) + + if_block.dedent(tokens) + del tokens[if_block.end:else_block.end] + del tokens[if_block.start:if_block.block] elif token.offset in visitor.six_type_ctx: _replace(i, SIX_TYPE_CTX_ATTRS, visitor.six_type_ctx[token.offset]) elif token.offset in visitor.six_simple: @@ -1305,16 +1479,13 @@ def _fix_py3_plus(contents_text): j = i + 1 while tokens[j].src != 'class': j += 1 + class_token = j # then search forward for a `:` token, not inside a brace - depth = 0 + j = _find_block_start(tokens, j) last_paren = -1 - while depth or tokens[j].src != ':': - if tokens[j].src == '(': - depth += 1 - elif tokens[j].src == ')': - depth -= 1 - last_paren = j - j += 1 + for k in range(class_token, j): + if tokens[k].src == ')': + last_paren = k if last_paren == -1: tokens.insert(j, Token('CODE', '({})'.format(metaclass)))
asottile/pyupgrade
8ba7b8b1844f76d2f3a8233cb1a632f3358fea9f
diff --git a/tests/pyupgrade_test.py b/tests/pyupgrade_test.py index 87ac751..070c9fe 100644 --- a/tests/pyupgrade_test.py +++ b/tests/pyupgrade_test.py @@ -1493,6 +1493,274 @@ def test_fix_encode_noop(s): assert _fix_py3_plus(s) == s [email protected]( + 's', + ( + # we timidly skip `if` without `else` as it could cause a SyntaxError + 'if six.PY2:\n' + ' pass', + # here's the case where it causes a SyntaxError + 'if True:\n' + ' if six.PY2:\n' + ' pass\n', + # for now we don't attempt to rewrite `elif` + 'if False:\n' + ' pass\n' + 'elif six.PY3:\n' + ' pass\n' + 'else:\n' + ' pass\n', + 'if False:\n' + ' pass\n' + 'elif six.PY2:\n' + ' pass\n' + 'else:\n' + ' pass\n', + ), +) +def test_fix_py2_block_noop(s): + assert _fix_py3_plus(s) == s + + [email protected]( + ('s', 'expected'), + ( + pytest.param( + 'if six.PY2:\n' + ' print("py2")\n' + 'else:\n' + ' print("py3")\n', + + 'print("py3")\n', + + id='six.PY2', + ), + pytest.param( + 'if six.PY2:\n' + ' if True:\n' + ' print("py2!")\n' + ' else:\n' + ' print("???")\n' + 'else:\n' + ' print("py3")\n', + + 'print("py3")\n', + + id='six.PY2, nested ifs', + ), + pytest.param( + 'if six.PY2: print("PY2!")\n' + 'else: print("PY3!")\n', + + 'print("PY3!")\n', + + id='six.PY2, oneline', + ), + pytest.param( + 'if six.PY2: print("PY2!")\n' + 'else: print("PY3!")', + + 'print("PY3!")', + + id='six.PY2, oneline, no newline at end of file', + ), + pytest.param( + 'if True:\n' + ' if six.PY2:\n' + ' print("PY2")\n' + ' else:\n' + ' print("PY3")\n', + + 'if True:\n' + ' print("PY3")\n', + + id='six.PY2, indented', + ), + pytest.param( + 'if six.PY2: print(1 if True else 3)\n' + 'else:\n' + ' print("py3")\n', + + 'print("py3")\n', + + id='six.PY2, `else` token inside oneline if\n', + ), + pytest.param( + 'if six.PY2:\n' + ' def f():\n' + ' print("py2")\n' + 'else:\n' + ' def f():\n' + ' print("py3")\n', + + 'def f():\n' + ' print("py3")\n', + + id='six.PY2, multiple indents in block', + ), + pytest.param( + 'if not six.PY2:\n' + ' print("py3")\n' + 'else:\n' + ' print("py2")\n' + '\n' + '\n' + 'x = 1\n', + + 'print("py3")\n' + '\n' + '\n' + 'x = 1\n', + + id='not six.PY2, remove second block', + ), + pytest.param( + 'if not six.PY2:\n' + ' print("py3")\n' + 'else:\n' + ' print("py2")', + + 'print("py3")\n', + + id='not six.PY2, no end of line', + ), + pytest.param( + 'if not six.PY2:\n' + ' print("py3")\n' + 'else:\n' + ' print("py2")\n' + ' # ohai\n' + '\n' + 'x = 1\n', + + 'print("py3")\n' + '\n' + 'x = 1\n', + + id='not six.PY2: else block ends in comment', + ), + pytest.param( + 'if not six.PY2: print("py3")\n' + 'else: print("py2")\n', + + 'print("py3")\n', + + id='not six.PY2, else is single line', + ), + pytest.param( + 'if six.PY3:\n' + ' print("py3")\n' + 'else:\n' + ' print("py2")\n', + + 'print("py3")\n', + + id='six.PY3', + ), + pytest.param( + 'if True:\n' + ' if six.PY3:\n' + ' print("py3")\n' + ' else:\n' + ' print("py2")\n', + + 'if True:\n' + ' print("py3")\n', + + id='indented six.PY3', + ), + pytest.param( + 'from six import PY3\n' + 'if not PY3:\n' + ' print("py2")\n' + 'else:\n' + ' print("py3")\n', + + 'from six import PY3\n' + 'print("py3")\n', + + id='not PY3', + ), + pytest.param( + 'def f():\n' + ' if six.PY2:\n' + ' try:\n' + ' yield\n' + ' finally:\n' + ' pass\n' + ' else:\n' + ' yield\n', + + 'def f():\n' + ' yield\n', + + id='six.PY2, finally', + ), + pytest.param( + 'class C:\n' + ' def g():\n' + ' pass\n' + '\n' + ' if six.PY2:\n' + ' def f(py2):\n' + ' pass\n' + ' else:\n' + ' def f(py3):\n' + ' pass\n' + '\n' + ' def h():\n' + ' pass\n', + + 'class C:\n' + ' def g():\n' + ' pass\n' + '\n' + ' def f(py3):\n' + ' pass\n' + '\n' + ' def h():\n' + ' pass\n', + + id='six.PY2 in class\n', + ), + pytest.param( + 'if True:\n' + ' if six.PY2:\n' + ' 2\n' + ' else:\n' + ' 3\n' + '\n' + ' # comment\n', + + 'if True:\n' + ' 3\n' + '\n' + ' # comment\n', + + id='six.PY2, comment after', + ), + pytest.param( + 'if True:\n' + ' if six.PY3:\n' + ' 3\n' + ' else:\n' + ' 2\n' + '\n' + ' # comment\n', + + 'if True:\n' + ' 3\n' + '\n' + ' # comment\n', + + id='six.PY3, comment after', + ), + ), +) +def test_fix_py2_blocks(s, expected): + assert _fix_py3_plus(s) == expected + + @pytest.mark.parametrize( 's', (
Rewrite `if PY2:` blocks in `--py3-plus` Ideally handle these different cases: ```python # input from six import PY2 if PY2: x = 5 else: x = 6 # output x = 6 ``` But also for ```python sys.version_info[0] == 2 sys.version_info < (3,) ``` etc. - [x] `six.PY2` - [x] `six.PY3` - [x] `not six.PY2` - [x] `not six.PY3` - [ ] `sys.version_info >= (3,)` - [ ] `sys.version_info < (3,)` - [ ] `sys.version_info[0] == 2` - [ ] `sys.version_info[0] == 3`
0.0
8ba7b8b1844f76d2f3a8233cb1a632f3358fea9f
[ "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY2]", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY2,", "tests/pyupgrade_test.py::test_fix_py2_blocks[not", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY3]", "tests/pyupgrade_test.py::test_fix_py2_blocks[indented", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY2", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY3," ]
[ "tests/pyupgrade_test.py::test_roundtrip_text[]", "tests/pyupgrade_test.py::test_roundtrip_text[foo]", "tests/pyupgrade_test.py::test_roundtrip_text[{}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0}]", "tests/pyupgrade_test.py::test_roundtrip_text[{named}]", "tests/pyupgrade_test.py::test_roundtrip_text[{!r}]", "tests/pyupgrade_test.py::test_roundtrip_text[{:>5}]", "tests/pyupgrade_test.py::test_roundtrip_text[{{]", "tests/pyupgrade_test.py::test_roundtrip_text[}}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0!s:15}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/pyupgrade_test.py::test_sets[set()-set()]", "tests/pyupgrade_test.py::test_sets[set((\\n))-set((\\n))]", "tests/pyupgrade_test.py::test_sets[set", "tests/pyupgrade_test.py::test_sets[set(())-set()]", "tests/pyupgrade_test.py::test_sets[set([])-set()]", "tests/pyupgrade_test.py::test_sets[set((", "tests/pyupgrade_test.py::test_sets[set((1,", "tests/pyupgrade_test.py::test_sets[set([1,", "tests/pyupgrade_test.py::test_sets[set(x", "tests/pyupgrade_test.py::test_sets[set([x", "tests/pyupgrade_test.py::test_sets[set((x", "tests/pyupgrade_test.py::test_sets[set(((1,", "tests/pyupgrade_test.py::test_sets[set((a,", "tests/pyupgrade_test.py::test_sets[set([(1,", "tests/pyupgrade_test.py::test_sets[set(\\n", "tests/pyupgrade_test.py::test_sets[set([((1,", "tests/pyupgrade_test.py::test_sets[set((((1,", "tests/pyupgrade_test.py::test_sets[set(\\n(1,", "tests/pyupgrade_test.py::test_sets[set((\\n1,\\n2,\\n))\\n-{\\n1,\\n2,\\n}\\n]", "tests/pyupgrade_test.py::test_sets[set((frozenset(set((1,", "tests/pyupgrade_test.py::test_sets[set((1,))-{1}]", "tests/pyupgrade_test.py::test_dictcomps[x", "tests/pyupgrade_test.py::test_dictcomps[dict()-dict()]", "tests/pyupgrade_test.py::test_dictcomps[(-(]", "tests/pyupgrade_test.py::test_dictcomps[dict", "tests/pyupgrade_test.py::test_dictcomps[dict((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([(a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a),", "tests/pyupgrade_test.py::test_dictcomps[dict((k,", "tests/pyupgrade_test.py::test_dictcomps[dict(\\n", "tests/pyupgrade_test.py::test_dictcomps[x(\\n", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal_noop[x", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is`]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[string]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[unicode", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[bytes]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[float]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[compound", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[multi-line", "tests/pyupgrade_test.py::test_format_literals[\"{0}\"format(1)-\"{0}\"format(1)]", "tests/pyupgrade_test.py::test_format_literals['{}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{'.format(1)-'{'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['}'.format(1)-'}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals[x", "tests/pyupgrade_test.py::test_format_literals['{0}", "tests/pyupgrade_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{0:x}'.format(30)-'{:x}'.format(30)]", "tests/pyupgrade_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/pyupgrade_test.py::test_format_literals['{0}'", "tests/pyupgrade_test.py::test_format_literals[print(\\n", "tests/pyupgrade_test.py::test_format_literals['{0:<{1}}'.format(1,", "tests/pyupgrade_test.py::test_imports_unicode_literals[import", "tests/pyupgrade_test.py::test_imports_unicode_literals[from", "tests/pyupgrade_test.py::test_imports_unicode_literals[x", "tests/pyupgrade_test.py::test_imports_unicode_literals[\"\"\"docstring\"\"\"\\nfrom", "tests/pyupgrade_test.py::test_unicode_literals[(-False-(]", "tests/pyupgrade_test.py::test_unicode_literals[u''-False-u'']", "tests/pyupgrade_test.py::test_unicode_literals[u''-True-'']", "tests/pyupgrade_test.py::test_unicode_literals[from", "tests/pyupgrade_test.py::test_unicode_literals[\"\"\"with", "tests/pyupgrade_test.py::test_unicode_literals[Regression:", "tests/pyupgrade_test.py::test_fix_ur_literals[basic", "tests/pyupgrade_test.py::test_fix_ur_literals[upper", "tests/pyupgrade_test.py::test_fix_ur_literals[with", "tests/pyupgrade_test.py::test_fix_ur_literals[emoji]", "tests/pyupgrade_test.py::test_fix_ur_literals_gets_fixed_before_u_removed", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'\\\\d']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\"\"\\\\d\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'''\\\\d''']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[rb\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\r\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\N{SNOWMAN}\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\d\"-r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\n\\\\d\"-\"\\\\n\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[u\"\\\\d\"-u\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\d\"-br\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\8\"-r\"\\\\8\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\9\"-r\"\\\\9\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\u2603\"-br\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\n\\\\q\"\"\"-\"\"\"\\\\\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\n\\\\q\"\"\"-\"\"\"\\\\\\r\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\\\q\"\"\"-\"\"\"\\\\\\r\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N\"-r\"\\\\N\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N\\\\n\"-\"\\\\\\\\N\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N{SNOWMAN}\\\\q\"-\"\\\\N{SNOWMAN}\\\\\\\\q\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\N{SNOWMAN}\"-br\"\\\\N{SNOWMAN}\"]", "tests/pyupgrade_test.py::test_noop_octal_literals[0]", "tests/pyupgrade_test.py::test_noop_octal_literals[00]", "tests/pyupgrade_test.py::test_noop_octal_literals[1]", "tests/pyupgrade_test.py::test_noop_octal_literals[12345]", "tests/pyupgrade_test.py::test_noop_octal_literals[1.2345]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((1,", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(())]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((\\n))]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[sum((block.code", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[def", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"foo{}\".format(1)))-print(\"foo{}\".format(1))]", "tests/pyupgrade_test.py::test_fix_extra_parens[print((((1))))-print(1)]", "tests/pyupgrade_test.py::test_fix_extra_parens[print(\\n", "tests/pyupgrade_test.py::test_fix_extra_parens[extra", "tests/pyupgrade_test.py::test_is_bytestring_true[b'']", "tests/pyupgrade_test.py::test_is_bytestring_true[b\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B'']", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''0]", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''1]", "tests/pyupgrade_test.py::test_is_bytestring_false[]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false['']", "tests/pyupgrade_test.py::test_is_bytestring_false[u\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"b\"]", "tests/pyupgrade_test.py::test_parse_percent_format[\"\"-expected0]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%%\"-expected1]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s\"-expected2]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(hi)s\"-expected4]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%()s\"-expected5]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%#o\"-expected6]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%", "tests/pyupgrade_test.py::test_parse_percent_format[\"%5d\"-expected8]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%*d\"-expected9]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.f\"-expected10]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.5f\"-expected11]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.*f\"-expected12]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%ld\"-expected13]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(complete)#4.4f\"-expected14]", "tests/pyupgrade_test.py::test_percent_to_format[%s-{}]", "tests/pyupgrade_test.py::test_percent_to_format[%%%s-%{}]", "tests/pyupgrade_test.py::test_percent_to_format[%(foo)s-{foo}]", "tests/pyupgrade_test.py::test_percent_to_format[%2f-{:2f}]", "tests/pyupgrade_test.py::test_percent_to_format[%r-{!r}]", "tests/pyupgrade_test.py::test_percent_to_format[%a-{!a}]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[-]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[", "tests/pyupgrade_test.py::test_simplify_conversion_flag[#0-", "tests/pyupgrade_test.py::test_simplify_conversion_flag[--<]", "tests/pyupgrade_test.py::test_percent_format_noop[\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[b\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%d\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%i\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%u\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%c\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%#o\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%()s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%4%\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2r\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2a\"", "tests/pyupgrade_test.py::test_percent_format_noop[i", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(1)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(a)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(ab)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(and)s\"", "tests/pyupgrade_test.py::test_percent_format[\"trivial\"", "tests/pyupgrade_test.py::test_percent_format[\"%s\"", "tests/pyupgrade_test.py::test_percent_format[\"%s%%", "tests/pyupgrade_test.py::test_percent_format[\"%3f\"", "tests/pyupgrade_test.py::test_percent_format[\"%-5s\"", "tests/pyupgrade_test.py::test_percent_format[\"%9s\"", "tests/pyupgrade_test.py::test_percent_format[\"brace", "tests/pyupgrade_test.py::test_percent_format[\"%(k)s\"", "tests/pyupgrade_test.py::test_percent_format[\"%(to_list)s\"", "tests/pyupgrade_test.py::test_fix_super_noop[x(]", "tests/pyupgrade_test.py::test_fix_super_noop[class", "tests/pyupgrade_test.py::test_fix_super_noop[def", "tests/pyupgrade_test.py::test_fix_super[class", "tests/pyupgrade_test.py::test_fix_classes_noop[x", "tests/pyupgrade_test.py::test_fix_classes_noop[class", "tests/pyupgrade_test.py::test_fix_classes[class", "tests/pyupgrade_test.py::test_fix_classes[import", "tests/pyupgrade_test.py::test_fix_classes[from", "tests/pyupgrade_test.py::test_fix_six_noop[x", "tests/pyupgrade_test.py::test_fix_six_noop[from", "tests/pyupgrade_test.py::test_fix_six_noop[@mydec\\nclass", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(\"\\xa3\"))]", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(", "tests/pyupgrade_test.py::test_fix_six_noop[class", "tests/pyupgrade_test.py::test_fix_six_noop[six.reraise(*err)]", "tests/pyupgrade_test.py::test_fix_six_noop[six.b(*a)]", "tests/pyupgrade_test.py::test_fix_six_noop[six.u(*a)]", "tests/pyupgrade_test.py::test_fix_six_noop[@six.add_metaclass(*a)\\nclass", "tests/pyupgrade_test.py::test_fix_six[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six[weird", "tests/pyupgrade_test.py::test_fix_six[issubclass(tp,", "tests/pyupgrade_test.py::test_fix_six[STRING_TYPES", "tests/pyupgrade_test.py::test_fix_six[from", "tests/pyupgrade_test.py::test_fix_six[six.b(\"123\")-b\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(r\"123\")-br\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(\"\\\\x12\\\\xef\")-b\"\\\\x12\\\\xef\"]", "tests/pyupgrade_test.py::test_fix_six[six.byte2int(b\"f\")-b\"f\"[0]]", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/pyupgrade_test.py::test_fix_six[six.get_unbound_method(meth)\\n-meth\\n]", "tests/pyupgrade_test.py::test_fix_six[six.indexbytes(bs,", "tests/pyupgrade_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/pyupgrade_test.py::test_fix_six[six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(tp,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(\\n", "tests/pyupgrade_test.py::test_fix_six[class", "tests/pyupgrade_test.py::test_fix_six[basic", "tests/pyupgrade_test.py::test_fix_six[add_metaclass,", "tests/pyupgrade_test.py::test_fix_classes_py3only[class", "tests/pyupgrade_test.py::test_fix_classes_py3only[from", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(1)]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(\"foo\"\\n\"bar\")]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(*a)]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(\"foo\",", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(**k)]", "tests/pyupgrade_test.py::test_fix_native_literals[str(\"foo\")-\"foo\"]", "tests/pyupgrade_test.py::test_fix_native_literals[str(\"\"\"\\nfoo\"\"\")-\"\"\"\\nfoo\"\"\"]", "tests/pyupgrade_test.py::test_fix_encode[\"asd\".encode(\"utf-8\")-\"asd\".encode()]", "tests/pyupgrade_test.py::test_fix_encode[\"asd\".encode(\"utf8\")-\"asd\".encode()]", "tests/pyupgrade_test.py::test_fix_encode[\"asd\".encode(\"UTF-8\")-\"asd\".encode()]", "tests/pyupgrade_test.py::test_fix_encode[sys.stdout.buffer.write(\\n", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(\"unknown-codec\")]", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(\"ascii\")]", "tests/pyupgrade_test.py::test_fix_encode_noop[x=\"asd\"\\nx.encode(\"utf-8\")]", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(\"utf-8\",", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(encoding=\"utf-8\")]", "tests/pyupgrade_test.py::test_fix_py2_block_noop[if", "tests/pyupgrade_test.py::test_fix_fstrings_noop[(]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\"", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{foo}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{0}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[b\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{1}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{.x}", "tests/pyupgrade_test.py::test_fix_fstrings[\"hello", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped,", "tests/pyupgrade_test.py::test_main_trivial", "tests/pyupgrade_test.py::test_main_noop", "tests/pyupgrade_test.py::test_main_changes_a_file", "tests/pyupgrade_test.py::test_main_keeps_line_endings", "tests/pyupgrade_test.py::test_main_syntax_error", "tests/pyupgrade_test.py::test_main_non_utf8_bytes", "tests/pyupgrade_test.py::test_keep_percent_format", "tests/pyupgrade_test.py::test_py3_plus_argument_unicode_literals", "tests/pyupgrade_test.py::test_py3_plus_super", "tests/pyupgrade_test.py::test_py3_plus_new_style_classes", "tests/pyupgrade_test.py::test_py36_plus_fstrings", "tests/pyupgrade_test.py::test_noop_token_error" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-05-26 02:16:10+00:00
mit
1,141
asottile__pyupgrade-158
diff --git a/pyupgrade.py b/pyupgrade.py index 8d11da1..ac8bd70 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -1114,6 +1114,8 @@ class FindPy3Plus(ast.NodeVisitor): def _remove_decorator(tokens, i): while tokens[i - 1].src != '@': i -= 1 + if i > 1 and tokens[i - 2].name not in {'NEWLINE', 'NL'}: + i -= 1 end = i + 1 while tokens[end].name != 'NEWLINE': end += 1
asottile/pyupgrade
19aac5a327570d4252c07cd8ce52c7ba504fe8d8
diff --git a/tests/pyupgrade_test.py b/tests/pyupgrade_test.py index 7c76a51..87ac751 100644 --- a/tests/pyupgrade_test.py +++ b/tests/pyupgrade_test.py @@ -1387,6 +1387,16 @@ def test_fix_six_noop(s): id='add_metaclass, weird base that contains a :', ), + pytest.param( + 'if True:\n' + ' @six.add_metaclass(M)\n' + ' class C: pass\n', + + 'if True:\n' + ' class C(metaclass=M): pass\n', + + id='add_metaclass, indented', + ), ), ) def test_fix_six(s, expected):
`add_metaclass` rewrite indentation is strange when indented Currently: ```diff if True: - @six.add_metaclass(M) - class C: pass + class C(metaclass=M): pass ```
0.0
19aac5a327570d4252c07cd8ce52c7ba504fe8d8
[ "tests/pyupgrade_test.py::test_fix_six[add_metaclass," ]
[ "tests/pyupgrade_test.py::test_roundtrip_text[]", "tests/pyupgrade_test.py::test_roundtrip_text[foo]", "tests/pyupgrade_test.py::test_roundtrip_text[{}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0}]", "tests/pyupgrade_test.py::test_roundtrip_text[{named}]", "tests/pyupgrade_test.py::test_roundtrip_text[{!r}]", "tests/pyupgrade_test.py::test_roundtrip_text[{:>5}]", "tests/pyupgrade_test.py::test_roundtrip_text[{{]", "tests/pyupgrade_test.py::test_roundtrip_text[}}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0!s:15}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/pyupgrade_test.py::test_sets[set()-set()]", "tests/pyupgrade_test.py::test_sets[set((\\n))-set((\\n))]", "tests/pyupgrade_test.py::test_sets[set", "tests/pyupgrade_test.py::test_sets[set(())-set()]", "tests/pyupgrade_test.py::test_sets[set([])-set()]", "tests/pyupgrade_test.py::test_sets[set((", "tests/pyupgrade_test.py::test_sets[set((1,", "tests/pyupgrade_test.py::test_sets[set([1,", "tests/pyupgrade_test.py::test_sets[set(x", "tests/pyupgrade_test.py::test_sets[set([x", "tests/pyupgrade_test.py::test_sets[set((x", "tests/pyupgrade_test.py::test_sets[set(((1,", "tests/pyupgrade_test.py::test_sets[set((a,", "tests/pyupgrade_test.py::test_sets[set([(1,", "tests/pyupgrade_test.py::test_sets[set(\\n", "tests/pyupgrade_test.py::test_sets[set([((1,", "tests/pyupgrade_test.py::test_sets[set((((1,", "tests/pyupgrade_test.py::test_sets[set(\\n(1,", "tests/pyupgrade_test.py::test_sets[set((\\n1,\\n2,\\n))\\n-{\\n1,\\n2,\\n}\\n]", "tests/pyupgrade_test.py::test_sets[set((frozenset(set((1,", "tests/pyupgrade_test.py::test_sets[set((1,))-{1}]", "tests/pyupgrade_test.py::test_dictcomps[x", "tests/pyupgrade_test.py::test_dictcomps[dict()-dict()]", "tests/pyupgrade_test.py::test_dictcomps[(-(]", "tests/pyupgrade_test.py::test_dictcomps[dict", "tests/pyupgrade_test.py::test_dictcomps[dict((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([(a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a),", "tests/pyupgrade_test.py::test_dictcomps[dict((k,", "tests/pyupgrade_test.py::test_dictcomps[dict(\\n", "tests/pyupgrade_test.py::test_dictcomps[x(\\n", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal_noop[x", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is`]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[string]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[unicode", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[bytes]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[float]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[compound", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[multi-line", "tests/pyupgrade_test.py::test_format_literals[\"{0}\"format(1)-\"{0}\"format(1)]", "tests/pyupgrade_test.py::test_format_literals['{}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{'.format(1)-'{'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['}'.format(1)-'}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals[x", "tests/pyupgrade_test.py::test_format_literals['{0}", "tests/pyupgrade_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{0:x}'.format(30)-'{:x}'.format(30)]", "tests/pyupgrade_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/pyupgrade_test.py::test_format_literals['{0}'", "tests/pyupgrade_test.py::test_format_literals[print(\\n", "tests/pyupgrade_test.py::test_format_literals['{0:<{1}}'.format(1,", "tests/pyupgrade_test.py::test_imports_unicode_literals[import", "tests/pyupgrade_test.py::test_imports_unicode_literals[from", "tests/pyupgrade_test.py::test_imports_unicode_literals[x", "tests/pyupgrade_test.py::test_imports_unicode_literals[\"\"\"docstring\"\"\"\\nfrom", "tests/pyupgrade_test.py::test_unicode_literals[(-False-(]", "tests/pyupgrade_test.py::test_unicode_literals[u''-False-u'']", "tests/pyupgrade_test.py::test_unicode_literals[u''-True-'']", "tests/pyupgrade_test.py::test_unicode_literals[from", "tests/pyupgrade_test.py::test_unicode_literals[\"\"\"with", "tests/pyupgrade_test.py::test_unicode_literals[Regression:", "tests/pyupgrade_test.py::test_fix_ur_literals[basic", "tests/pyupgrade_test.py::test_fix_ur_literals[upper", "tests/pyupgrade_test.py::test_fix_ur_literals[with", "tests/pyupgrade_test.py::test_fix_ur_literals[emoji]", "tests/pyupgrade_test.py::test_fix_ur_literals_gets_fixed_before_u_removed", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'\\\\d']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\"\"\\\\d\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'''\\\\d''']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[rb\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\r\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\N{SNOWMAN}\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\d\"-r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\n\\\\d\"-\"\\\\n\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[u\"\\\\d\"-u\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\d\"-br\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\8\"-r\"\\\\8\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\9\"-r\"\\\\9\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\u2603\"-br\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\n\\\\q\"\"\"-\"\"\"\\\\\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\n\\\\q\"\"\"-\"\"\"\\\\\\r\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\\\q\"\"\"-\"\"\"\\\\\\r\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N\"-r\"\\\\N\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N\\\\n\"-\"\\\\\\\\N\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N{SNOWMAN}\\\\q\"-\"\\\\N{SNOWMAN}\\\\\\\\q\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\N{SNOWMAN}\"-br\"\\\\N{SNOWMAN}\"]", "tests/pyupgrade_test.py::test_noop_octal_literals[0]", "tests/pyupgrade_test.py::test_noop_octal_literals[00]", "tests/pyupgrade_test.py::test_noop_octal_literals[1]", "tests/pyupgrade_test.py::test_noop_octal_literals[12345]", "tests/pyupgrade_test.py::test_noop_octal_literals[1.2345]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((1,", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(())]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((\\n))]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[sum((block.code", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[def", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"foo{}\".format(1)))-print(\"foo{}\".format(1))]", "tests/pyupgrade_test.py::test_fix_extra_parens[print((((1))))-print(1)]", "tests/pyupgrade_test.py::test_fix_extra_parens[print(\\n", "tests/pyupgrade_test.py::test_fix_extra_parens[extra", "tests/pyupgrade_test.py::test_is_bytestring_true[b'']", "tests/pyupgrade_test.py::test_is_bytestring_true[b\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B'']", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''0]", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''1]", "tests/pyupgrade_test.py::test_is_bytestring_false[]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false['']", "tests/pyupgrade_test.py::test_is_bytestring_false[u\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"b\"]", "tests/pyupgrade_test.py::test_parse_percent_format[\"\"-expected0]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%%\"-expected1]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s\"-expected2]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(hi)s\"-expected4]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%()s\"-expected5]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%#o\"-expected6]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%", "tests/pyupgrade_test.py::test_parse_percent_format[\"%5d\"-expected8]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%*d\"-expected9]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.f\"-expected10]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.5f\"-expected11]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.*f\"-expected12]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%ld\"-expected13]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(complete)#4.4f\"-expected14]", "tests/pyupgrade_test.py::test_percent_to_format[%s-{}]", "tests/pyupgrade_test.py::test_percent_to_format[%%%s-%{}]", "tests/pyupgrade_test.py::test_percent_to_format[%(foo)s-{foo}]", "tests/pyupgrade_test.py::test_percent_to_format[%2f-{:2f}]", "tests/pyupgrade_test.py::test_percent_to_format[%r-{!r}]", "tests/pyupgrade_test.py::test_percent_to_format[%a-{!a}]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[-]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[", "tests/pyupgrade_test.py::test_simplify_conversion_flag[#0-", "tests/pyupgrade_test.py::test_simplify_conversion_flag[--<]", "tests/pyupgrade_test.py::test_percent_format_noop[\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[b\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%d\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%i\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%u\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%c\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%#o\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%()s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%4%\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2r\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2a\"", "tests/pyupgrade_test.py::test_percent_format_noop[i", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(1)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(a)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(ab)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(and)s\"", "tests/pyupgrade_test.py::test_percent_format[\"trivial\"", "tests/pyupgrade_test.py::test_percent_format[\"%s\"", "tests/pyupgrade_test.py::test_percent_format[\"%s%%", "tests/pyupgrade_test.py::test_percent_format[\"%3f\"", "tests/pyupgrade_test.py::test_percent_format[\"%-5s\"", "tests/pyupgrade_test.py::test_percent_format[\"%9s\"", "tests/pyupgrade_test.py::test_percent_format[\"brace", "tests/pyupgrade_test.py::test_percent_format[\"%(k)s\"", "tests/pyupgrade_test.py::test_percent_format[\"%(to_list)s\"", "tests/pyupgrade_test.py::test_fix_super_noop[x(]", "tests/pyupgrade_test.py::test_fix_super_noop[class", "tests/pyupgrade_test.py::test_fix_super_noop[def", "tests/pyupgrade_test.py::test_fix_super[class", "tests/pyupgrade_test.py::test_fix_classes_noop[x", "tests/pyupgrade_test.py::test_fix_classes_noop[class", "tests/pyupgrade_test.py::test_fix_classes[class", "tests/pyupgrade_test.py::test_fix_classes[import", "tests/pyupgrade_test.py::test_fix_classes[from", "tests/pyupgrade_test.py::test_fix_six_noop[x", "tests/pyupgrade_test.py::test_fix_six_noop[from", "tests/pyupgrade_test.py::test_fix_six_noop[@mydec\\nclass", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(\"\\xa3\"))]", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(", "tests/pyupgrade_test.py::test_fix_six_noop[class", "tests/pyupgrade_test.py::test_fix_six_noop[six.reraise(*err)]", "tests/pyupgrade_test.py::test_fix_six_noop[six.b(*a)]", "tests/pyupgrade_test.py::test_fix_six_noop[six.u(*a)]", "tests/pyupgrade_test.py::test_fix_six_noop[@six.add_metaclass(*a)\\nclass", "tests/pyupgrade_test.py::test_fix_six[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six[weird", "tests/pyupgrade_test.py::test_fix_six[issubclass(tp,", "tests/pyupgrade_test.py::test_fix_six[STRING_TYPES", "tests/pyupgrade_test.py::test_fix_six[from", "tests/pyupgrade_test.py::test_fix_six[six.b(\"123\")-b\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(r\"123\")-br\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(\"\\\\x12\\\\xef\")-b\"\\\\x12\\\\xef\"]", "tests/pyupgrade_test.py::test_fix_six[six.byte2int(b\"f\")-b\"f\"[0]]", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/pyupgrade_test.py::test_fix_six[six.get_unbound_method(meth)\\n-meth\\n]", "tests/pyupgrade_test.py::test_fix_six[six.indexbytes(bs,", "tests/pyupgrade_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/pyupgrade_test.py::test_fix_six[six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(tp,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(\\n", "tests/pyupgrade_test.py::test_fix_six[class", "tests/pyupgrade_test.py::test_fix_six[basic", "tests/pyupgrade_test.py::test_fix_classes_py3only[class", "tests/pyupgrade_test.py::test_fix_classes_py3only[from", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(1)]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(\"foo\"\\n\"bar\")]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(*a)]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(\"foo\",", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(**k)]", "tests/pyupgrade_test.py::test_fix_native_literals[str(\"foo\")-\"foo\"]", "tests/pyupgrade_test.py::test_fix_native_literals[str(\"\"\"\\nfoo\"\"\")-\"\"\"\\nfoo\"\"\"]", "tests/pyupgrade_test.py::test_fix_encode[\"asd\".encode(\"utf-8\")-\"asd\".encode()]", "tests/pyupgrade_test.py::test_fix_encode[\"asd\".encode(\"utf8\")-\"asd\".encode()]", "tests/pyupgrade_test.py::test_fix_encode[\"asd\".encode(\"UTF-8\")-\"asd\".encode()]", "tests/pyupgrade_test.py::test_fix_encode[sys.stdout.buffer.write(\\n", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(\"unknown-codec\")]", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(\"ascii\")]", "tests/pyupgrade_test.py::test_fix_encode_noop[x=\"asd\"\\nx.encode(\"utf-8\")]", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(\"utf-8\",", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(encoding=\"utf-8\")]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[(]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\"", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{foo}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{0}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[b\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{1}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{.x}", "tests/pyupgrade_test.py::test_fix_fstrings[\"hello", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped,", "tests/pyupgrade_test.py::test_main_trivial", "tests/pyupgrade_test.py::test_main_noop", "tests/pyupgrade_test.py::test_main_changes_a_file", "tests/pyupgrade_test.py::test_main_keeps_line_endings", "tests/pyupgrade_test.py::test_main_syntax_error", "tests/pyupgrade_test.py::test_main_non_utf8_bytes", "tests/pyupgrade_test.py::test_keep_percent_format", "tests/pyupgrade_test.py::test_py3_plus_argument_unicode_literals", "tests/pyupgrade_test.py::test_py3_plus_super", "tests/pyupgrade_test.py::test_py3_plus_new_style_classes", "tests/pyupgrade_test.py::test_py36_plus_fstrings", "tests/pyupgrade_test.py::test_noop_token_error" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2019-06-02 03:38:46+00:00
mit
1,142
asottile__pyupgrade-165
diff --git a/pyupgrade.py b/pyupgrade.py index b83d15e..6e6051f 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -1672,6 +1672,15 @@ def _starargs(call): ) +def _format_params(call): + params = {} + for i, arg in enumerate(call.args): + params[str(i)] = _unparse(arg) + for kwd in call.keywords: + params[kwd.arg] = _unparse(kwd.value) + return params + + class FindSimpleFormats(ast.NodeVisitor): def __init__(self): self.found = {} @@ -1685,7 +1694,9 @@ class FindSimpleFormats(ast.NodeVisitor): all(_simple_arg(k.value) for k in node.keywords) and not _starargs(node) ): + params = _format_params(node) seen = set() + i = 0 for _, name, spec, _ in parse_format(node.func.value.s): # timid: difficult to rewrite correctly if spec is not None and '{' in spec: @@ -1699,6 +1710,13 @@ class FindSimpleFormats(ast.NodeVisitor): elif '[' in name: break seen.add(candidate) + + key = candidate or str(i) + # their .format() call is broken currently + if key not in params: + break + if not candidate: + i += 1 else: self.found[_ast_to_offset(node)] = node @@ -1715,11 +1733,7 @@ def _unparse(node): def _to_fstring(src, call): - params = {} - for i, arg in enumerate(call.args): - params[str(i)] = _unparse(arg) - for kwd in call.keywords: - params[kwd.arg] = _unparse(kwd.value) + params = _format_params(call) parts = [] i = 0 @@ -1727,7 +1741,8 @@ def _to_fstring(src, call): if name is not None: k, dot, rest = name.partition('.') name = ''.join((params[k or str(i)], dot, rest)) - i += 1 + if not k: # named and auto params can be in different orders + i += 1 parts.append((s, name, spec, conv)) return unparse_parsed_string(parts)
asottile/pyupgrade
847d0caf9d57666ce06d58421cec982176e8a256
diff --git a/tests/pyupgrade_test.py b/tests/pyupgrade_test.py index fe3d328..d4b5bdc 100644 --- a/tests/pyupgrade_test.py +++ b/tests/pyupgrade_test.py @@ -2004,6 +2004,8 @@ def test_fix_py2_blocks(s, expected): '"{:{}}".format(x, y)', '"{a[b]}".format(a=a)', '"{a.a[b]}".format(a=a)', + # not enough placeholders / placeholders missing + '"{}{}".format(a)', '"{a}{b}".format(a=a)', ), ) def test_fix_fstrings_noop(s): @@ -2020,7 +2022,7 @@ def test_fix_fstrings_noop(s): ('"{} {}".format(a.b, c.d)', 'f"{a.b} {c.d}"'), ('"hello {}!".format(name)', 'f"hello {name}!"'), ('"{}{{}}{}".format(escaped, y)', 'f"{escaped}{{}}{y}"'), - + ('"{}{b}{}".format(a, c, b=b)', 'f"{a}{b}{c}"'), # TODO: poor man's f-strings? # '"{foo}".format(**locals())' ),
--py36-plus: KeyError on broken `.format()` call Currently garbage in garbage out, however this shouldn't crash: ```python '{}{}'.format(a) ``` ```console $ pyupgrade --py36-plus t.py Traceback (most recent call last): File "/home/asottile/workspace/ambassador/v/bin/pyupgrade", line 10, in <module> sys.exit(main()) File "/home/asottile/workspace/ambassador/v/lib/python3.6/site-packages/pyupgrade.py", line 1763, in main ret |= fix_file(filename, args) File "/home/asottile/workspace/ambassador/v/lib/python3.6/site-packages/pyupgrade.py", line 1739, in fix_file contents_text = _fix_fstrings(contents_text) File "/home/asottile/workspace/ambassador/v/lib/python3.6/site-packages/pyupgrade.py", line 1715, in _fix_fstrings tokens[i] = token._replace(src=_to_fstring(token.src, node)) File "/home/asottile/workspace/ambassador/v/lib/python3.6/site-packages/pyupgrade.py", line 1674, in _to_fstring name = ''.join((params[k or str(i)], dot, rest)) KeyError: '1' ```
0.0
847d0caf9d57666ce06d58421cec982176e8a256
[ "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}{}\".format(a)]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a}{b}\".format(a=a)]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}{b}{}\".format(a," ]
[ "tests/pyupgrade_test.py::test_roundtrip_text[]", "tests/pyupgrade_test.py::test_roundtrip_text[foo]", "tests/pyupgrade_test.py::test_roundtrip_text[{}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0}]", "tests/pyupgrade_test.py::test_roundtrip_text[{named}]", "tests/pyupgrade_test.py::test_roundtrip_text[{!r}]", "tests/pyupgrade_test.py::test_roundtrip_text[{:>5}]", "tests/pyupgrade_test.py::test_roundtrip_text[{{]", "tests/pyupgrade_test.py::test_roundtrip_text[}}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0!s:15}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/pyupgrade_test.py::test_sets[set()-set()]", "tests/pyupgrade_test.py::test_sets[set((\\n))-set((\\n))]", "tests/pyupgrade_test.py::test_sets[set", "tests/pyupgrade_test.py::test_sets[set(())-set()]", "tests/pyupgrade_test.py::test_sets[set([])-set()]", "tests/pyupgrade_test.py::test_sets[set((", "tests/pyupgrade_test.py::test_sets[set((1,", "tests/pyupgrade_test.py::test_sets[set([1,", "tests/pyupgrade_test.py::test_sets[set(x", "tests/pyupgrade_test.py::test_sets[set([x", "tests/pyupgrade_test.py::test_sets[set((x", "tests/pyupgrade_test.py::test_sets[set(((1,", "tests/pyupgrade_test.py::test_sets[set((a,", "tests/pyupgrade_test.py::test_sets[set([(1,", "tests/pyupgrade_test.py::test_sets[set(\\n", "tests/pyupgrade_test.py::test_sets[set([((1,", "tests/pyupgrade_test.py::test_sets[set((((1,", "tests/pyupgrade_test.py::test_sets[set(\\n(1,", "tests/pyupgrade_test.py::test_sets[set((\\n1,\\n2,\\n))\\n-{\\n1,\\n2,\\n}\\n]", "tests/pyupgrade_test.py::test_sets[set((frozenset(set((1,", "tests/pyupgrade_test.py::test_sets[set((1,))-{1}]", "tests/pyupgrade_test.py::test_dictcomps[x", "tests/pyupgrade_test.py::test_dictcomps[dict()-dict()]", "tests/pyupgrade_test.py::test_dictcomps[(-(]", "tests/pyupgrade_test.py::test_dictcomps[dict", "tests/pyupgrade_test.py::test_dictcomps[dict((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([(a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a),", "tests/pyupgrade_test.py::test_dictcomps[dict((k,", "tests/pyupgrade_test.py::test_dictcomps[dict(\\n", "tests/pyupgrade_test.py::test_dictcomps[x(\\n", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal_noop[x", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is`]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[string]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[unicode", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[bytes]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[float]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[compound", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[multi-line", "tests/pyupgrade_test.py::test_format_literals[\"{0}\"format(1)-\"{0}\"format(1)]", "tests/pyupgrade_test.py::test_format_literals['{}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{'.format(1)-'{'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['}'.format(1)-'}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals[x", "tests/pyupgrade_test.py::test_format_literals['{0}", "tests/pyupgrade_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{0:x}'.format(30)-'{:x}'.format(30)]", "tests/pyupgrade_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/pyupgrade_test.py::test_format_literals['{0}'", "tests/pyupgrade_test.py::test_format_literals[print(\\n", "tests/pyupgrade_test.py::test_format_literals['{0:<{1}}'.format(1,", "tests/pyupgrade_test.py::test_imports_unicode_literals[import", "tests/pyupgrade_test.py::test_imports_unicode_literals[from", "tests/pyupgrade_test.py::test_imports_unicode_literals[x", "tests/pyupgrade_test.py::test_imports_unicode_literals[\"\"\"docstring\"\"\"\\nfrom", "tests/pyupgrade_test.py::test_unicode_literals[(-False-(]", "tests/pyupgrade_test.py::test_unicode_literals[u''-False-u'']", "tests/pyupgrade_test.py::test_unicode_literals[u''-True-'']", "tests/pyupgrade_test.py::test_unicode_literals[from", "tests/pyupgrade_test.py::test_unicode_literals[\"\"\"with", "tests/pyupgrade_test.py::test_unicode_literals[Regression:", "tests/pyupgrade_test.py::test_fix_ur_literals[basic", "tests/pyupgrade_test.py::test_fix_ur_literals[upper", "tests/pyupgrade_test.py::test_fix_ur_literals[with", "tests/pyupgrade_test.py::test_fix_ur_literals[emoji]", "tests/pyupgrade_test.py::test_fix_ur_literals_gets_fixed_before_u_removed", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'\\\\d']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\"\"\\\\d\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'''\\\\d''']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[rb\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\r\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\N{SNOWMAN}\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\d\"-r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\n\\\\d\"-\"\\\\n\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[u\"\\\\d\"-u\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\d\"-br\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\8\"-r\"\\\\8\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\9\"-r\"\\\\9\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\u2603\"-br\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\n\\\\q\"\"\"-\"\"\"\\\\\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\n\\\\q\"\"\"-\"\"\"\\\\\\r\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\\\q\"\"\"-\"\"\"\\\\\\r\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N\"-r\"\\\\N\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N\\\\n\"-\"\\\\\\\\N\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N{SNOWMAN}\\\\q\"-\"\\\\N{SNOWMAN}\\\\\\\\q\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\N{SNOWMAN}\"-br\"\\\\N{SNOWMAN}\"]", "tests/pyupgrade_test.py::test_noop_octal_literals[0]", "tests/pyupgrade_test.py::test_noop_octal_literals[00]", "tests/pyupgrade_test.py::test_noop_octal_literals[1]", "tests/pyupgrade_test.py::test_noop_octal_literals[12345]", "tests/pyupgrade_test.py::test_noop_octal_literals[1.2345]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((1,", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(())]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((\\n))]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[sum((block.code", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[def", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"foo{}\".format(1)))-print(\"foo{}\".format(1))]", "tests/pyupgrade_test.py::test_fix_extra_parens[print((((1))))-print(1)]", "tests/pyupgrade_test.py::test_fix_extra_parens[print(\\n", "tests/pyupgrade_test.py::test_fix_extra_parens[extra", "tests/pyupgrade_test.py::test_is_bytestring_true[b'']", "tests/pyupgrade_test.py::test_is_bytestring_true[b\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B'']", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''0]", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''1]", "tests/pyupgrade_test.py::test_is_bytestring_false[]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false['']", "tests/pyupgrade_test.py::test_is_bytestring_false[u\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"b\"]", "tests/pyupgrade_test.py::test_parse_percent_format[\"\"-expected0]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%%\"-expected1]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s\"-expected2]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(hi)s\"-expected4]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%()s\"-expected5]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%#o\"-expected6]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%", "tests/pyupgrade_test.py::test_parse_percent_format[\"%5d\"-expected8]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%*d\"-expected9]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.f\"-expected10]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.5f\"-expected11]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.*f\"-expected12]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%ld\"-expected13]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(complete)#4.4f\"-expected14]", "tests/pyupgrade_test.py::test_percent_to_format[%s-{}]", "tests/pyupgrade_test.py::test_percent_to_format[%%%s-%{}]", "tests/pyupgrade_test.py::test_percent_to_format[%(foo)s-{foo}]", "tests/pyupgrade_test.py::test_percent_to_format[%2f-{:2f}]", "tests/pyupgrade_test.py::test_percent_to_format[%r-{!r}]", "tests/pyupgrade_test.py::test_percent_to_format[%a-{!a}]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[-]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[", "tests/pyupgrade_test.py::test_simplify_conversion_flag[#0-", "tests/pyupgrade_test.py::test_simplify_conversion_flag[--<]", "tests/pyupgrade_test.py::test_percent_format_noop[\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[b\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%d\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%i\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%u\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%c\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%#o\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%()s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%4%\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2r\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2a\"", "tests/pyupgrade_test.py::test_percent_format_noop[i", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(1)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(a)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(ab)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(and)s\"", "tests/pyupgrade_test.py::test_percent_format[\"trivial\"", "tests/pyupgrade_test.py::test_percent_format[\"%s\"", "tests/pyupgrade_test.py::test_percent_format[\"%s%%", "tests/pyupgrade_test.py::test_percent_format[\"%3f\"", "tests/pyupgrade_test.py::test_percent_format[\"%-5s\"", "tests/pyupgrade_test.py::test_percent_format[\"%9s\"", "tests/pyupgrade_test.py::test_percent_format[\"brace", "tests/pyupgrade_test.py::test_percent_format[\"%(k)s\"", "tests/pyupgrade_test.py::test_percent_format[\"%(to_list)s\"", "tests/pyupgrade_test.py::test_fix_super_noop[x(]", "tests/pyupgrade_test.py::test_fix_super_noop[class", "tests/pyupgrade_test.py::test_fix_super_noop[def", "tests/pyupgrade_test.py::test_fix_super[class", "tests/pyupgrade_test.py::test_fix_classes_noop[x", "tests/pyupgrade_test.py::test_fix_classes_noop[class", "tests/pyupgrade_test.py::test_fix_classes[class", "tests/pyupgrade_test.py::test_fix_classes[import", "tests/pyupgrade_test.py::test_fix_classes[from", "tests/pyupgrade_test.py::test_fix_six_noop[x", "tests/pyupgrade_test.py::test_fix_six_noop[from", "tests/pyupgrade_test.py::test_fix_six_noop[@mydec\\nclass", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(\"\\xa3\"))]", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(", "tests/pyupgrade_test.py::test_fix_six_noop[class", "tests/pyupgrade_test.py::test_fix_six_noop[six.reraise(*err)]", "tests/pyupgrade_test.py::test_fix_six_noop[six.b(*a)]", "tests/pyupgrade_test.py::test_fix_six_noop[six.u(*a)]", "tests/pyupgrade_test.py::test_fix_six_noop[@six.add_metaclass(*a)\\nclass", "tests/pyupgrade_test.py::test_fix_six[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six[weird", "tests/pyupgrade_test.py::test_fix_six[issubclass(tp,", "tests/pyupgrade_test.py::test_fix_six[STRING_TYPES", "tests/pyupgrade_test.py::test_fix_six[from", "tests/pyupgrade_test.py::test_fix_six[six.b(\"123\")-b\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(r\"123\")-br\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(\"\\\\x12\\\\xef\")-b\"\\\\x12\\\\xef\"]", "tests/pyupgrade_test.py::test_fix_six[six.byte2int(b\"f\")-b\"f\"[0]]", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/pyupgrade_test.py::test_fix_six[six.get_unbound_method(meth)\\n-meth\\n]", "tests/pyupgrade_test.py::test_fix_six[six.indexbytes(bs,", "tests/pyupgrade_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/pyupgrade_test.py::test_fix_six[six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(tp,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(\\n", "tests/pyupgrade_test.py::test_fix_six[class", "tests/pyupgrade_test.py::test_fix_six[basic", "tests/pyupgrade_test.py::test_fix_six[add_metaclass,", "tests/pyupgrade_test.py::test_fix_classes_py3only[class", "tests/pyupgrade_test.py::test_fix_classes_py3only[from", "tests/pyupgrade_test.py::test_fix_yield_from[def", "tests/pyupgrade_test.py::test_fix_yield_from_noop[def", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(1)]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(\"foo\"\\n\"bar\")]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(*a)]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(\"foo\",", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(**k)]", "tests/pyupgrade_test.py::test_fix_native_literals[str(\"foo\")-\"foo\"]", "tests/pyupgrade_test.py::test_fix_native_literals[str(\"\"\"\\nfoo\"\"\")-\"\"\"\\nfoo\"\"\"]", "tests/pyupgrade_test.py::test_fix_encode[\"asd\".encode(\"utf-8\")-\"asd\".encode()]", "tests/pyupgrade_test.py::test_fix_encode[\"asd\".encode(\"utf8\")-\"asd\".encode()]", "tests/pyupgrade_test.py::test_fix_encode[\"asd\".encode(\"UTF-8\")-\"asd\".encode()]", "tests/pyupgrade_test.py::test_fix_encode[sys.stdout.buffer.write(\\n", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(\"unknown-codec\")]", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(\"ascii\")]", "tests/pyupgrade_test.py::test_fix_encode_noop[x=\"asd\"\\nx.encode(\"utf-8\")]", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(\"utf-8\",", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(encoding=\"utf-8\")]", "tests/pyupgrade_test.py::test_fix_py2_block_noop[if", "tests/pyupgrade_test.py::test_fix_py2_block_noop[from", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY2]", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY2,", "tests/pyupgrade_test.py::test_fix_py2_blocks[not", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY3]", "tests/pyupgrade_test.py::test_fix_py2_blocks[indented", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY2", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY3,", "tests/pyupgrade_test.py::test_fix_py2_blocks[sys.version_info", "tests/pyupgrade_test.py::test_fix_py2_blocks[from", "tests/pyupgrade_test.py::test_fix_fstrings_noop[(]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\"", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{foo}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{0}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[b\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{1}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{.x}", "tests/pyupgrade_test.py::test_fix_fstrings[\"hello", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped,", "tests/pyupgrade_test.py::test_main_trivial", "tests/pyupgrade_test.py::test_main_noop", "tests/pyupgrade_test.py::test_main_changes_a_file", "tests/pyupgrade_test.py::test_main_keeps_line_endings", "tests/pyupgrade_test.py::test_main_syntax_error", "tests/pyupgrade_test.py::test_main_non_utf8_bytes", "tests/pyupgrade_test.py::test_keep_percent_format", "tests/pyupgrade_test.py::test_py3_plus_argument_unicode_literals", "tests/pyupgrade_test.py::test_py3_plus_super", "tests/pyupgrade_test.py::test_py3_plus_new_style_classes", "tests/pyupgrade_test.py::test_py36_plus_fstrings", "tests/pyupgrade_test.py::test_noop_token_error", "tests/pyupgrade_test.py::test_targets_same", "tests/pyupgrade_test.py::test_fields_same" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-06-15 21:23:45+00:00
mit
1,143
asottile__pyupgrade-166
diff --git a/pyupgrade.py b/pyupgrade.py index 6e6051f..7313835 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -1541,6 +1541,9 @@ def _fix_py3_plus(contents_text): else: j = i while tokens[j].src != node.attr: + # timid: if we see a parenthesis here, skip it + if tokens[j].src == ')': + return j += 1 tokens[i:j + 1] = [new_token]
asottile/pyupgrade
8cf438106eb8532a6e754017f8773dcfcef93556
diff --git a/tests/pyupgrade_test.py b/tests/pyupgrade_test.py index d4b5bdc..ef78b95 100644 --- a/tests/pyupgrade_test.py +++ b/tests/pyupgrade_test.py @@ -1102,6 +1102,10 @@ def test_fix_classes(s, expected): 'class C(six.with_metaclass(*a)): pass', '@six.add_metaclass(*a)\n' 'class C: pass\n', + # parenthesized part of attribute + '(\n' + ' six\n' + ').text_type(u)\n', ), ) def test_fix_six_noop(s):
function call rewrite broken when function is parenthesized A bit of an edge case, I haven't seen this break in the wild but it's certainly possible ```python ( six ).text_type(x) ``` This should produce ```python str(x) ``` But currently produces this broken syntax: ```python ( str(b) ```
0.0
8cf438106eb8532a6e754017f8773dcfcef93556
[ "tests/pyupgrade_test.py::test_fix_six_noop[(\\n" ]
[ "tests/pyupgrade_test.py::test_roundtrip_text[]", "tests/pyupgrade_test.py::test_roundtrip_text[foo]", "tests/pyupgrade_test.py::test_roundtrip_text[{}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0}]", "tests/pyupgrade_test.py::test_roundtrip_text[{named}]", "tests/pyupgrade_test.py::test_roundtrip_text[{!r}]", "tests/pyupgrade_test.py::test_roundtrip_text[{:>5}]", "tests/pyupgrade_test.py::test_roundtrip_text[{{]", "tests/pyupgrade_test.py::test_roundtrip_text[}}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0!s:15}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/pyupgrade_test.py::test_sets[set()-set()]", "tests/pyupgrade_test.py::test_sets[set((\\n))-set((\\n))]", "tests/pyupgrade_test.py::test_sets[set", "tests/pyupgrade_test.py::test_sets[set(())-set()]", "tests/pyupgrade_test.py::test_sets[set([])-set()]", "tests/pyupgrade_test.py::test_sets[set((", "tests/pyupgrade_test.py::test_sets[set((1,", "tests/pyupgrade_test.py::test_sets[set([1,", "tests/pyupgrade_test.py::test_sets[set(x", "tests/pyupgrade_test.py::test_sets[set([x", "tests/pyupgrade_test.py::test_sets[set((x", "tests/pyupgrade_test.py::test_sets[set(((1,", "tests/pyupgrade_test.py::test_sets[set((a,", "tests/pyupgrade_test.py::test_sets[set([(1,", "tests/pyupgrade_test.py::test_sets[set(\\n", "tests/pyupgrade_test.py::test_sets[set([((1,", "tests/pyupgrade_test.py::test_sets[set((((1,", "tests/pyupgrade_test.py::test_sets[set(\\n(1,", "tests/pyupgrade_test.py::test_sets[set((\\n1,\\n2,\\n))\\n-{\\n1,\\n2,\\n}\\n]", "tests/pyupgrade_test.py::test_sets[set((frozenset(set((1,", "tests/pyupgrade_test.py::test_sets[set((1,))-{1}]", "tests/pyupgrade_test.py::test_dictcomps[x", "tests/pyupgrade_test.py::test_dictcomps[dict()-dict()]", "tests/pyupgrade_test.py::test_dictcomps[(-(]", "tests/pyupgrade_test.py::test_dictcomps[dict", "tests/pyupgrade_test.py::test_dictcomps[dict((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([(a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a),", "tests/pyupgrade_test.py::test_dictcomps[dict((k,", "tests/pyupgrade_test.py::test_dictcomps[dict(\\n", "tests/pyupgrade_test.py::test_dictcomps[x(\\n", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal_noop[x", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is`]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[string]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[unicode", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[bytes]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[float]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[compound", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[multi-line", "tests/pyupgrade_test.py::test_format_literals[\"{0}\"format(1)-\"{0}\"format(1)]", "tests/pyupgrade_test.py::test_format_literals['{}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{'.format(1)-'{'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['}'.format(1)-'}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals[x", "tests/pyupgrade_test.py::test_format_literals['{0}", "tests/pyupgrade_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{0:x}'.format(30)-'{:x}'.format(30)]", "tests/pyupgrade_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/pyupgrade_test.py::test_format_literals['{0}'", "tests/pyupgrade_test.py::test_format_literals[print(\\n", "tests/pyupgrade_test.py::test_format_literals['{0:<{1}}'.format(1,", "tests/pyupgrade_test.py::test_imports_unicode_literals[import", "tests/pyupgrade_test.py::test_imports_unicode_literals[from", "tests/pyupgrade_test.py::test_imports_unicode_literals[x", "tests/pyupgrade_test.py::test_imports_unicode_literals[\"\"\"docstring\"\"\"\\nfrom", "tests/pyupgrade_test.py::test_unicode_literals[(-False-(]", "tests/pyupgrade_test.py::test_unicode_literals[u''-False-u'']", "tests/pyupgrade_test.py::test_unicode_literals[u''-True-'']", "tests/pyupgrade_test.py::test_unicode_literals[from", "tests/pyupgrade_test.py::test_unicode_literals[\"\"\"with", "tests/pyupgrade_test.py::test_unicode_literals[Regression:", "tests/pyupgrade_test.py::test_fix_ur_literals[basic", "tests/pyupgrade_test.py::test_fix_ur_literals[upper", "tests/pyupgrade_test.py::test_fix_ur_literals[with", "tests/pyupgrade_test.py::test_fix_ur_literals[emoji]", "tests/pyupgrade_test.py::test_fix_ur_literals_gets_fixed_before_u_removed", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'\\\\d']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\"\"\\\\d\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'''\\\\d''']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[rb\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\r\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\N{SNOWMAN}\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\d\"-r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\n\\\\d\"-\"\\\\n\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[u\"\\\\d\"-u\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\d\"-br\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\8\"-r\"\\\\8\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\9\"-r\"\\\\9\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\u2603\"-br\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\n\\\\q\"\"\"-\"\"\"\\\\\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\n\\\\q\"\"\"-\"\"\"\\\\\\r\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\\\q\"\"\"-\"\"\"\\\\\\r\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N\"-r\"\\\\N\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N\\\\n\"-\"\\\\\\\\N\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N{SNOWMAN}\\\\q\"-\"\\\\N{SNOWMAN}\\\\\\\\q\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\N{SNOWMAN}\"-br\"\\\\N{SNOWMAN}\"]", "tests/pyupgrade_test.py::test_noop_octal_literals[0]", "tests/pyupgrade_test.py::test_noop_octal_literals[00]", "tests/pyupgrade_test.py::test_noop_octal_literals[1]", "tests/pyupgrade_test.py::test_noop_octal_literals[12345]", "tests/pyupgrade_test.py::test_noop_octal_literals[1.2345]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((1,", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(())]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((\\n))]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[sum((block.code", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[def", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"foo{}\".format(1)))-print(\"foo{}\".format(1))]", "tests/pyupgrade_test.py::test_fix_extra_parens[print((((1))))-print(1)]", "tests/pyupgrade_test.py::test_fix_extra_parens[print(\\n", "tests/pyupgrade_test.py::test_fix_extra_parens[extra", "tests/pyupgrade_test.py::test_is_bytestring_true[b'']", "tests/pyupgrade_test.py::test_is_bytestring_true[b\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B'']", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''0]", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''1]", "tests/pyupgrade_test.py::test_is_bytestring_false[]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false['']", "tests/pyupgrade_test.py::test_is_bytestring_false[u\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"b\"]", "tests/pyupgrade_test.py::test_parse_percent_format[\"\"-expected0]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%%\"-expected1]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s\"-expected2]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(hi)s\"-expected4]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%()s\"-expected5]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%#o\"-expected6]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%", "tests/pyupgrade_test.py::test_parse_percent_format[\"%5d\"-expected8]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%*d\"-expected9]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.f\"-expected10]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.5f\"-expected11]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.*f\"-expected12]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%ld\"-expected13]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(complete)#4.4f\"-expected14]", "tests/pyupgrade_test.py::test_percent_to_format[%s-{}]", "tests/pyupgrade_test.py::test_percent_to_format[%%%s-%{}]", "tests/pyupgrade_test.py::test_percent_to_format[%(foo)s-{foo}]", "tests/pyupgrade_test.py::test_percent_to_format[%2f-{:2f}]", "tests/pyupgrade_test.py::test_percent_to_format[%r-{!r}]", "tests/pyupgrade_test.py::test_percent_to_format[%a-{!a}]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[-]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[", "tests/pyupgrade_test.py::test_simplify_conversion_flag[#0-", "tests/pyupgrade_test.py::test_simplify_conversion_flag[--<]", "tests/pyupgrade_test.py::test_percent_format_noop[\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[b\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%d\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%i\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%u\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%c\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%#o\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%()s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%4%\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2r\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2a\"", "tests/pyupgrade_test.py::test_percent_format_noop[i", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(1)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(a)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(ab)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(and)s\"", "tests/pyupgrade_test.py::test_percent_format[\"trivial\"", "tests/pyupgrade_test.py::test_percent_format[\"%s\"", "tests/pyupgrade_test.py::test_percent_format[\"%s%%", "tests/pyupgrade_test.py::test_percent_format[\"%3f\"", "tests/pyupgrade_test.py::test_percent_format[\"%-5s\"", "tests/pyupgrade_test.py::test_percent_format[\"%9s\"", "tests/pyupgrade_test.py::test_percent_format[\"brace", "tests/pyupgrade_test.py::test_percent_format[\"%(k)s\"", "tests/pyupgrade_test.py::test_percent_format[\"%(to_list)s\"", "tests/pyupgrade_test.py::test_fix_super_noop[x(]", "tests/pyupgrade_test.py::test_fix_super_noop[class", "tests/pyupgrade_test.py::test_fix_super_noop[def", "tests/pyupgrade_test.py::test_fix_super[class", "tests/pyupgrade_test.py::test_fix_classes_noop[x", "tests/pyupgrade_test.py::test_fix_classes_noop[class", "tests/pyupgrade_test.py::test_fix_classes[class", "tests/pyupgrade_test.py::test_fix_classes[import", "tests/pyupgrade_test.py::test_fix_classes[from", "tests/pyupgrade_test.py::test_fix_six_noop[x", "tests/pyupgrade_test.py::test_fix_six_noop[from", "tests/pyupgrade_test.py::test_fix_six_noop[@mydec\\nclass", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(\"\\xa3\"))]", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(", "tests/pyupgrade_test.py::test_fix_six_noop[class", "tests/pyupgrade_test.py::test_fix_six_noop[six.reraise(*err)]", "tests/pyupgrade_test.py::test_fix_six_noop[six.b(*a)]", "tests/pyupgrade_test.py::test_fix_six_noop[six.u(*a)]", "tests/pyupgrade_test.py::test_fix_six_noop[@six.add_metaclass(*a)\\nclass", "tests/pyupgrade_test.py::test_fix_six[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six[weird", "tests/pyupgrade_test.py::test_fix_six[issubclass(tp,", "tests/pyupgrade_test.py::test_fix_six[STRING_TYPES", "tests/pyupgrade_test.py::test_fix_six[from", "tests/pyupgrade_test.py::test_fix_six[six.b(\"123\")-b\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(r\"123\")-br\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(\"\\\\x12\\\\xef\")-b\"\\\\x12\\\\xef\"]", "tests/pyupgrade_test.py::test_fix_six[six.byte2int(b\"f\")-b\"f\"[0]]", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/pyupgrade_test.py::test_fix_six[six.get_unbound_method(meth)\\n-meth\\n]", "tests/pyupgrade_test.py::test_fix_six[six.indexbytes(bs,", "tests/pyupgrade_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/pyupgrade_test.py::test_fix_six[six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(tp,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(\\n", "tests/pyupgrade_test.py::test_fix_six[class", "tests/pyupgrade_test.py::test_fix_six[basic", "tests/pyupgrade_test.py::test_fix_six[add_metaclass,", "tests/pyupgrade_test.py::test_fix_classes_py3only[class", "tests/pyupgrade_test.py::test_fix_classes_py3only[from", "tests/pyupgrade_test.py::test_fix_yield_from[def", "tests/pyupgrade_test.py::test_fix_yield_from_noop[def", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(1)]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(\"foo\"\\n\"bar\")]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(*a)]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(\"foo\",", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(**k)]", "tests/pyupgrade_test.py::test_fix_native_literals[str(\"foo\")-\"foo\"]", "tests/pyupgrade_test.py::test_fix_native_literals[str(\"\"\"\\nfoo\"\"\")-\"\"\"\\nfoo\"\"\"]", "tests/pyupgrade_test.py::test_fix_encode[\"asd\".encode(\"utf-8\")-\"asd\".encode()]", "tests/pyupgrade_test.py::test_fix_encode[\"asd\".encode(\"utf8\")-\"asd\".encode()]", "tests/pyupgrade_test.py::test_fix_encode[\"asd\".encode(\"UTF-8\")-\"asd\".encode()]", "tests/pyupgrade_test.py::test_fix_encode[sys.stdout.buffer.write(\\n", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(\"unknown-codec\")]", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(\"ascii\")]", "tests/pyupgrade_test.py::test_fix_encode_noop[x=\"asd\"\\nx.encode(\"utf-8\")]", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(\"utf-8\",", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(encoding=\"utf-8\")]", "tests/pyupgrade_test.py::test_fix_py2_block_noop[if", "tests/pyupgrade_test.py::test_fix_py2_block_noop[from", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY2]", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY2,", "tests/pyupgrade_test.py::test_fix_py2_blocks[not", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY3]", "tests/pyupgrade_test.py::test_fix_py2_blocks[indented", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY2", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY3,", "tests/pyupgrade_test.py::test_fix_py2_blocks[sys.version_info", "tests/pyupgrade_test.py::test_fix_py2_blocks[from", "tests/pyupgrade_test.py::test_fix_fstrings_noop[(]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\"", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{foo}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{0}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[b\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}{}\".format(a)]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a}{b}\".format(a=a)]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{1}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{.x}", "tests/pyupgrade_test.py::test_fix_fstrings[\"hello", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped,", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}{b}{}\".format(a,", "tests/pyupgrade_test.py::test_main_trivial", "tests/pyupgrade_test.py::test_main_noop", "tests/pyupgrade_test.py::test_main_changes_a_file", "tests/pyupgrade_test.py::test_main_keeps_line_endings", "tests/pyupgrade_test.py::test_main_syntax_error", "tests/pyupgrade_test.py::test_main_non_utf8_bytes", "tests/pyupgrade_test.py::test_keep_percent_format", "tests/pyupgrade_test.py::test_py3_plus_argument_unicode_literals", "tests/pyupgrade_test.py::test_py3_plus_super", "tests/pyupgrade_test.py::test_py3_plus_new_style_classes", "tests/pyupgrade_test.py::test_py36_plus_fstrings", "tests/pyupgrade_test.py::test_noop_token_error", "tests/pyupgrade_test.py::test_targets_same", "tests/pyupgrade_test.py::test_fields_same" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-06-15 21:49:21+00:00
mit
1,144
asottile__pyupgrade-168
diff --git a/pyupgrade.py b/pyupgrade.py index 7313835..5a25ec8 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -1023,6 +1023,7 @@ class FindPy3Plus(ast.NodeVisitor): self._class_info_stack = [] self._in_comp = 0 self.super_calls = {} + self._in_async_def = False self.yield_from_fors = set() def _is_six(self, node, names): @@ -1101,7 +1102,17 @@ class FindPy3Plus(ast.NodeVisitor): else: self.generic_visit(node) - visit_FunctionDef = visit_Lambda = _visit_func + def _visit_sync_func(self, node): + self._in_async_def, orig = False, self._in_async_def + self._visit_func(node) + self._in_async_def = orig + + visit_FunctionDef = visit_Lambda = _visit_sync_func + + def visit_AsyncFunctionDef(self, node): # pragma: no cover (py35+) + self._in_async_def, orig = True, self._in_async_def + self._visit_func(node) + self._in_async_def = orig def _visit_comp(self, node): self._in_comp += 1 @@ -1235,6 +1246,7 @@ class FindPy3Plus(ast.NodeVisitor): def visit_For(self, node): # type: (ast.For) -> None if ( + not self._in_async_def and len(node.body) == 1 and isinstance(node.body[0], ast.Expr) and isinstance(node.body[0].value, ast.Yield) and
asottile/pyupgrade
bddb4a06cf9373b77a49510ef0b8423468c03603
diff --git a/tests/pyupgrade_test.py b/tests/pyupgrade_test.py index ef78b95..cfed404 100644 --- a/tests/pyupgrade_test.py +++ b/tests/pyupgrade_test.py @@ -1540,6 +1540,44 @@ def test_fix_yield_from(s, expected): assert _fix_py3_plus(s) == expected [email protected]( + sys.version_info < (3, 5), + reason='async introduced in python 3.5', +) [email protected]( + ('s', 'expected'), + ( + ( + 'async def f():\n' + ' for x in [1, 2]:\n' + ' yield x\n' + '\n' + ' def g():\n' + ' for x in [1, 2, 3]:\n' + ' yield x\n' + '\n' + ' for x in [1, 2]:\n' + ' yield x\n' + '\n' + ' return g', + 'async def f():\n' + ' for x in [1, 2]:\n' + ' yield x\n' + '\n' + ' def g():\n' + ' yield from [1, 2, 3]\n' + '\n' + ' for x in [1, 2]:\n' + ' yield x\n' + '\n' + ' return g', + ), + ), +) +def test_fix_async_yield_from(s, expected): + assert _fix_py3_plus(s) == expected + + @pytest.mark.parametrize( 's', (
Should not rewrite to `yield from` inside `async def` oops, totally forgot about this. Currently this is happening but this is forbidden by [PEP 525](https://www.python.org/dev/peps/pep-0525/#asynchronous-yield-from) ```diff async def f(): - for x in y: - yield x + yield from y ```
0.0
bddb4a06cf9373b77a49510ef0b8423468c03603
[ "tests/pyupgrade_test.py::test_fix_async_yield_from[async" ]
[ "tests/pyupgrade_test.py::test_roundtrip_text[]", "tests/pyupgrade_test.py::test_roundtrip_text[foo]", "tests/pyupgrade_test.py::test_roundtrip_text[{}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0}]", "tests/pyupgrade_test.py::test_roundtrip_text[{named}]", "tests/pyupgrade_test.py::test_roundtrip_text[{!r}]", "tests/pyupgrade_test.py::test_roundtrip_text[{:>5}]", "tests/pyupgrade_test.py::test_roundtrip_text[{{]", "tests/pyupgrade_test.py::test_roundtrip_text[}}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0!s:15}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/pyupgrade_test.py::test_sets[set()-set()]", "tests/pyupgrade_test.py::test_sets[set((\\n))-set((\\n))]", "tests/pyupgrade_test.py::test_sets[set", "tests/pyupgrade_test.py::test_sets[set(())-set()]", "tests/pyupgrade_test.py::test_sets[set([])-set()]", "tests/pyupgrade_test.py::test_sets[set((", "tests/pyupgrade_test.py::test_sets[set((1,", "tests/pyupgrade_test.py::test_sets[set([1,", "tests/pyupgrade_test.py::test_sets[set(x", "tests/pyupgrade_test.py::test_sets[set([x", "tests/pyupgrade_test.py::test_sets[set((x", "tests/pyupgrade_test.py::test_sets[set(((1,", "tests/pyupgrade_test.py::test_sets[set((a,", "tests/pyupgrade_test.py::test_sets[set([(1,", "tests/pyupgrade_test.py::test_sets[set(\\n", "tests/pyupgrade_test.py::test_sets[set([((1,", "tests/pyupgrade_test.py::test_sets[set((((1,", "tests/pyupgrade_test.py::test_sets[set(\\n(1,", "tests/pyupgrade_test.py::test_sets[set((\\n1,\\n2,\\n))\\n-{\\n1,\\n2,\\n}\\n]", "tests/pyupgrade_test.py::test_sets[set((frozenset(set((1,", "tests/pyupgrade_test.py::test_sets[set((1,))-{1}]", "tests/pyupgrade_test.py::test_dictcomps[x", "tests/pyupgrade_test.py::test_dictcomps[dict()-dict()]", "tests/pyupgrade_test.py::test_dictcomps[(-(]", "tests/pyupgrade_test.py::test_dictcomps[dict", "tests/pyupgrade_test.py::test_dictcomps[dict((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a,", "tests/pyupgrade_test.py::test_dictcomps[dict([(a,", "tests/pyupgrade_test.py::test_dictcomps[dict(((a),", "tests/pyupgrade_test.py::test_dictcomps[dict((k,", "tests/pyupgrade_test.py::test_dictcomps[dict(\\n", "tests/pyupgrade_test.py::test_dictcomps[x(\\n", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal_noop[x", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is`]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[`is", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[string]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[unicode", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[bytes]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[float]", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[compound", "tests/pyupgrade_test.py::test_fix_is_compare_to_literal[multi-line", "tests/pyupgrade_test.py::test_format_literals[\"{0}\"format(1)-\"{0}\"format(1)]", "tests/pyupgrade_test.py::test_format_literals['{}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{'.format(1)-'{'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['}'.format(1)-'}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals[x", "tests/pyupgrade_test.py::test_format_literals['{0}", "tests/pyupgrade_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{0:x}'.format(30)-'{:x}'.format(30)]", "tests/pyupgrade_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/pyupgrade_test.py::test_format_literals['{0}'", "tests/pyupgrade_test.py::test_format_literals[print(\\n", "tests/pyupgrade_test.py::test_format_literals['{0:<{1}}'.format(1,", "tests/pyupgrade_test.py::test_imports_unicode_literals[import", "tests/pyupgrade_test.py::test_imports_unicode_literals[from", "tests/pyupgrade_test.py::test_imports_unicode_literals[x", "tests/pyupgrade_test.py::test_imports_unicode_literals[\"\"\"docstring\"\"\"\\nfrom", "tests/pyupgrade_test.py::test_unicode_literals[(-False-(]", "tests/pyupgrade_test.py::test_unicode_literals[u''-False-u'']", "tests/pyupgrade_test.py::test_unicode_literals[u''-True-'']", "tests/pyupgrade_test.py::test_unicode_literals[from", "tests/pyupgrade_test.py::test_unicode_literals[\"\"\"with", "tests/pyupgrade_test.py::test_unicode_literals[Regression:", "tests/pyupgrade_test.py::test_fix_ur_literals[basic", "tests/pyupgrade_test.py::test_fix_ur_literals[upper", "tests/pyupgrade_test.py::test_fix_ur_literals[with", "tests/pyupgrade_test.py::test_fix_ur_literals[emoji]", "tests/pyupgrade_test.py::test_fix_ur_literals_gets_fixed_before_u_removed", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'\\\\d']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\"\"\\\\d\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'''\\\\d''']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[rb\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\r\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\N{SNOWMAN}\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\d\"-r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\n\\\\d\"-\"\\\\n\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[u\"\\\\d\"-u\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\d\"-br\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\8\"-r\"\\\\8\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\9\"-r\"\\\\9\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\u2603\"-br\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\n\\\\q\"\"\"-\"\"\"\\\\\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\n\\\\q\"\"\"-\"\"\"\\\\\\r\\n\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\"\"\\\\\\r\\\\q\"\"\"-\"\"\"\\\\\\r\\\\\\\\q\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N\"-r\"\\\\N\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N\\\\n\"-\"\\\\\\\\N\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\N{SNOWMAN}\\\\q\"-\"\\\\N{SNOWMAN}\\\\\\\\q\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\N{SNOWMAN}\"-br\"\\\\N{SNOWMAN}\"]", "tests/pyupgrade_test.py::test_noop_octal_literals[0]", "tests/pyupgrade_test.py::test_noop_octal_literals[00]", "tests/pyupgrade_test.py::test_noop_octal_literals[1]", "tests/pyupgrade_test.py::test_noop_octal_literals[12345]", "tests/pyupgrade_test.py::test_noop_octal_literals[1.2345]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((1,", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print(())]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[print((\\n))]", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[sum((block.code", "tests/pyupgrade_test.py::test_fix_extra_parens_noop[def", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"hello", "tests/pyupgrade_test.py::test_fix_extra_parens[print((\"foo{}\".format(1)))-print(\"foo{}\".format(1))]", "tests/pyupgrade_test.py::test_fix_extra_parens[print((((1))))-print(1)]", "tests/pyupgrade_test.py::test_fix_extra_parens[print(\\n", "tests/pyupgrade_test.py::test_fix_extra_parens[extra", "tests/pyupgrade_test.py::test_is_bytestring_true[b'']", "tests/pyupgrade_test.py::test_is_bytestring_true[b\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B'']", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''0]", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''1]", "tests/pyupgrade_test.py::test_is_bytestring_false[]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false['']", "tests/pyupgrade_test.py::test_is_bytestring_false[u\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"b\"]", "tests/pyupgrade_test.py::test_parse_percent_format[\"\"-expected0]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%%\"-expected1]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s\"-expected2]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(hi)s\"-expected4]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%()s\"-expected5]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%#o\"-expected6]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%", "tests/pyupgrade_test.py::test_parse_percent_format[\"%5d\"-expected8]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%*d\"-expected9]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.f\"-expected10]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.5f\"-expected11]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.*f\"-expected12]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%ld\"-expected13]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(complete)#4.4f\"-expected14]", "tests/pyupgrade_test.py::test_percent_to_format[%s-{}]", "tests/pyupgrade_test.py::test_percent_to_format[%%%s-%{}]", "tests/pyupgrade_test.py::test_percent_to_format[%(foo)s-{foo}]", "tests/pyupgrade_test.py::test_percent_to_format[%2f-{:2f}]", "tests/pyupgrade_test.py::test_percent_to_format[%r-{!r}]", "tests/pyupgrade_test.py::test_percent_to_format[%a-{!a}]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[-]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[", "tests/pyupgrade_test.py::test_simplify_conversion_flag[#0-", "tests/pyupgrade_test.py::test_simplify_conversion_flag[--<]", "tests/pyupgrade_test.py::test_percent_format_noop[\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[b\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%d\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%i\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%u\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%c\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%#o\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%()s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%4%\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2r\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2a\"", "tests/pyupgrade_test.py::test_percent_format_noop[i", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(1)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(a)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(ab)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(and)s\"", "tests/pyupgrade_test.py::test_percent_format[\"trivial\"", "tests/pyupgrade_test.py::test_percent_format[\"%s\"", "tests/pyupgrade_test.py::test_percent_format[\"%s%%", "tests/pyupgrade_test.py::test_percent_format[\"%3f\"", "tests/pyupgrade_test.py::test_percent_format[\"%-5s\"", "tests/pyupgrade_test.py::test_percent_format[\"%9s\"", "tests/pyupgrade_test.py::test_percent_format[\"brace", "tests/pyupgrade_test.py::test_percent_format[\"%(k)s\"", "tests/pyupgrade_test.py::test_percent_format[\"%(to_list)s\"", "tests/pyupgrade_test.py::test_fix_super_noop[x(]", "tests/pyupgrade_test.py::test_fix_super_noop[class", "tests/pyupgrade_test.py::test_fix_super_noop[def", "tests/pyupgrade_test.py::test_fix_super[class", "tests/pyupgrade_test.py::test_fix_classes_noop[x", "tests/pyupgrade_test.py::test_fix_classes_noop[class", "tests/pyupgrade_test.py::test_fix_classes[class", "tests/pyupgrade_test.py::test_fix_classes[import", "tests/pyupgrade_test.py::test_fix_classes[from", "tests/pyupgrade_test.py::test_fix_six_noop[x", "tests/pyupgrade_test.py::test_fix_six_noop[from", "tests/pyupgrade_test.py::test_fix_six_noop[@mydec\\nclass", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(\"\\xa3\"))]", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.b(", "tests/pyupgrade_test.py::test_fix_six_noop[class", "tests/pyupgrade_test.py::test_fix_six_noop[six.reraise(*err)]", "tests/pyupgrade_test.py::test_fix_six_noop[six.b(*a)]", "tests/pyupgrade_test.py::test_fix_six_noop[six.u(*a)]", "tests/pyupgrade_test.py::test_fix_six_noop[@six.add_metaclass(*a)\\nclass", "tests/pyupgrade_test.py::test_fix_six_noop[(\\n", "tests/pyupgrade_test.py::test_fix_six[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six[weird", "tests/pyupgrade_test.py::test_fix_six[issubclass(tp,", "tests/pyupgrade_test.py::test_fix_six[STRING_TYPES", "tests/pyupgrade_test.py::test_fix_six[from", "tests/pyupgrade_test.py::test_fix_six[six.b(\"123\")-b\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(r\"123\")-br\"123\"]", "tests/pyupgrade_test.py::test_fix_six[six.b(\"\\\\x12\\\\xef\")-b\"\\\\x12\\\\xef\"]", "tests/pyupgrade_test.py::test_fix_six[six.byte2int(b\"f\")-b\"f\"[0]]", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/pyupgrade_test.py::test_fix_six[six.get_unbound_method(meth)\\n-meth\\n]", "tests/pyupgrade_test.py::test_fix_six[six.indexbytes(bs,", "tests/pyupgrade_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/pyupgrade_test.py::test_fix_six[six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(tp,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(\\n", "tests/pyupgrade_test.py::test_fix_six[class", "tests/pyupgrade_test.py::test_fix_six[basic", "tests/pyupgrade_test.py::test_fix_six[add_metaclass,", "tests/pyupgrade_test.py::test_fix_classes_py3only[class", "tests/pyupgrade_test.py::test_fix_classes_py3only[from", "tests/pyupgrade_test.py::test_fix_yield_from[def", "tests/pyupgrade_test.py::test_fix_yield_from_noop[def", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(1)]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(\"foo\"\\n\"bar\")]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(*a)]", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(\"foo\",", "tests/pyupgrade_test.py::test_fix_native_literals_noop[str(**k)]", "tests/pyupgrade_test.py::test_fix_native_literals[str(\"foo\")-\"foo\"]", "tests/pyupgrade_test.py::test_fix_native_literals[str(\"\"\"\\nfoo\"\"\")-\"\"\"\\nfoo\"\"\"]", "tests/pyupgrade_test.py::test_fix_encode[\"asd\".encode(\"utf-8\")-\"asd\".encode()]", "tests/pyupgrade_test.py::test_fix_encode[\"asd\".encode(\"utf8\")-\"asd\".encode()]", "tests/pyupgrade_test.py::test_fix_encode[\"asd\".encode(\"UTF-8\")-\"asd\".encode()]", "tests/pyupgrade_test.py::test_fix_encode[sys.stdout.buffer.write(\\n", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(\"unknown-codec\")]", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(\"ascii\")]", "tests/pyupgrade_test.py::test_fix_encode_noop[x=\"asd\"\\nx.encode(\"utf-8\")]", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(\"utf-8\",", "tests/pyupgrade_test.py::test_fix_encode_noop[\"asd\".encode(encoding=\"utf-8\")]", "tests/pyupgrade_test.py::test_fix_py2_block_noop[if", "tests/pyupgrade_test.py::test_fix_py2_block_noop[from", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY2]", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY2,", "tests/pyupgrade_test.py::test_fix_py2_blocks[not", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY3]", "tests/pyupgrade_test.py::test_fix_py2_blocks[indented", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY2", "tests/pyupgrade_test.py::test_fix_py2_blocks[six.PY3,", "tests/pyupgrade_test.py::test_fix_py2_blocks[sys.version_info", "tests/pyupgrade_test.py::test_fix_py2_blocks[from", "tests/pyupgrade_test.py::test_fix_fstrings_noop[(]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\"", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{foo}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{0}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[b\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}{}\".format(a)]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{a}{b}\".format(a=a)]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{1}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{.x}", "tests/pyupgrade_test.py::test_fix_fstrings[\"hello", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped,", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}{b}{}\".format(a,", "tests/pyupgrade_test.py::test_main_trivial", "tests/pyupgrade_test.py::test_main_noop", "tests/pyupgrade_test.py::test_main_changes_a_file", "tests/pyupgrade_test.py::test_main_keeps_line_endings", "tests/pyupgrade_test.py::test_main_syntax_error", "tests/pyupgrade_test.py::test_main_non_utf8_bytes", "tests/pyupgrade_test.py::test_keep_percent_format", "tests/pyupgrade_test.py::test_py3_plus_argument_unicode_literals", "tests/pyupgrade_test.py::test_py3_plus_super", "tests/pyupgrade_test.py::test_py3_plus_new_style_classes", "tests/pyupgrade_test.py::test_py36_plus_fstrings", "tests/pyupgrade_test.py::test_noop_token_error", "tests/pyupgrade_test.py::test_targets_same", "tests/pyupgrade_test.py::test_fields_same" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2019-06-15 23:59:02+00:00
mit
1,145
asottile__pyupgrade-190
diff --git a/pyupgrade.py b/pyupgrade.py index c7a8d26..2f8626c 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -233,6 +233,8 @@ def _victims(tokens, start, arg, gen): ends.extend((i - 1, i)) else: ends.append(i) + if len(brace_stack) > 1 and tokens[i + 1].src == ',': + ends.append(i + 1) if is_end_brace: brace_stack.pop() @@ -245,9 +247,9 @@ def _victims(tokens, start, arg, gen): while tokens[i].name in NON_CODING_TOKENS: i -= 1 if tokens[i].src == ',': - ends = sorted(set(ends + [i])) + ends.append(i) - return Victims(starts, ends, first_comma_index, arg_index) + return Victims(starts, sorted(set(ends)), first_comma_index, arg_index) def _find_token(tokens, i, token): # type: (List[Token], int, Token) -> int
asottile/pyupgrade
8faebaaccd3bd25ed0643b2a07e8cd10b17a4f68
diff --git a/tests/set_literals_test.py b/tests/set_literals_test.py index 22ac4d6..50363be 100644 --- a/tests/set_literals_test.py +++ b/tests/set_literals_test.py @@ -85,6 +85,16 @@ def test_fix_sets_noop(s): ' x for x in y\n' '}', ), + ( + 'set(\n' + ' [\n' + ' 99, 100,\n' + ' ],\n' + ')\n', + '{\n' + ' 99, 100,\n' + '}\n', + ), ), ) def test_sets(s, expected):
`set` with trailing comma after list causes syntax error ```python set( [ 1, 2, 3, ], ) ``` currently gets rewritten to (`SyntaxError`) ```python { 1, 2, 3, , } ```
0.0
8faebaaccd3bd25ed0643b2a07e8cd10b17a4f68
[ "tests/set_literals_test.py::test_sets[set(\\n" ]
[ "tests/set_literals_test.py::test_fix_sets_noop[set()]", "tests/set_literals_test.py::test_fix_sets_noop[set((\\n))]", "tests/set_literals_test.py::test_fix_sets_noop[set", "tests/set_literals_test.py::test_sets[set(())-set()]", "tests/set_literals_test.py::test_sets[set([])-set()]", "tests/set_literals_test.py::test_sets[set((", "tests/set_literals_test.py::test_sets[set((1,", "tests/set_literals_test.py::test_sets[set([1,", "tests/set_literals_test.py::test_sets[set(x", "tests/set_literals_test.py::test_sets[set([x", "tests/set_literals_test.py::test_sets[set((x", "tests/set_literals_test.py::test_sets[set(((1,", "tests/set_literals_test.py::test_sets[set((a,", "tests/set_literals_test.py::test_sets[set([(1,", "tests/set_literals_test.py::test_sets[set([((1,", "tests/set_literals_test.py::test_sets[set((((1,", "tests/set_literals_test.py::test_sets[set(\\n(1,", "tests/set_literals_test.py::test_sets[set((\\n1,\\n2,\\n))\\n-{\\n1,\\n2,\\n}\\n]", "tests/set_literals_test.py::test_sets[set((frozenset(set((1,", "tests/set_literals_test.py::test_sets[set((1,))-{1}]" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2019-07-09 05:14:25+00:00
mit
1,146
asottile__pyupgrade-191
diff --git a/README.md b/README.md index cada007..ec67866 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,7 @@ Availability: - `--py3-plus` is passed on the commandline. ```python +str() # "''" str("foo") # "foo" ``` diff --git a/pyupgrade.py b/pyupgrade.py index a51cb50..9bbe886 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -1271,10 +1271,15 @@ class FindPy3Plus(ast.NodeVisitor): elif ( isinstance(node.func, ast.Name) and node.func.id == 'str' and - len(node.args) == 1 and - isinstance(node.args[0], ast.Str) and not node.keywords and - not _starargs(node) + not _starargs(node) and + ( + len(node.args) == 0 or + ( + len(node.args) == 1 and + isinstance(node.args[0], ast.Str) + ) + ) ): self.native_literals.add(_ast_to_offset(node)) elif ( @@ -1788,7 +1793,10 @@ def _fix_py3_plus(contents_text): # type: (str) -> str func_args, end = _parse_call_args(tokens, j) if any(tok.name == 'NL' for tok in tokens[i:end]): continue - _replace_call(tokens, i, end, func_args, '{args[0]}') + if func_args: + _replace_call(tokens, i, end, func_args, '{args[0]}') + else: + tokens[i:end] = [token._replace(name='STRING', src="''")] elif token.offset in visitor.simple_ids: tokens[i] = Token( token.name,
asottile/pyupgrade
730dd770961576213ea06bcd8164b91196f1e903
diff --git a/tests/native_literals_test.py b/tests/native_literals_test.py index a894e2d..a82820a 100644 --- a/tests/native_literals_test.py +++ b/tests/native_literals_test.py @@ -24,6 +24,7 @@ def test_fix_native_literals_noop(s): @pytest.mark.parametrize( ('s', 'expected'), ( + ('str()', "''"), ('str("foo")', '"foo"'), ('str("""\nfoo""")', '"""\nfoo"""'), ),
`str()` native literal should be just `''` https://github.com/asottile/pyupgrade#forced-strnative-literals ```python str() # '' ```
0.0
730dd770961576213ea06bcd8164b91196f1e903
[ "tests/native_literals_test.py::test_fix_native_literals[str()-'']" ]
[ "tests/native_literals_test.py::test_fix_native_literals_noop[str(1)]", "tests/native_literals_test.py::test_fix_native_literals_noop[str(\"foo\"\\n\"bar\")]", "tests/native_literals_test.py::test_fix_native_literals_noop[str(*a)]", "tests/native_literals_test.py::test_fix_native_literals_noop[str(\"foo\",", "tests/native_literals_test.py::test_fix_native_literals_noop[str(**k)]", "tests/native_literals_test.py::test_fix_native_literals[str(\"foo\")-\"foo\"]", "tests/native_literals_test.py::test_fix_native_literals[str(\"\"\"\\nfoo\"\"\")-\"\"\"\\nfoo\"\"\"]" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2019-07-12 05:08:27+00:00
mit
1,147
asottile__pyupgrade-195
diff --git a/pyupgrade.py b/pyupgrade.py index 2347ec5..d24f9af 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -1982,18 +1982,12 @@ class FindSimpleFormats(ast.NodeVisitor): self.found = {} # type: Dict[Offset, ast.Call] def visit_Call(self, node): # type: (ast.Call) -> None - if ( - isinstance(node.func, ast.Attribute) and - isinstance(node.func.value, ast.Str) and - node.func.attr == 'format' and - all(_simple_arg(arg) for arg in node.args) and - all(_simple_arg(k.value) for k in node.keywords) and - not _starargs(node) - ): + parsed = self._parse_call(node) + if parsed is not None: params = _format_params(node) seen = set() # type: Set[str] i = 0 - for _, name, spec, _ in parse_format(node.func.value.s): + for _, name, spec, _ in parsed: # timid: difficult to rewrite correctly if spec is not None and '{' in spec: break @@ -2018,6 +2012,23 @@ class FindSimpleFormats(ast.NodeVisitor): self.generic_visit(node) + def _parse_call(self, node): + # type: (ast.Call) -> Optional[Tuple[DotFormatPart, ...]] + if not ( + isinstance(node.func, ast.Attribute) and + isinstance(node.func.value, ast.Str) and + node.func.attr == 'format' and + all(_simple_arg(arg) for arg in node.args) and + all(_simple_arg(k.value) for k in node.keywords) and + not _starargs(node) + ): + return None + + try: + return parse_format(node.func.value.s) + except ValueError: + return None + def _unparse(node): # type: (ast.expr) -> str if isinstance(node, ast.Name):
asottile/pyupgrade
776d3fd38005862a891ce7a8e9c77fbfaadcca4c
diff --git a/tests/fstrings_test.py b/tests/fstrings_test.py index b0b5da6..66f90ae 100644 --- a/tests/fstrings_test.py +++ b/tests/fstrings_test.py @@ -12,6 +12,8 @@ from pyupgrade import _fix_fstrings ( # syntax error '(', + # invalid format strings + "'{'.format(a)", "'}'.format(a)", # weird syntax '"{}" . format(x)', # spans multiple lines
--py36-plus: ValueError: Single '{' encountered in format string Invalid format failures are not skipped currently: ```python '{'.format(a) ``` ```console $ pyupgrade --py36-plus t.py Traceback (most recent call last): File "/home/asottile/workspace/ridemonitor/venv/bin/pyupgrade", line 10, in <module> sys.exit(main()) File "/home/asottile/workspace/ridemonitor/venv/lib/python3.6/site-packages/pyupgrade.py", line 2136, in main ret |= fix_file(filename, args) File "/home/asottile/workspace/ridemonitor/venv/lib/python3.6/site-packages/pyupgrade.py", line 2107, in fix_file contents_text = _fix_fstrings(contents_text) File "/home/asottile/workspace/ridemonitor/venv/lib/python3.6/site-packages/pyupgrade.py", line 2053, in _fix_fstrings visitor.visit(ast_obj) File "/usr/lib/python3.6/ast.py", line 253, in visit return visitor(node) File "/usr/lib/python3.6/ast.py", line 261, in generic_visit self.visit(item) File "/usr/lib/python3.6/ast.py", line 253, in visit return visitor(node) File "/usr/lib/python3.6/ast.py", line 263, in generic_visit self.visit(value) File "/usr/lib/python3.6/ast.py", line 253, in visit return visitor(node) File "/home/asottile/workspace/ridemonitor/venv/lib/python3.6/site-packages/pyupgrade.py", line 1996, in visit_Call for _, name, spec, _ in parse_format(node.func.value.s): File "/home/asottile/workspace/ridemonitor/venv/lib/python3.6/site-packages/pyupgrade.py", line 69, in parse_format parsed = tuple(_stdlib_parse_format(s)) ValueError: Single '{' encountered in format string ```
0.0
776d3fd38005862a891ce7a8e9c77fbfaadcca4c
[ "tests/fstrings_test.py::test_fix_fstrings_noop['{'.format(a)]", "tests/fstrings_test.py::test_fix_fstrings_noop['}'.format(a)]" ]
[ "tests/fstrings_test.py::test_fix_fstrings_noop[(]", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{}\"", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{}", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{foo}", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{0}", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{x}", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/fstrings_test.py::test_fix_fstrings_noop[b\"{}", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{}{}\".format(a)]", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{a}{b}\".format(a=a)]", "tests/fstrings_test.py::test_fix_fstrings[\"{}", "tests/fstrings_test.py::test_fix_fstrings[\"{1}", "tests/fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/fstrings_test.py::test_fix_fstrings[\"{.x}", "tests/fstrings_test.py::test_fix_fstrings[\"hello", "tests/fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped,", "tests/fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a," ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-08-07 22:52:41+00:00
mit
1,148
asottile__pyupgrade-208
diff --git a/pyupgrade.py b/pyupgrade.py index d660a6d..fd897bc 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -1184,6 +1184,7 @@ class FindPy3Plus(ast.NodeVisitor): self.six_add_metaclass = set() # type: Set[ast.ClassDef] self.six_b = set() # type: Set[ast.Call] self.six_calls = {} # type: Dict[Offset, ast.Call] + self.six_iter = {} # type: Dict[Offset, ast.Call] self._previous_node = None # type: Optional[ast.AST] self.six_raises = {} # type: Dict[Offset, ast.Call] self.six_remove_decorators = set() # type: Set[Offset] @@ -1384,6 +1385,18 @@ class FindPy3Plus(ast.NodeVisitor): self.six_b.add(_ast_to_offset(node)) elif self._is_six(node.func, SIX_CALLS) and not _starargs(node): self.six_calls[_ast_to_offset(node)] = node + elif ( + isinstance(node.func, ast.Name) and + node.func.id == 'next' and + not _starargs(node) and + isinstance(node.args[0], ast.Call) and + self._is_six( + node.args[0].func, + ('iteritems', 'iterkeys', 'itervalues'), + ) and + not _starargs(node.args[0]) + ): + self.six_iter[_ast_to_offset(node.args[0])] = node.args[0] elif ( isinstance(self._previous_node, ast.Expr) and self._is_six(node.func, SIX_RAISES) and @@ -1799,6 +1812,7 @@ def _fix_py3_plus(contents_text): # type: (str) -> str visitor.six_add_metaclass, visitor.six_b, visitor.six_calls, + visitor.six_iter, visitor.six_raises, visitor.six_remove_decorators, visitor.six_simple, @@ -1865,6 +1879,13 @@ def _fix_py3_plus(contents_text): # type: (str) -> str ): func_args, end = _parse_call_args(tokens, j) _replace_call(tokens, i, end, func_args, SIX_B_TMPL) + elif token.offset in visitor.six_iter: + j = _find_open_paren(tokens, i) + func_args, end = _parse_call_args(tokens, j) + call = visitor.six_iter[token.offset] + assert isinstance(call.func, (ast.Name, ast.Attribute)) + template = 'iter({})'.format(_get_tmpl(SIX_CALLS, call.func)) + _replace_call(tokens, i, end, func_args, template) elif token.offset in visitor.six_calls: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j)
asottile/pyupgrade
a5dc2d6c367df8bdac783c4d00cf6dc459f797cf
diff --git a/tests/six_test.py b/tests/six_test.py index a139e7f..ae53419 100644 --- a/tests/six_test.py +++ b/tests/six_test.py @@ -337,6 +337,16 @@ def test_fix_six_noop(s): id='add_metaclass, indented', ), + pytest.param( + 'print(six.itervalues({1:2}))\n', + 'print({1:2}.values())\n', + id='six.itervalues', + ), + pytest.param( + 'print(next(six.itervalues({1:2})))\n', + 'print(next(iter({1:2}.values())))\n', + id='six.itervalues inside next(...)', + ), ), ) def test_fix_six(s, expected):
next(six.itervalues(d)) is rewritten to next(d.values()) ```console $ cat example.py import six print(next(six.itervalues({1: 2}))) $ python example.py 2 ``` ```console $ pyupgrade --py36-plus example.py Rewriting example.py ``` ```console $ cat example.py import six print(next({1: 2}.values())) $ python example.py Traceback (most recent call last): File "example.py", line 4, in <module> print(next({1: 2}.values())) TypeError: 'dict_values' object is not an iterator ```
0.0
a5dc2d6c367df8bdac783c4d00cf6dc459f797cf
[ "tests/six_test.py::test_fix_six[six.itervalues" ]
[ "tests/six_test.py::test_fix_six_noop[x", "tests/six_test.py::test_fix_six_noop[from", "tests/six_test.py::test_fix_six_noop[@mydec\\nclass", "tests/six_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/six_test.py::test_fix_six_noop[print(six.b(\"\\xa3\"))]", "tests/six_test.py::test_fix_six_noop[print(six.b(", "tests/six_test.py::test_fix_six_noop[class", "tests/six_test.py::test_fix_six_noop[six.reraise(*err)]", "tests/six_test.py::test_fix_six_noop[six.b(*a)]", "tests/six_test.py::test_fix_six_noop[six.u(*a)]", "tests/six_test.py::test_fix_six_noop[@six.add_metaclass(*a)\\nclass", "tests/six_test.py::test_fix_six_noop[(\\n", "tests/six_test.py::test_fix_six[isinstance(s,", "tests/six_test.py::test_fix_six[weird", "tests/six_test.py::test_fix_six[issubclass(tp,", "tests/six_test.py::test_fix_six[STRING_TYPES", "tests/six_test.py::test_fix_six[from", "tests/six_test.py::test_fix_six[six.b(\"123\")-b\"123\"]", "tests/six_test.py::test_fix_six[six.b(r\"123\")-br\"123\"]", "tests/six_test.py::test_fix_six[six.b(\"\\\\x12\\\\xef\")-b\"\\\\x12\\\\xef\"]", "tests/six_test.py::test_fix_six[six.byte2int(b\"f\")-b\"f\"[0]]", "tests/six_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/six_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/six_test.py::test_fix_six[six.get_unbound_method(meth)\\n-meth\\n]", "tests/six_test.py::test_fix_six[six.indexbytes(bs,", "tests/six_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/six_test.py::test_fix_six[six.raise_from(exc,", "tests/six_test.py::test_fix_six[six.reraise(tp,", "tests/six_test.py::test_fix_six[six.reraise(\\n", "tests/six_test.py::test_fix_six[class", "tests/six_test.py::test_fix_six[basic", "tests/six_test.py::test_fix_six[add_metaclass,", "tests/six_test.py::test_fix_six[six.itervalues]", "tests/six_test.py::test_fix_base_classes[import", "tests/six_test.py::test_fix_base_classes[from", "tests/six_test.py::test_fix_base_classes[class", "tests/six_test.py::test_fix_base_classes_py3only[class", "tests/six_test.py::test_fix_base_classes_py3only[from" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2019-10-07 02:53:50+00:00
mit
1,149
asottile__pyupgrade-217
diff --git a/pyupgrade.py b/pyupgrade.py index b451f58..161eeb9 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -1390,6 +1390,7 @@ class FindPy3Plus(ast.NodeVisitor): isinstance(node.func, ast.Name) and node.func.id == 'next' and not _starargs(node) and + len(node.args) == 1 and isinstance(node.args[0], ast.Call) and self._is_six( node.args[0].func,
asottile/pyupgrade
0599e7b22e0757f8c655b8d93e3585a1a884b160
diff --git a/tests/six_test.py b/tests/six_test.py index ae53419..3afe83b 100644 --- a/tests/six_test.py +++ b/tests/six_test.py @@ -40,6 +40,8 @@ from pyupgrade import _fix_py3_plus '(\n' ' six\n' ').text_type(u)\n', + # next is shadowed + 'next()', ), ) def test_fix_six_noop(s):
IndexError: list index out of range Tested with pyupgrade-1.25.0. Running the following command on the [more-itertools](https://github.com/erikrose/more-itertools) repository results in the following crash. Only occurs with the `--py3-plus` flag. ``` $ pyupgrade --py3-plus more_itertools/recipes.py Traceback (most recent call last): File "/home/jdufresne/.venv/more-itertools/bin/pyupgrade", line 10, in <module> sys.exit(main()) File "/home/jdufresne/.venv/more-itertools/lib64/python3.7/site-packages/pyupgrade.py", line 2237, in main ret |= _fix_file(filename, args) File "/home/jdufresne/.venv/more-itertools/lib64/python3.7/site-packages/pyupgrade.py", line 2199, in _fix_file contents_text = _fix_py3_plus(contents_text) File "/home/jdufresne/.venv/more-itertools/lib64/python3.7/site-packages/pyupgrade.py", line 1801, in _fix_py3_plus visitor.visit(ast_obj) File "/usr/lib64/python3.7/ast.py", line 262, in visit return visitor(node) File "/home/jdufresne/.venv/more-itertools/lib64/python3.7/site-packages/pyupgrade.py", line 1536, in generic_visit super(FindPy3Plus, self).generic_visit(node) File "/usr/lib64/python3.7/ast.py", line 270, in generic_visit self.visit(item) File "/usr/lib64/python3.7/ast.py", line 262, in visit return visitor(node) File "/home/jdufresne/.venv/more-itertools/lib64/python3.7/site-packages/pyupgrade.py", line 1312, in _visit_sync_func self._visit_func(node) File "/home/jdufresne/.venv/more-itertools/lib64/python3.7/site-packages/pyupgrade.py", line 1307, in _visit_func self.generic_visit(node) File "/home/jdufresne/.venv/more-itertools/lib64/python3.7/site-packages/pyupgrade.py", line 1536, in generic_visit super(FindPy3Plus, self).generic_visit(node) File "/usr/lib64/python3.7/ast.py", line 270, in generic_visit self.visit(item) File "/usr/lib64/python3.7/ast.py", line 262, in visit return visitor(node) File "/home/jdufresne/.venv/more-itertools/lib64/python3.7/site-packages/pyupgrade.py", line 1536, in generic_visit super(FindPy3Plus, self).generic_visit(node) File "/usr/lib64/python3.7/ast.py", line 270, in generic_visit self.visit(item) File "/usr/lib64/python3.7/ast.py", line 262, in visit return visitor(node) File "/home/jdufresne/.venv/more-itertools/lib64/python3.7/site-packages/pyupgrade.py", line 1353, in visit_Try self.generic_visit(node) File "/home/jdufresne/.venv/more-itertools/lib64/python3.7/site-packages/pyupgrade.py", line 1536, in generic_visit super(FindPy3Plus, self).generic_visit(node) File "/usr/lib64/python3.7/ast.py", line 270, in generic_visit self.visit(item) File "/usr/lib64/python3.7/ast.py", line 262, in visit return visitor(node) File "/home/jdufresne/.venv/more-itertools/lib64/python3.7/site-packages/pyupgrade.py", line 1532, in visit_For self.generic_visit(node) File "/home/jdufresne/.venv/more-itertools/lib64/python3.7/site-packages/pyupgrade.py", line 1536, in generic_visit super(FindPy3Plus, self).generic_visit(node) File "/usr/lib64/python3.7/ast.py", line 270, in generic_visit self.visit(item) File "/usr/lib64/python3.7/ast.py", line 262, in visit return visitor(node) File "/home/jdufresne/.venv/more-itertools/lib64/python3.7/site-packages/pyupgrade.py", line 1536, in generic_visit super(FindPy3Plus, self).generic_visit(node) File "/usr/lib64/python3.7/ast.py", line 272, in generic_visit self.visit(value) File "/usr/lib64/python3.7/ast.py", line 262, in visit return visitor(node) File "/home/jdufresne/.venv/more-itertools/lib64/python3.7/site-packages/pyupgrade.py", line 1536, in generic_visit super(FindPy3Plus, self).generic_visit(node) File "/usr/lib64/python3.7/ast.py", line 272, in generic_visit self.visit(value) File "/usr/lib64/python3.7/ast.py", line 262, in visit return visitor(node) File "/home/jdufresne/.venv/more-itertools/lib64/python3.7/site-packages/pyupgrade.py", line 1393, in visit_Call isinstance(node.args[0], ast.Call) and IndexError: list index out of range ```
0.0
0599e7b22e0757f8c655b8d93e3585a1a884b160
[ "tests/six_test.py::test_fix_six_noop[next()]" ]
[ "tests/six_test.py::test_fix_six_noop[x", "tests/six_test.py::test_fix_six_noop[from", "tests/six_test.py::test_fix_six_noop[@mydec\\nclass", "tests/six_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/six_test.py::test_fix_six_noop[print(six.b(\"\\xa3\"))]", "tests/six_test.py::test_fix_six_noop[print(six.b(", "tests/six_test.py::test_fix_six_noop[class", "tests/six_test.py::test_fix_six_noop[six.reraise(*err)]", "tests/six_test.py::test_fix_six_noop[six.b(*a)]", "tests/six_test.py::test_fix_six_noop[six.u(*a)]", "tests/six_test.py::test_fix_six_noop[@six.add_metaclass(*a)\\nclass", "tests/six_test.py::test_fix_six_noop[(\\n", "tests/six_test.py::test_fix_six[isinstance(s,", "tests/six_test.py::test_fix_six[weird", "tests/six_test.py::test_fix_six[issubclass(tp,", "tests/six_test.py::test_fix_six[STRING_TYPES", "tests/six_test.py::test_fix_six[from", "tests/six_test.py::test_fix_six[six.b(\"123\")-b\"123\"]", "tests/six_test.py::test_fix_six[six.b(r\"123\")-br\"123\"]", "tests/six_test.py::test_fix_six[six.b(\"\\\\x12\\\\xef\")-b\"\\\\x12\\\\xef\"]", "tests/six_test.py::test_fix_six[six.byte2int(b\"f\")-b\"f\"[0]]", "tests/six_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/six_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/six_test.py::test_fix_six[six.get_unbound_method(meth)\\n-meth\\n]", "tests/six_test.py::test_fix_six[six.indexbytes(bs,", "tests/six_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/six_test.py::test_fix_six[six.raise_from(exc,", "tests/six_test.py::test_fix_six[six.reraise(tp,", "tests/six_test.py::test_fix_six[six.reraise(\\n", "tests/six_test.py::test_fix_six[class", "tests/six_test.py::test_fix_six[basic", "tests/six_test.py::test_fix_six[add_metaclass,", "tests/six_test.py::test_fix_six[six.itervalues]", "tests/six_test.py::test_fix_six[six.itervalues", "tests/six_test.py::test_fix_base_classes[import", "tests/six_test.py::test_fix_base_classes[from", "tests/six_test.py::test_fix_base_classes[class", "tests/six_test.py::test_fix_base_classes_py3only[class", "tests/six_test.py::test_fix_base_classes_py3only[from" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2019-10-20 18:06:27+00:00
mit
1,150
asottile__pyupgrade-23
diff --git a/README.md b/README.md index 9230fe5..f5d6db7 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,14 @@ Availability: 123456789123456789123456789L # 123456789123456789123456789 ``` +### Octal literals + +Availability: +- If `pyupgrade` is running in python 2. +```python +0755 # 0o755 +``` + ## Planned features diff --git a/pyupgrade.py b/pyupgrade.py index d305ad2..cac40ea 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -435,6 +435,20 @@ def _fix_long_literals(contents_text): return tokens_to_src(tokens) +def _fix_octal_literals(contents_text): + def _fix_octal(s): + if not s.startswith('0') or not s.isdigit() or s == len(s) * '0': + return s + else: # pragma: no cover (py2 only) + return '0o' + s[1:] + + tokens = src_to_tokens(contents_text) + for i, token in enumerate(tokens): + if token.name == 'NUMBER': + tokens[i] = token._replace(src=_fix_octal(token.src)) + return tokens_to_src(tokens) + + def fix_file(filename, args): with open(filename, 'rb') as f: contents_bytes = f.read() @@ -450,6 +464,7 @@ def fix_file(filename, args): contents_text = _fix_format_literals(contents_text) contents_text = _fix_unicode_literals(contents_text, args.py3_only) contents_text = _fix_long_literals(contents_text) + contents_text = _fix_octal_literals(contents_text) if contents_text != contents_text_orig: print('Rewriting {}'.format(filename))
asottile/pyupgrade
abb1bc0761edaace699c52c582dbbff1acf836b9
diff --git a/tests/pyupgrade_test.py b/tests/pyupgrade_test.py index bbc1a05..712a4e8 100644 --- a/tests/pyupgrade_test.py +++ b/tests/pyupgrade_test.py @@ -9,6 +9,7 @@ import pytest from pyupgrade import _fix_dictcomps from pyupgrade import _fix_format_literals from pyupgrade import _fix_long_literals +from pyupgrade import _fix_octal_literals from pyupgrade import _fix_sets from pyupgrade import _fix_unicode_literals from pyupgrade import _imports_unicode_literals @@ -309,6 +310,27 @@ def test_long_literals(s, expected): assert _fix_long_literals(s) == expected [email protected]( + ('s', 'expected'), + ( + # Any number of zeros is considered a legal token + ('0', '0'), + ('00', '00'), + # Don't modify non octal literals + ('1', '1'), + ('12345', '12345'), + ('1.2345', '1.2345'), + ), +) +def test_noop_octal_literals(s, expected): + assert _fix_octal_literals(s) == expected + + [email protected](sys.version_info >= (3,), reason='python2 "feature"') +def test_fix_octal_literal(): + assert _fix_octal_literals('0755') == '0o755' + + def test_main_trivial(): assert main(()) == 0
Upgrade python 2 octal literals Along the same lines as the long literals
0.0
abb1bc0761edaace699c52c582dbbff1acf836b9
[ "tests/pyupgrade_test.py::test_roundtrip_text[]", "tests/pyupgrade_test.py::test_roundtrip_text[foo]", "tests/pyupgrade_test.py::test_roundtrip_text[{}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0}]", "tests/pyupgrade_test.py::test_roundtrip_text[{named}]", "tests/pyupgrade_test.py::test_roundtrip_text[{!r}]", "tests/pyupgrade_test.py::test_roundtrip_text[{:>5}]", "tests/pyupgrade_test.py::test_roundtrip_text[{{]", "tests/pyupgrade_test.py::test_roundtrip_text[}}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0!s:15}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/pyupgrade_test.py::test_sets[set()-set()]", "tests/pyupgrade_test.py::test_sets[set((\\n))-set((\\n))]", "tests/pyupgrade_test.py::test_sets[set", "tests/pyupgrade_test.py::test_sets[set(())-set()]", "tests/pyupgrade_test.py::test_sets[set([])-set()]", "tests/pyupgrade_test.py::test_sets[set((", "tests/pyupgrade_test.py::test_sets[set([1,", "tests/pyupgrade_test.py::test_sets[set([(1,", "tests/pyupgrade_test.py::test_sets[set([((1,", "tests/pyupgrade_test.py::test_dictcomps[x", "tests/pyupgrade_test.py::test_dictcomps[dict()-dict()]", "tests/pyupgrade_test.py::test_dictcomps[(-(]", "tests/pyupgrade_test.py::test_dictcomps[dict", "tests/pyupgrade_test.py::test_format_literals['{}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{'.format(1)-'{'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['}'.format(1)-'}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals[x", "tests/pyupgrade_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/pyupgrade_test.py::test_format_literals['{0}'", "tests/pyupgrade_test.py::test_format_literals[print(\\n", "tests/pyupgrade_test.py::test_format_literals['{0:<{1}}'.format(1,", "tests/pyupgrade_test.py::test_imports_unicode_literals[import", "tests/pyupgrade_test.py::test_imports_unicode_literals[from", "tests/pyupgrade_test.py::test_imports_unicode_literals[x", "tests/pyupgrade_test.py::test_imports_unicode_literals[\"\"\"docstring\"\"\"\\nfrom", "tests/pyupgrade_test.py::test_unicode_literals[(-False-(]", "tests/pyupgrade_test.py::test_unicode_literals[u''-False-u'']", "tests/pyupgrade_test.py::test_unicode_literals[u''-True-'']", "tests/pyupgrade_test.py::test_unicode_literals[from", "tests/pyupgrade_test.py::test_unicode_literals[\"\"\"with", "tests/pyupgrade_test.py::test_noop_octal_literals[0-0]", "tests/pyupgrade_test.py::test_noop_octal_literals[00-00]", "tests/pyupgrade_test.py::test_noop_octal_literals[1-1]", "tests/pyupgrade_test.py::test_noop_octal_literals[12345-12345]", "tests/pyupgrade_test.py::test_noop_octal_literals[1.2345-1.2345]", "tests/pyupgrade_test.py::test_main_trivial", "tests/pyupgrade_test.py::test_main_noop", "tests/pyupgrade_test.py::test_main_syntax_error", "tests/pyupgrade_test.py::test_main_non_utf8_bytes", "tests/pyupgrade_test.py::test_py3_only_argument_unicode_literals" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2017-08-19 19:46:11+00:00
mit
1,151
asottile__pyupgrade-242
diff --git a/pyupgrade.py b/pyupgrade.py index 25d7e99..1d0636f 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -656,6 +656,7 @@ def _fix_encode_to_binary(tokens, i): # type: (List[Token], int) -> None not _is_ascii(rest) or '\\u' in escapes or '\\U' in escapes or + '\\N' in escapes or ('\\x' in escapes and not latin1_ok) or 'f' in prefix.lower() ):
asottile/pyupgrade
34a269fd7650d264e4de7603157c10d0a9bb8211
diff --git a/tests/binary_literals_test.py b/tests/binary_literals_test.py index 885d122..1c543fd 100644 --- a/tests/binary_literals_test.py +++ b/tests/binary_literals_test.py @@ -13,6 +13,7 @@ from pyupgrade import _fix_tokens '"☃".encode("UTF-8")', '"\\u2603".encode("UTF-8")', '"\\U0001f643".encode("UTF-8")', + '"\\N{SNOWMAN}".encode("UTF-8")', '"\\xa0".encode("UTF-8")', # not byte literal compatible '"y".encode("utf16")',
Possible bug `"/\N{SNOWMAN}".encode("utf-8")` -> `br"/\N{SNOWMAN}"` Taken from running pyupgrade on Werkzeug's test suite. I think this is the wrong behavior as `"/\N{SNOWMAN}".encode("utf-8")` != `br"/\N{SNOWMAN}"` and therefore this tools should not convert the former to the latter.
0.0
34a269fd7650d264e4de7603157c10d0a9bb8211
[ "tests/binary_literals_test.py::test_binary_literals_noop[\"\\\\N{SNOWMAN}\".encode(\"UTF-8\")]" ]
[ "tests/binary_literals_test.py::test_binary_literals_noop[\"\\u2603\".encode(\"UTF-8\")]", "tests/binary_literals_test.py::test_binary_literals_noop[\"\\\\u2603\".encode(\"UTF-8\")]", "tests/binary_literals_test.py::test_binary_literals_noop[\"\\\\U0001f643\".encode(\"UTF-8\")]", "tests/binary_literals_test.py::test_binary_literals_noop[\"\\\\xa0\".encode(\"UTF-8\")]", "tests/binary_literals_test.py::test_binary_literals_noop[\"y\".encode(\"utf16\")]", "tests/binary_literals_test.py::test_binary_literals_noop[f\"{x}\".encode()]", "tests/binary_literals_test.py::test_binary_literals_noop[\"foo\".encode]", "tests/binary_literals_test.py::test_binary_literals_noop[(\"foo\".encode)]", "tests/binary_literals_test.py::test_binary_literals_noop[x.encode()]", "tests/binary_literals_test.py::test_binary_literals_noop[str.encode(f\"{c}\")]", "tests/binary_literals_test.py::test_binary_literals_noop[\"foo\".encode(f\"{c}\")]", "tests/binary_literals_test.py::test_binary_literals[\"foo\".encode()-b\"foo\"]", "tests/binary_literals_test.py::test_binary_literals[\"foo\".encode(\"ascii\")-b\"foo\"]", "tests/binary_literals_test.py::test_binary_literals[\"foo\".encode(\"utf-8\")-b\"foo\"]", "tests/binary_literals_test.py::test_binary_literals[\"\\\\xa0\".encode(\"latin1\")-b\"\\\\xa0\"]", "tests/binary_literals_test.py::test_binary_literals[\"\\\\\\\\u", "tests/binary_literals_test.py::test_binary_literals[\"\\\\\\\\x" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2020-01-08 16:14:58+00:00
mit
1,152
asottile__pyupgrade-243
diff --git a/README.md b/README.md index eeb1a5f..7a7a469 100644 --- a/README.md +++ b/README.md @@ -331,6 +331,11 @@ six.get_function_globals(fn) # fn.__globals__ six.assertCountEqual(self, a1, a2) # self.assertCountEqual(a1, a2) six.assertRaisesRegex(self, e, r, fn) # self.assertRaisesRegex(e, r, fn) six.assertRegex(self, s, r) # self.assertRegex(s, r) + +# note: only for *literals* +six.ensure_binary('...') # b'...' +six.ensure_str('...') # '...' +six.ensure_text('...') # '...' ``` ### `open` alias diff --git a/pyupgrade.py b/pyupgrade.py index 07ed723..d110895 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -1420,7 +1420,7 @@ class FindPy3Plus(ast.NodeVisitor): # _is_six() enforces this assert isinstance(arg, (ast.Name, ast.Attribute)) self.six_type_ctx[_ast_to_offset(node.args[1])] = arg - elif self._is_six(node.func, ('b',)): + elif self._is_six(node.func, ('b', 'ensure_binary')): self.six_b.add(_ast_to_offset(node)) elif self._is_six(node.func, SIX_CALLS) and not _starargs(node): self.six_calls[_ast_to_offset(node)] = node @@ -1457,8 +1457,10 @@ class FindPy3Plus(ast.NodeVisitor): ): self.super_calls[_ast_to_offset(node)] = node elif ( - isinstance(node.func, ast.Name) and - node.func.id == 'str' and + ( + self._is_six(node.func, ('ensure_str', 'ensure_text')) or + isinstance(node.func, ast.Name) and node.func.id == 'str' + ) and not node.keywords and not _starargs(node) and (
asottile/pyupgrade
438c83b7e11ff7f3894c25f6c2bee4cb3275a5c7
diff --git a/tests/native_literals_test.py b/tests/native_literals_test.py index a82820a..7b6c8f0 100644 --- a/tests/native_literals_test.py +++ b/tests/native_literals_test.py @@ -27,6 +27,8 @@ def test_fix_native_literals_noop(s): ('str()', "''"), ('str("foo")', '"foo"'), ('str("""\nfoo""")', '"""\nfoo"""'), + ('six.ensure_str("foo")', '"foo"'), + ('six.ensure_text("foo")', '"foo"'), ), ) def test_fix_native_literals(s, expected): diff --git a/tests/six_test.py b/tests/six_test.py index f840c3f..83ce558 100644 --- a/tests/six_test.py +++ b/tests/six_test.py @@ -98,6 +98,10 @@ def test_fix_six_noop(s): r'six.b("\x12\xef")', r'b"\x12\xef"', ), + ( + 'six.ensure_binary("foo")', + 'b"foo"', + ), ( 'from six import b\n\n' r'b("\x12\xef")', 'from six import b\n\n' r'b"\x12\xef"',
six: ensure_str / ensure_binary / ensure_text of a literal string while we generally can't fix the ensure_* variants, we can for string literals (as we're already doing for `str('...')` for example)
0.0
438c83b7e11ff7f3894c25f6c2bee4cb3275a5c7
[ "tests/native_literals_test.py::test_fix_native_literals[six.ensure_str(\"foo\")-\"foo\"]", "tests/native_literals_test.py::test_fix_native_literals[six.ensure_text(\"foo\")-\"foo\"]", "tests/six_test.py::test_fix_six[six.ensure_binary(\"foo\")-b\"foo\"]" ]
[ "tests/native_literals_test.py::test_fix_native_literals_noop[str(1)]", "tests/native_literals_test.py::test_fix_native_literals_noop[str(\"foo\"\\n\"bar\")]", "tests/native_literals_test.py::test_fix_native_literals_noop[str(*a)]", "tests/native_literals_test.py::test_fix_native_literals_noop[str(\"foo\",", "tests/native_literals_test.py::test_fix_native_literals_noop[str(**k)]", "tests/native_literals_test.py::test_fix_native_literals[str()-'']", "tests/native_literals_test.py::test_fix_native_literals[str(\"foo\")-\"foo\"]", "tests/native_literals_test.py::test_fix_native_literals[str(\"\"\"\\nfoo\"\"\")-\"\"\"\\nfoo\"\"\"]", "tests/six_test.py::test_fix_six_noop[x", "tests/six_test.py::test_fix_six_noop[from", "tests/six_test.py::test_fix_six_noop[@mydec\\nclass", "tests/six_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/six_test.py::test_fix_six_noop[print(six.b(\"\\xa3\"))]", "tests/six_test.py::test_fix_six_noop[print(six.b(", "tests/six_test.py::test_fix_six_noop[class", "tests/six_test.py::test_fix_six_noop[six.reraise(*err)]", "tests/six_test.py::test_fix_six_noop[six.b(*a)]", "tests/six_test.py::test_fix_six_noop[six.u(*a)]", "tests/six_test.py::test_fix_six_noop[@six.add_metaclass(*a)\\nclass", "tests/six_test.py::test_fix_six_noop[(\\n", "tests/six_test.py::test_fix_six_noop[next()]", "tests/six_test.py::test_fix_six[isinstance(s,", "tests/six_test.py::test_fix_six[weird", "tests/six_test.py::test_fix_six[issubclass(tp,", "tests/six_test.py::test_fix_six[STRING_TYPES", "tests/six_test.py::test_fix_six[from", "tests/six_test.py::test_fix_six[six.b(\"123\")-b\"123\"]", "tests/six_test.py::test_fix_six[six.b(r\"123\")-br\"123\"]", "tests/six_test.py::test_fix_six[six.b(\"\\\\x12\\\\xef\")-b\"\\\\x12\\\\xef\"]", "tests/six_test.py::test_fix_six[six.byte2int(b\"f\")-b\"f\"[0]]", "tests/six_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/six_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/six_test.py::test_fix_six[six.get_unbound_function(meth)\\n-meth\\n]", "tests/six_test.py::test_fix_six[six.indexbytes(bs,", "tests/six_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/six_test.py::test_fix_six[six.raise_from(exc,", "tests/six_test.py::test_fix_six[six.reraise(tp,", "tests/six_test.py::test_fix_six[six.reraise(\\n", "tests/six_test.py::test_fix_six[class", "tests/six_test.py::test_fix_six[basic", "tests/six_test.py::test_fix_six[add_metaclass,", "tests/six_test.py::test_fix_six[six.itervalues]", "tests/six_test.py::test_fix_six[six.itervalues", "tests/six_test.py::test_fix_base_classes[import", "tests/six_test.py::test_fix_base_classes[from", "tests/six_test.py::test_fix_base_classes[class", "tests/six_test.py::test_fix_base_classes_py3only[class", "tests/six_test.py::test_fix_base_classes_py3only[from" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2020-01-08 18:19:53+00:00
mit
1,153
asottile__pyupgrade-247
diff --git a/pyupgrade.py b/pyupgrade.py index 2f9170e..4a0f9c1 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -1137,10 +1137,9 @@ SIX_CALLS = { SIX_B_TMPL = 'b{args[0]}' WITH_METACLASS_NO_BASES_TMPL = 'metaclass={args[0]}' WITH_METACLASS_BASES_TMPL = '{rest}, metaclass={args[0]}' -SIX_RAISES = { - 'raise_from': 'raise {args[0]} from {rest}', - 'reraise': 'raise {args[1]}.with_traceback({args[2]})', -} +RAISE_FROM_TMPL = 'raise {args[0]} from {rest}' +RERAISE_2_TMPL = 'raise {args[1]}.with_traceback(None)' +RERAISE_3_TMPL = 'raise {args[1]}.with_traceback({args[2]})' def _all_isinstance(vals, tp): @@ -1234,7 +1233,8 @@ class FindPy3Plus(ast.NodeVisitor): self.six_calls = {} # type: Dict[Offset, ast.Call] self.six_iter = {} # type: Dict[Offset, ast.Call] self._previous_node = None # type: Optional[ast.AST] - self.six_raises = {} # type: Dict[Offset, ast.Call] + self.six_raise_from = set() # type: Set[Offset] + self.six_reraise = set() # type: Set[Offset] self.six_remove_decorators = set() # type: Set[Offset] self.six_simple = {} # type: Dict[Offset, NameOrAttr] self.six_type_ctx = {} # type: Dict[Offset, NameOrAttr] @@ -1448,10 +1448,16 @@ class FindPy3Plus(ast.NodeVisitor): self.six_iter[_ast_to_offset(node.args[0])] = node.args[0] elif ( isinstance(self._previous_node, ast.Expr) and - self._is_six(node.func, SIX_RAISES) and + self._is_six(node.func, ('raise_from',)) and + not _starargs(node) + ): + self.six_raise_from.add(_ast_to_offset(node)) + elif ( + isinstance(self._previous_node, ast.Expr) and + self._is_six(node.func, ('reraise',)) and not _starargs(node) ): - self.six_raises[_ast_to_offset(node)] = node + self.six_reraise.add(_ast_to_offset(node)) elif ( not self._in_comp and self._class_info_stack and @@ -1882,7 +1888,8 @@ def _fix_py3_plus(contents_text): # type: (str) -> str visitor.six_b, visitor.six_calls, visitor.six_iter, - visitor.six_raises, + visitor.six_raise_from, + visitor.six_reraise, visitor.six_remove_decorators, visitor.six_simple, visitor.six_type_ctx, @@ -1975,13 +1982,17 @@ def _fix_py3_plus(contents_text): # type: (str) -> str assert isinstance(call.func, (ast.Name, ast.Attribute)) template = _get_tmpl(SIX_CALLS, call.func) _replace_call(tokens, i, end, func_args, template) - elif token.offset in visitor.six_raises: + elif token.offset in visitor.six_raise_from: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j) - call = visitor.six_raises[token.offset] - assert isinstance(call.func, (ast.Name, ast.Attribute)) - template = _get_tmpl(SIX_RAISES, call.func) - _replace_call(tokens, i, end, func_args, template) + _replace_call(tokens, i, end, func_args, RAISE_FROM_TMPL) + elif token.offset in visitor.six_reraise: + j = _find_open_paren(tokens, i) + func_args, end = _parse_call_args(tokens, j) + if len(func_args) == 2: + _replace_call(tokens, i, end, func_args, RERAISE_2_TMPL) + else: + _replace_call(tokens, i, end, func_args, RERAISE_3_TMPL) elif token.offset in visitor.six_add_metaclass: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j)
asottile/pyupgrade
711b1cdfa1b92eb035fe379b35d73a23859b5bc3
diff --git a/tests/six_test.py b/tests/six_test.py index 83ce558..c58f5fc 100644 --- a/tests/six_test.py +++ b/tests/six_test.py @@ -221,6 +221,10 @@ def test_fix_six_noop(s): 'six.reraise(tp, exc, tb)\n', 'raise exc.with_traceback(tb)\n', ), + ( + 'six.reraise(tp, exc)\n', + 'raise exc.with_traceback(None)\n', + ), ( 'from six import raise_from\n' 'raise_from(exc, exc_from)\n',
six.reraise: IndexError: list index out of range pyupgrade 1.26.0 Minimal test case. Requires using the `--py3-plus` argument. ``` def foo(func, arg): et, ev, _ = sys.exc_info() six.reraise(et, (ev[0], ev[1] + (" %s %s" % (func, arg)))) ``` ``` Traceback (most recent call last): File ".../venv/bin/pyupgrade", line 10, in <module> sys.exit(main()) File ".../venv/lib64/python3.8/site-packages/pyupgrade.py", line 2318, in main ret |= _fix_file(filename, args) File ".../venv/lib64/python3.8/site-packages/pyupgrade.py", line 2280, in _fix_file contents_text = _fix_py3_plus(contents_text) File ".../venv/lib64/python3.8/site-packages/pyupgrade.py", line 1984, in _fix_py3_plus _replace_call(tokens, i, end, func_args, template) File ".../venv/lib64/python3.8/site-packages/pyupgrade.py", line 1849, in _replace_call src = tmpl.format(args=arg_strs, rest=rest) IndexError: list index out of range ``` Discovered by running on setuptools: https://github.com/pypa/setuptools/blob/682b6511ac67e021b542e74ce30e13fe52bc2da9/setuptools/command/easy_install.py#L1730-L1735
0.0
711b1cdfa1b92eb035fe379b35d73a23859b5bc3
[ "tests/six_test.py::test_fix_six[six.reraise(tp," ]
[ "tests/six_test.py::test_fix_six_noop[x", "tests/six_test.py::test_fix_six_noop[from", "tests/six_test.py::test_fix_six_noop[@mydec\\nclass", "tests/six_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/six_test.py::test_fix_six_noop[print(six.b(\"\\xa3\"))]", "tests/six_test.py::test_fix_six_noop[print(six.b(", "tests/six_test.py::test_fix_six_noop[class", "tests/six_test.py::test_fix_six_noop[six.reraise(*err)]", "tests/six_test.py::test_fix_six_noop[six.b(*a)]", "tests/six_test.py::test_fix_six_noop[six.u(*a)]", "tests/six_test.py::test_fix_six_noop[@six.add_metaclass(*a)\\nclass", "tests/six_test.py::test_fix_six_noop[(\\n", "tests/six_test.py::test_fix_six_noop[next()]", "tests/six_test.py::test_fix_six[isinstance(s,", "tests/six_test.py::test_fix_six[weird", "tests/six_test.py::test_fix_six[issubclass(tp,", "tests/six_test.py::test_fix_six[STRING_TYPES", "tests/six_test.py::test_fix_six[from", "tests/six_test.py::test_fix_six[six.b(\"123\")-b\"123\"]", "tests/six_test.py::test_fix_six[six.b(r\"123\")-br\"123\"]", "tests/six_test.py::test_fix_six[six.b(\"\\\\x12\\\\xef\")-b\"\\\\x12\\\\xef\"]", "tests/six_test.py::test_fix_six[six.ensure_binary(\"foo\")-b\"foo\"]", "tests/six_test.py::test_fix_six[six.byte2int(b\"f\")-b\"f\"[0]]", "tests/six_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/six_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/six_test.py::test_fix_six[six.get_unbound_function(meth)\\n-meth\\n]", "tests/six_test.py::test_fix_six[six.indexbytes(bs,", "tests/six_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/six_test.py::test_fix_six[six.raise_from(exc,", "tests/six_test.py::test_fix_six[six.reraise(\\n", "tests/six_test.py::test_fix_six[class", "tests/six_test.py::test_fix_six[basic", "tests/six_test.py::test_fix_six[add_metaclass,", "tests/six_test.py::test_fix_six[six.itervalues]", "tests/six_test.py::test_fix_six[six.itervalues", "tests/six_test.py::test_fix_base_classes[import", "tests/six_test.py::test_fix_base_classes[from", "tests/six_test.py::test_fix_base_classes[class", "tests/six_test.py::test_fix_base_classes_py3only[class", "tests/six_test.py::test_fix_base_classes_py3only[from" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-01-18 16:15:24+00:00
mit
1,154
asottile__pyupgrade-250
diff --git a/pyupgrade.py b/pyupgrade.py index 4a0f9c1..6f99694 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -1140,6 +1140,7 @@ WITH_METACLASS_BASES_TMPL = '{rest}, metaclass={args[0]}' RAISE_FROM_TMPL = 'raise {args[0]} from {rest}' RERAISE_2_TMPL = 'raise {args[1]}.with_traceback(None)' RERAISE_3_TMPL = 'raise {args[1]}.with_traceback({args[2]})' +SIX_NATIVE_STR = frozenset(('ensure_str', 'ensure_text', 'text_type')) def _all_isinstance(vals, tp): @@ -1473,7 +1474,7 @@ class FindPy3Plus(ast.NodeVisitor): self.super_calls[_ast_to_offset(node)] = node elif ( ( - self._is_six(node.func, ('ensure_str', 'ensure_text')) or + self._is_six(node.func, SIX_NATIVE_STR) or isinstance(node.func, ast.Name) and node.func.id == 'str' ) and not node.keywords and @@ -1953,6 +1954,15 @@ def _fix_py3_plus(contents_text): # type: (str) -> str if_block, else_block = _find_if_else_block(tokens, j) del tokens[if_block.end:else_block.end] if_block.replace_condition(tokens, [Token('NAME', 'else')]) + elif token.offset in visitor.native_literals: + j = _find_open_paren(tokens, i) + func_args, end = _parse_call_args(tokens, j) + if any(tok.name == 'NL' for tok in tokens[i:end]): + continue + if func_args: + _replace_call(tokens, i, end, func_args, '{args[0]}') + else: + tokens[i:end] = [token._replace(name='STRING', src="''")] elif token.offset in visitor.six_type_ctx: _replace(i, SIX_TYPE_CTX_ATTRS, visitor.six_type_ctx[token.offset]) elif token.offset in visitor.six_simple: @@ -2042,15 +2052,6 @@ def _fix_py3_plus(contents_text): # type: (str) -> str call = visitor.encode_calls[token.offset] victims = _victims(tokens, i, call, gen=False) del tokens[victims.starts[0] + 1:victims.ends[-1]] - elif token.offset in visitor.native_literals: - j = _find_open_paren(tokens, i) - func_args, end = _parse_call_args(tokens, j) - if any(tok.name == 'NL' for tok in tokens[i:end]): - continue - if func_args: - _replace_call(tokens, i, end, func_args, '{args[0]}') - else: - tokens[i:end] = [token._replace(name='STRING', src="''")] elif token.offset in visitor.io_open_calls: j = _find_open_paren(tokens, i) tokens[i:j] = [token._replace(name='NAME', src='open')]
asottile/pyupgrade
465effb0a65f3cd05d8b8201be4c8b899941b6e1
diff --git a/tests/native_literals_test.py b/tests/native_literals_test.py index 7b6c8f0..7f52126 100644 --- a/tests/native_literals_test.py +++ b/tests/native_literals_test.py @@ -29,6 +29,7 @@ def test_fix_native_literals_noop(s): ('str("""\nfoo""")', '"""\nfoo"""'), ('six.ensure_str("foo")', '"foo"'), ('six.ensure_text("foo")', '"foo"'), + ('six.text_type("foo")', '"foo"'), ), ) def test_fix_native_literals(s, expected):
six.text_type('') takes two passes to resolve For example: ```console $ pip freeze | grep pyupgrade pyupgrade==1.26.1 $ cat 1.py six.text_type('') $ pyupgrade 1.py --py3-plus Rewriting 1.py $ cat 1.py str('') $ pyupgrade 1.py --py3-plus Rewriting 1.py $ cat 1.py '' $ pyupgrade 1.py --py3-plus $ ``` Perhaps rewrite directly to `''`?
0.0
465effb0a65f3cd05d8b8201be4c8b899941b6e1
[ "tests/native_literals_test.py::test_fix_native_literals[six.text_type(\"foo\")-\"foo\"]" ]
[ "tests/native_literals_test.py::test_fix_native_literals_noop[str(1)]", "tests/native_literals_test.py::test_fix_native_literals_noop[str(\"foo\"\\n\"bar\")]", "tests/native_literals_test.py::test_fix_native_literals_noop[str(*a)]", "tests/native_literals_test.py::test_fix_native_literals_noop[str(\"foo\",", "tests/native_literals_test.py::test_fix_native_literals_noop[str(**k)]", "tests/native_literals_test.py::test_fix_native_literals[str()-'']", "tests/native_literals_test.py::test_fix_native_literals[str(\"foo\")-\"foo\"]", "tests/native_literals_test.py::test_fix_native_literals[str(\"\"\"\\nfoo\"\"\")-\"\"\"\\nfoo\"\"\"]", "tests/native_literals_test.py::test_fix_native_literals[six.ensure_str(\"foo\")-\"foo\"]", "tests/native_literals_test.py::test_fix_native_literals[six.ensure_text(\"foo\")-\"foo\"]" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-01-22 18:14:01+00:00
mit
1,155
asottile__pyupgrade-263
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))
asottile/pyupgrade
93a8c0f191e3ff269f5824bf1010f2920f0b1284
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 + + [email protected]( + '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 + + [email protected]( + ('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
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
0.0
93a8c0f191e3ff269f5824bf1010f2920f0b1284
[ "tests/fstrings_test.py::test_fix_fstrings[\"{}\".format(a())-f\"{a()}\"]", "tests/fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b())-f\"{a.b()}\"]", "tests/fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b().c())-f\"{a.b().c()}\"]", "tests/open_mode_test.py::test_fix_open_mode[open(\"foo\",", "tests/open_mode_test.py::test_fix_open_mode[open(\"f\"," ]
[ "tests/fstrings_test.py::test_fix_fstrings_noop[(]", "tests/fstrings_test.py::test_fix_fstrings_noop['{'.format(a)]", "tests/fstrings_test.py::test_fix_fstrings_noop['}'.format(a)]", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{}\"", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{}", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{foo}", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{0}", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{x}", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/fstrings_test.py::test_fix_fstrings_noop[b\"{}", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{}{}\".format(a)]", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{a}{b}\".format(a=a)]", "tests/fstrings_test.py::test_fix_fstrings[\"{}", "tests/fstrings_test.py::test_fix_fstrings[\"{1}", "tests/fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/fstrings_test.py::test_fix_fstrings[\"{.x}", "tests/fstrings_test.py::test_fix_fstrings[\"hello", "tests/fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped,", "tests/fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a,", "tests/open_mode_test.py::test_fix_open_mode_noop[open(\"foo\"," ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-02-20 13:07:36+00:00
mit
1,156
asottile__pyupgrade-279
diff --git a/pyupgrade.py b/pyupgrade.py index dab7eb2..bcd4250 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -1058,6 +1058,10 @@ def _fix_percent_format(contents_text: str) -> str: if node is None: continue + # TODO: handle \N escape sequences + if r'\N' in token.src: + continue + if isinstance(node.right, ast.Tuple): _fix_percent_format_tuple(tokens, i, node) elif isinstance(node.right, ast.Dict): @@ -2255,6 +2259,10 @@ def _fix_fstrings(contents_text: str) -> str: if node is None: continue + # TODO: handle \N escape sequences + if r'\N' in token.src: + continue + paren = i + 3 if tokens_to_src(tokens[i + 1:paren + 1]) != '.format(': continue
asottile/pyupgrade
e41b9c75f0cb73ce01d90bbfcb6bea558c42ff5d
diff --git a/tests/format_literals_test.py b/tests/format_literals_test.py index ae656d1..f3610a1 100644 --- a/tests/format_literals_test.py +++ b/tests/format_literals_test.py @@ -49,6 +49,8 @@ def test_intentionally_not_round_trip(s, expected): "'{' '0}'.format(1)", # comment looks like placeholder but is not! '("{0}" # {1}\n"{2}").format(1, 2, 3)', + # TODO: this works by accident (extended escape treated as placeholder) + r'"\N{snowman} {}".format(1)', ), ) def test_format_literals_noop(s): diff --git a/tests/fstrings_test.py b/tests/fstrings_test.py index d850293..2090930 100644 --- a/tests/fstrings_test.py +++ b/tests/fstrings_test.py @@ -26,6 +26,8 @@ from pyupgrade import _fix_fstrings '"{:{}}".format(x, y)', '"{a[b]}".format(a=a)', '"{a.a[b]}".format(a=a)', + # TODO: handle \N escape sequences + r'"\N{snowman} {}".format(a)', # not enough placeholders / placeholders missing '"{}{}".format(a)', '"{a}{b}".format(a=a)', ), diff --git a/tests/percent_format_test.py b/tests/percent_format_test.py index 6301620..e1c5f8d 100644 --- a/tests/percent_format_test.py +++ b/tests/percent_format_test.py @@ -176,6 +176,8 @@ def test_simplify_conversion_flag(s, expected): '"%(and)s" % {"and": 2}', # invalid string formats '"%" % {}', '"%(hi)" % {}', '"%2" % {}', + # TODO: handle \N escape sequences + r'"%s \N{snowman}" % (a,)', ), ) def test_percent_format_noop(s):
Valid f-string conversion throws KeyError While working on a conversion project, I noticed that certain files would throw `KeyError`'s for `\N{...}` strings. A minimal test case looks like: ```python world = "world" print("hello {} \N{snowman}".format(world)) ``` Which I would expect to be left alone or rewritten as: ```python world = "world" print(f"hello {world} \N{snowman}") ``` I had trouble reproducing it in pytests. This seemed to trigger the same error: ```diff diff --git tests/fstrings_test.py tests/fstrings_test.py index d850293..a772a0f 100644 --- tests/fstrings_test.py +++ tests/fstrings_test.py @@ -48,6 +48,7 @@ def test_fix_fstrings_noop(s): ('"hello {}!".format(name)', 'f"hello {name}!"'), ('"{}{{}}{}".format(escaped, y)', 'f"{escaped}{{}}{y}"'), ('"{}{b}{}".format(a, c, b=b)', 'f"{a}{b}{c}"'), + (r'"{}\N{snowman}".format(a)', r'f"{a}\N{snowman}"'), # TODO: poor man's f-strings? # '"{foo}".format(**locals())' ), ```
0.0
e41b9c75f0cb73ce01d90bbfcb6bea558c42ff5d
[ "tests/fstrings_test.py::test_fix_fstrings_noop[\"\\\\N{snowman}", "tests/percent_format_test.py::test_percent_format_noop[\"%s" ]
[ "tests/format_literals_test.py::test_roundtrip_text[]", "tests/format_literals_test.py::test_roundtrip_text[foo]", "tests/format_literals_test.py::test_roundtrip_text[{}]", "tests/format_literals_test.py::test_roundtrip_text[{0}]", "tests/format_literals_test.py::test_roundtrip_text[{named}]", "tests/format_literals_test.py::test_roundtrip_text[{!r}]", "tests/format_literals_test.py::test_roundtrip_text[{:>5}]", "tests/format_literals_test.py::test_roundtrip_text[{{]", "tests/format_literals_test.py::test_roundtrip_text[}}]", "tests/format_literals_test.py::test_roundtrip_text[{0!s:15}]", "tests/format_literals_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/format_literals_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/format_literals_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/format_literals_test.py::test_format_literals_noop[\"{0}\"format(1)]", "tests/format_literals_test.py::test_format_literals_noop['{}'.format(1)]", "tests/format_literals_test.py::test_format_literals_noop['{'.format(1)]", "tests/format_literals_test.py::test_format_literals_noop['}'.format(1)]", "tests/format_literals_test.py::test_format_literals_noop[x", "tests/format_literals_test.py::test_format_literals_noop['{0}", "tests/format_literals_test.py::test_format_literals_noop['{0:<{1}}'.format(1,", "tests/format_literals_test.py::test_format_literals_noop['{'", "tests/format_literals_test.py::test_format_literals_noop[(\"{0}\"", "tests/format_literals_test.py::test_format_literals_noop[\"\\\\N{snowman}", "tests/format_literals_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/format_literals_test.py::test_format_literals['{0:x}'.format(30)-'{:x}'.format(30)]", "tests/format_literals_test.py::test_format_literals[x", "tests/format_literals_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/format_literals_test.py::test_format_literals['{0}'", "tests/format_literals_test.py::test_format_literals[print(\\n", "tests/format_literals_test.py::test_format_literals[(\"{0}\").format(1)-(\"{}\").format(1)]", "tests/fstrings_test.py::test_fix_fstrings_noop[(]", "tests/fstrings_test.py::test_fix_fstrings_noop['{'.format(a)]", "tests/fstrings_test.py::test_fix_fstrings_noop['}'.format(a)]", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{}\"", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{}", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{foo}", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{0}", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{x}", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/fstrings_test.py::test_fix_fstrings_noop[b\"{}", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{}{}\".format(a)]", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{a}{b}\".format(a=a)]", "tests/fstrings_test.py::test_fix_fstrings[\"{}", "tests/fstrings_test.py::test_fix_fstrings[\"{1}", "tests/fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/fstrings_test.py::test_fix_fstrings[\"{.x}", "tests/fstrings_test.py::test_fix_fstrings[\"{}\".format(a())-f\"{a()}\"]", "tests/fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b())-f\"{a.b()}\"]", "tests/fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b().c())-f\"{a.b().c()}\"]", "tests/fstrings_test.py::test_fix_fstrings[\"hello", "tests/fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped,", "tests/fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a,", "tests/percent_format_test.py::test_parse_percent_format[\"\"-expected0]", "tests/percent_format_test.py::test_parse_percent_format[\"%%\"-expected1]", "tests/percent_format_test.py::test_parse_percent_format[\"%s\"-expected2]", "tests/percent_format_test.py::test_parse_percent_format[\"%s", "tests/percent_format_test.py::test_parse_percent_format[\"%(hi)s\"-expected4]", "tests/percent_format_test.py::test_parse_percent_format[\"%()s\"-expected5]", "tests/percent_format_test.py::test_parse_percent_format[\"%#o\"-expected6]", "tests/percent_format_test.py::test_parse_percent_format[\"%", "tests/percent_format_test.py::test_parse_percent_format[\"%5d\"-expected8]", "tests/percent_format_test.py::test_parse_percent_format[\"%*d\"-expected9]", "tests/percent_format_test.py::test_parse_percent_format[\"%.f\"-expected10]", "tests/percent_format_test.py::test_parse_percent_format[\"%.5f\"-expected11]", "tests/percent_format_test.py::test_parse_percent_format[\"%.*f\"-expected12]", "tests/percent_format_test.py::test_parse_percent_format[\"%ld\"-expected13]", "tests/percent_format_test.py::test_parse_percent_format[\"%(complete)#4.4f\"-expected14]", "tests/percent_format_test.py::test_percent_to_format[%s-{}]", "tests/percent_format_test.py::test_percent_to_format[%%%s-%{}]", "tests/percent_format_test.py::test_percent_to_format[%(foo)s-{foo}]", "tests/percent_format_test.py::test_percent_to_format[%2f-{:2f}]", "tests/percent_format_test.py::test_percent_to_format[%r-{!r}]", "tests/percent_format_test.py::test_percent_to_format[%a-{!a}]", "tests/percent_format_test.py::test_simplify_conversion_flag[-]", "tests/percent_format_test.py::test_simplify_conversion_flag[", "tests/percent_format_test.py::test_simplify_conversion_flag[#0-", "tests/percent_format_test.py::test_simplify_conversion_flag[--<]", "tests/percent_format_test.py::test_percent_format_noop[\"%s\"", "tests/percent_format_test.py::test_percent_format_noop[b\"%s\"", "tests/percent_format_test.py::test_percent_format_noop[\"%*s\"", "tests/percent_format_test.py::test_percent_format_noop[\"%.*s\"", "tests/percent_format_test.py::test_percent_format_noop[\"%d\"", "tests/percent_format_test.py::test_percent_format_noop[\"%i\"", "tests/percent_format_test.py::test_percent_format_noop[\"%u\"", "tests/percent_format_test.py::test_percent_format_noop[\"%c\"", "tests/percent_format_test.py::test_percent_format_noop[\"%#o\"", "tests/percent_format_test.py::test_percent_format_noop[\"%()s\"", "tests/percent_format_test.py::test_percent_format_noop[\"%4%\"", "tests/percent_format_test.py::test_percent_format_noop[\"%.2r\"", "tests/percent_format_test.py::test_percent_format_noop[\"%.2a\"", "tests/percent_format_test.py::test_percent_format_noop[i", "tests/percent_format_test.py::test_percent_format_noop[\"%(1)s\"", "tests/percent_format_test.py::test_percent_format_noop[\"%(a)s\"", "tests/percent_format_test.py::test_percent_format_noop[\"%(ab)s\"", "tests/percent_format_test.py::test_percent_format_noop[\"%(and)s\"", "tests/percent_format_test.py::test_percent_format_noop[\"%\"", "tests/percent_format_test.py::test_percent_format_noop[\"%(hi)\"", "tests/percent_format_test.py::test_percent_format_noop[\"%2\"", "tests/percent_format_test.py::test_percent_format[\"trivial\"", "tests/percent_format_test.py::test_percent_format[\"%s\"", "tests/percent_format_test.py::test_percent_format[\"%s%%", "tests/percent_format_test.py::test_percent_format[\"%3f\"", "tests/percent_format_test.py::test_percent_format[\"%-5s\"", "tests/percent_format_test.py::test_percent_format[\"%9s\"", "tests/percent_format_test.py::test_percent_format[\"brace", "tests/percent_format_test.py::test_percent_format[\"%(k)s\"", "tests/percent_format_test.py::test_percent_format[\"%(to_list)s\"" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-04-12 21:23:11+00:00
mit
1,157
asottile__pyupgrade-283
diff --git a/README.md b/README.md index 8178ec6..4e3a01a 100644 --- a/README.md +++ b/README.md @@ -387,6 +387,34 @@ except OSError: raise ``` +### `typing.NamedTuple` / `typing.TypedDict` py36+ syntax + +Availability: +- `--py36-plus` is passed on the commandline. + +```python +# input +NT = typing.NamedTuple('NT', [('a': int, 'b': Tuple[str, ...])]) + +D1 = typing.TypedDict('D1', a=int, b=str) + +D2 = typing.TypedDict('D2', {'a': int, 'b': str}) + +# output + +class NT(typing.NamedTuple): + a: int + b: Tuple[str, ...] + +class D1(typing.TypedDict): + a: int + b: str + +class D2(typing.TypedDict): + a: int + b: str +``` + ### f-strings Availability: diff --git a/pyupgrade.py b/pyupgrade.py index bcd4250..e6511be 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -54,6 +54,8 @@ SyncFunctionDef = Union[ast.FunctionDef, ast.Lambda] _stdlib_parse_format = string.Formatter().parse +_KEYWORDS = frozenset(keyword.kwlist) + def parse_format(s: str) -> Tuple[DotFormatPart, ...]: """Makes the empty string not a special case. In the stdlib, there's @@ -1000,7 +1002,7 @@ def _fix_percent_format_dict( elif not k.s.isidentifier(): return # a keyword - elif k.s in keyword.kwlist: + elif k.s in _KEYWORDS: return seen_keys.add(k.s) keys[_ast_to_offset(k)] = k @@ -2160,9 +2162,35 @@ def _format_params(call: ast.Call) -> Dict[str, str]: return params -class FindSimpleFormats(ast.NodeVisitor): +class FindPy36Plus(ast.NodeVisitor): def __init__(self) -> None: - self.found: Dict[Offset, ast.Call] = {} + self.fstrings: Dict[Offset, ast.Call] = {} + self.named_tuples: Dict[Offset, ast.Call] = {} + self.dict_typed_dicts: Dict[Offset, ast.Call] = {} + self.kw_typed_dicts: Dict[Offset, ast.Call] = {} + self._from_imports: Dict[str, Set[str]] = collections.defaultdict(set) + + def visit_ImportFrom(self, node: ast.ImportFrom) -> None: + if node.module in {'typing', 'typing_extensions'}: + for name in node.names: + if not name.asname: + self._from_imports[node.module].add(name.name) + self.generic_visit(node) + + def _is_attr(self, node: ast.AST, mods: Set[str], name: str) -> bool: + return ( + ( + isinstance(node, ast.Name) and + node.id == name and + any(name in self._from_imports[mod] for mod in mods) + ) or + ( + isinstance(node, ast.Attribute) and + node.attr == name and + isinstance(node.value, ast.Name) and + node.value.id in mods + ) + ) def _parse(self, node: ast.Call) -> Optional[Tuple[DotFormatPart, ...]]: if not ( @@ -2207,7 +2235,64 @@ class FindSimpleFormats(ast.NodeVisitor): if not candidate: i += 1 else: - self.found[_ast_to_offset(node)] = node + self.fstrings[_ast_to_offset(node)] = node + + self.generic_visit(node) + + def visit_Assign(self, node: ast.Assign) -> None: + if ( + # NT = ...("NT", ...) + len(node.targets) == 1 and + isinstance(node.targets[0], ast.Name) and + isinstance(node.value, ast.Call) and + len(node.value.args) >= 1 and + isinstance(node.value.args[0], ast.Str) and + node.targets[0].id == node.value.args[0].s and + not _starargs(node.value) + ): + if ( + self._is_attr( + node.value.func, {'typing'}, 'NamedTuple', + ) and + len(node.value.args) == 2 and + not node.value.keywords and + isinstance(node.value.args[1], (ast.List, ast.Tuple)) and + len(node.value.args[1].elts) > 0 and + all( + isinstance(tup, ast.Tuple) and + len(tup.elts) == 2 and + isinstance(tup.elts[0], ast.Str) and + tup.elts[0].s not in _KEYWORDS + for tup in node.value.args[1].elts + ) + ): + self.named_tuples[_ast_to_offset(node)] = node.value + elif ( + self._is_attr( + node.value.func, + {'typing', 'typing_extensions'}, + 'TypedDict', + ) and + len(node.value.args) == 1 and + len(node.value.keywords) > 0 + ): + self.kw_typed_dicts[_ast_to_offset(node)] = node.value + elif ( + self._is_attr( + node.value.func, + {'typing', 'typing_extensions'}, + 'TypedDict', + ) and + len(node.value.args) == 2 and + not node.value.keywords and + isinstance(node.value.args[1], ast.Dict) and + node.value.args[1].keys and + all( + isinstance(k, ast.Str) + for k in node.value.args[1].keys + ) + ): + self.dict_typed_dicts[_ast_to_offset(node)] = node.value self.generic_visit(node) @@ -2219,6 +2304,23 @@ def _unparse(node: ast.expr) -> str: return ''.join((_unparse(node.value), '.', node.attr)) elif isinstance(node, ast.Call): return '{}()'.format(_unparse(node.func)) + elif isinstance(node, ast.Subscript): + assert isinstance(node.slice, ast.Index), ast.dump(node) + if isinstance(node.slice.value, ast.Name): + slice_s = _unparse(node.slice.value) + elif isinstance(node.slice.value, ast.Tuple): + slice_s = ', '.join(_unparse(elt) for elt in node.slice.value.elts) + else: + raise NotImplementedError(ast.dump(node)) + return '{}[{}]'.format(_unparse(node.value), slice_s) + elif isinstance(node, ast.Str): + return repr(node.s) + elif isinstance(node, ast.Ellipsis): + return '...' + elif isinstance(node, ast.List): + return '[{}]'.format(', '.join(_unparse(elt) for elt in node.elts)) + elif isinstance(node, ast.NameConstant): + return repr(node.value) else: raise NotImplementedError(ast.dump(node)) @@ -2238,16 +2340,43 @@ def _to_fstring(src: str, call: ast.Call) -> str: return unparse_parsed_string(parts) -def _fix_fstrings(contents_text: str) -> str: +def _replace_typed_class( + tokens: List[Token], + i: int, + call: ast.Call, + types: Dict[str, ast.expr], +) -> None: + if i > 0 and tokens[i - 1].name in {'INDENT', UNIMPORTANT_WS}: + indent = f'{tokens[i - 1].src}{" " * 4}' + else: + indent = ' ' * 4 + + # NT = NamedTuple("nt", [("a", int)]) + # ^i ^end + end = i + 1 + while end < len(tokens) and tokens[end].name != 'NEWLINE': + end += 1 + + attrs = '\n'.join(f'{indent}{k}: {_unparse(v)}' for k, v in types.items()) + src = f'class {tokens[i].src}({_unparse(call.func)}):\n{attrs}' + tokens[i:end] = [Token('CODE', src)] + + +def _fix_py36_plus(contents_text: str) -> str: try: ast_obj = ast_parse(contents_text) except SyntaxError: return contents_text - visitor = FindSimpleFormats() + visitor = FindPy36Plus() visitor.visit(ast_obj) - if not visitor.found: + if not any(( + visitor.fstrings, + visitor.named_tuples, + visitor.dict_typed_dicts, + visitor.kw_typed_dicts, + )): return contents_text try: @@ -2255,27 +2384,50 @@ def _fix_fstrings(contents_text: str) -> str: except tokenize.TokenError: # pragma: no cover (bpo-2180) return contents_text for i, token in reversed_enumerate(tokens): - node = visitor.found.get(token.offset) - if node is None: - continue + if token.offset in visitor.fstrings: + node = visitor.fstrings[token.offset] - # TODO: handle \N escape sequences - if r'\N' in token.src: - continue + # TODO: handle \N escape sequences + if r'\N' in token.src: + continue - paren = i + 3 - if tokens_to_src(tokens[i + 1:paren + 1]) != '.format(': - continue + paren = i + 3 + if tokens_to_src(tokens[i + 1:paren + 1]) != '.format(': + continue - # we don't actually care about arg position, so we pass `node` - victims = _victims(tokens, paren, node, gen=False) - end = victims.ends[-1] - # if it spans more than one line, bail - if tokens[end].line != token.line: - continue + # we don't actually care about arg position, so we pass `node` + victims = _victims(tokens, paren, node, gen=False) + end = victims.ends[-1] + # if it spans more than one line, bail + if tokens[end].line != token.line: + continue - tokens[i] = token._replace(src=_to_fstring(token.src, node)) - del tokens[i + 1:end + 1] + tokens[i] = token._replace(src=_to_fstring(token.src, node)) + del tokens[i + 1:end + 1] + elif token.offset in visitor.named_tuples and token.name == 'NAME': + call = visitor.named_tuples[token.offset] + types: Dict[str, ast.expr] = { + tup.elts[0].s: tup.elts[1] # type: ignore # (checked above) + for tup in call.args[1].elts # type: ignore # (checked above) + } + _replace_typed_class(tokens, i, call, types) + elif token.offset in visitor.kw_typed_dicts and token.name == 'NAME': + call = visitor.kw_typed_dicts[token.offset] + types = { + arg.arg: arg.value # type: ignore # (checked above) + for arg in call.keywords + } + _replace_typed_class(tokens, i, call, types) + elif token.offset in visitor.dict_typed_dicts and token.name == 'NAME': + call = visitor.dict_typed_dicts[token.offset] + types = { + k.s: v # type: ignore # (checked above) + for k, v in zip( + call.args[1].keys, # type: ignore # (checked above) + call.args[1].values, # type: ignore # (checked above) + ) + } + _replace_typed_class(tokens, i, call, types) return tokens_to_src(tokens) @@ -2300,7 +2452,7 @@ def _fix_file(filename: str, args: argparse.Namespace) -> int: if args.min_version >= (3,): contents_text = _fix_py3_plus(contents_text) if args.min_version >= (3, 6): - contents_text = _fix_fstrings(contents_text) + contents_text = _fix_py36_plus(contents_text) if filename == '-': print(contents_text, end='')
asottile/pyupgrade
645dbea4874fa541dcdce1153fa1044e221b9bbb
diff --git a/tests/fstrings_test.py b/tests/fstrings_test.py index 2090930..fcc6a92 100644 --- a/tests/fstrings_test.py +++ b/tests/fstrings_test.py @@ -1,6 +1,6 @@ import pytest -from pyupgrade import _fix_fstrings +from pyupgrade import _fix_py36_plus @pytest.mark.parametrize( @@ -33,7 +33,7 @@ from pyupgrade import _fix_fstrings ), ) def test_fix_fstrings_noop(s): - assert _fix_fstrings(s) == s + assert _fix_py36_plus(s) == s @pytest.mark.parametrize( @@ -55,4 +55,4 @@ def test_fix_fstrings_noop(s): ), ) def test_fix_fstrings(s, expected): - assert _fix_fstrings(s) == expected + assert _fix_py36_plus(s) == expected diff --git a/tests/typing_named_tuple_test.py b/tests/typing_named_tuple_test.py new file mode 100644 index 0000000..83a41ef --- /dev/null +++ b/tests/typing_named_tuple_test.py @@ -0,0 +1,155 @@ +import pytest + +from pyupgrade import _fix_py36_plus + + [email protected]( + 's', + ( + '', + + pytest.param( + 'from typing import NamedTuple as wat\n' + 'C = wat("C", ("a", int))\n', + id='currently not following as imports', + ), + + pytest.param('C = typing.NamedTuple("C", ())', id='no types'), + pytest.param('C = typing.NamedTuple("C")', id='not enough args'), + pytest.param( + 'C = typing.NamedTuple("C", (), nonsense=1)', + id='namedtuple with named args', + ), + pytest.param( + 'C = typing.NamedTuple("C", {"foo": int, "bar": str})', + id='namedtuple without a list/tuple', + ), + pytest.param( + 'C = typing.NamedTuple("C", [["a", str], ["b", int]])', + id='namedtuple without inner tuples', + ), + pytest.param( + 'C = typing.NamedTuple("C", [(), ()])', + id='namedtuple but inner tuples are incorrect length', + ), + pytest.param( + 'C = typing.NamedTuple("C", [(not_a_str, str)])', + id='namedtuple but attribute name is not a string', + ), + + pytest.param( + 'C = typing.NamedTuple("C", [("def", int)])', + id='uses keyword', + ), + pytest.param( + 'C = typing.NamedTuple("C", *types)', + id='NamedTuple starargs', + ), + ), +) +def test_typing_named_tuple_noop(s): + assert _fix_py36_plus(s) == s + + [email protected]( + ('s', 'expected'), + ( + pytest.param( + 'from typing import NamedTuple\n' + 'C = NamedTuple("C", [("a", int), ("b", str)])\n', + + 'from typing import NamedTuple\n' + 'class C(NamedTuple):\n' + ' a: int\n' + ' b: str\n', + id='typing from import', + ), + pytest.param( + 'import typing\n' + 'C = typing.NamedTuple("C", [("a", int), ("b", str)])\n', + + 'import typing\n' + 'class C(typing.NamedTuple):\n' + ' a: int\n' + ' b: str\n', + + id='import typing', + ), + pytest.param( + 'C = typing.NamedTuple("C", [("a", List[int])])', + + 'class C(typing.NamedTuple):\n' + ' a: List[int]', + + id='generic attribute types', + ), + pytest.param( + 'C = typing.NamedTuple("C", [("a", Mapping[int, str])])', + + 'class C(typing.NamedTuple):\n' + ' a: Mapping[int, str]', + + id='generic attribute types with multi types', + ), + pytest.param( + 'C = typing.NamedTuple("C", [("a", "Queue[int]")])', + + 'class C(typing.NamedTuple):\n' + " a: 'Queue[int]'", + + id='quoted type names', + ), + pytest.param( + 'C = typing.NamedTuple("C", [("a", Tuple[int, ...])])', + + 'class C(typing.NamedTuple):\n' + ' a: Tuple[int, ...]', + + id='type with ellipsis', + ), + pytest.param( + 'C = typing.NamedTuple("C", [("a", Callable[[Any], None])])', + + 'class C(typing.NamedTuple):\n' + ' a: Callable[[Any], None]', + + id='type containing a list', + ), + pytest.param( + 'if False:\n' + ' pass\n' + 'C = typing.NamedTuple("C", [("a", int)])\n', + + 'if False:\n' + ' pass\n' + 'class C(typing.NamedTuple):\n' + ' a: int\n', + + id='class directly after block', + ), + pytest.param( + 'if True:\n' + ' C = typing.NamedTuple("C", [("a", int)])\n', + + 'if True:\n' + ' class C(typing.NamedTuple):\n' + ' a: int\n', + + id='indented', + ), + pytest.param( + 'if True:\n' + ' ...\n' + ' C = typing.NamedTuple("C", [("a", int)])\n', + + 'if True:\n' + ' ...\n' + ' class C(typing.NamedTuple):\n' + ' a: int\n', + + id='indented, but on next line', + ), + ), +) +def test_fix_typing_named_tuple(s, expected): + assert _fix_py36_plus(s) == expected diff --git a/tests/typing_typed_dict_test.py b/tests/typing_typed_dict_test.py new file mode 100644 index 0000000..af4e4e7 --- /dev/null +++ b/tests/typing_typed_dict_test.py @@ -0,0 +1,96 @@ +import pytest + +from pyupgrade import _fix_py36_plus + + [email protected]( + 's', + ( + pytest.param( + 'from wat import TypedDict\n' + 'Q = TypedDict("Q")\n', + id='from imported from elsewhere', + ), + pytest.param('D = typing.TypedDict("D")', id='no typed kwargs'), + pytest.param('D = typing.TypedDict("D", {})', id='no typed args'), + pytest.param('D = typing.TypedDict("D", {}, a=int)', id='both'), + pytest.param('D = typing.TypedDict("D", 1)', id='not a dict'), + pytest.param( + 'D = typing.TypedDict("D", {1: str})', + id='key is not a string', + ), + pytest.param( + 'D = typing.TypedDict("D", {**d, "a": str})', + id='dictionary splat operator', + ), + pytest.param( + 'C = typing.TypedDict("C", *types)', + id='starargs', + ), + pytest.param( + 'D = typing.TypedDict("D", **types)', + id='starstarkwargs', + ), + ), +) +def test_typing_typed_dict_noop(s): + assert _fix_py36_plus(s) == s + + [email protected]( + ('s', 'expected'), + ( + pytest.param( + 'from typing import TypedDict\n' + 'D = TypedDict("D", a=int)\n', + + 'from typing import TypedDict\n' + 'class D(TypedDict):\n' + ' a: int\n', + + id='keyword TypedDict from imported', + ), + pytest.param( + 'import typing\n' + 'D = typing.TypedDict("D", a=int)\n', + + 'import typing\n' + 'class D(typing.TypedDict):\n' + ' a: int\n', + + id='keyword TypedDict from attribute', + ), + pytest.param( + 'import typing\n' + 'D = typing.TypedDict("D", {"a": int})\n', + + 'import typing\n' + 'class D(typing.TypedDict):\n' + ' a: int\n', + + id='TypedDict from dict literal', + ), + pytest.param( + 'from typing_extensions import TypedDict\n' + 'D = TypedDict("D", a=int)\n', + + 'from typing_extensions import TypedDict\n' + 'class D(TypedDict):\n' + ' a: int\n', + + id='keyword TypedDict from typing_extensions', + ), + pytest.param( + 'import typing_extensions\n' + 'D = typing_extensions.TypedDict("D", {"a": int})\n', + + 'import typing_extensions\n' + 'class D(typing_extensions.TypedDict):\n' + ' a: int\n', + + id='keyword TypedDict from typing_extensions', + ), + ), +) +def test_typing_typed_dict(s, expected): + assert _fix_py36_plus(s) == expected
rewrite typing.NamedTuple and typing.TypedDict to class form in --py36-plus ```python Employee = NamedTuple('Employee', [('name', str), ('id', int)]) ``` becomes ```python class Employee(NamedTuple): name: str id: int ```
0.0
645dbea4874fa541dcdce1153fa1044e221b9bbb
[ "tests/fstrings_test.py::test_fix_fstrings_noop[(]", "tests/fstrings_test.py::test_fix_fstrings_noop['{'.format(a)]", "tests/fstrings_test.py::test_fix_fstrings_noop['}'.format(a)]", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{}\"", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{}", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{foo}", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{0}", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{x}", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/fstrings_test.py::test_fix_fstrings_noop[b\"{}", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]", "tests/fstrings_test.py::test_fix_fstrings_noop[\"\\\\N{snowman}", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{}{}\".format(a)]", "tests/fstrings_test.py::test_fix_fstrings_noop[\"{a}{b}\".format(a=a)]", "tests/fstrings_test.py::test_fix_fstrings[\"{}", "tests/fstrings_test.py::test_fix_fstrings[\"{1}", "tests/fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/fstrings_test.py::test_fix_fstrings[\"{.x}", "tests/fstrings_test.py::test_fix_fstrings[\"{}\".format(a())-f\"{a()}\"]", "tests/fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b())-f\"{a.b()}\"]", "tests/fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b().c())-f\"{a.b().c()}\"]", "tests/fstrings_test.py::test_fix_fstrings[\"hello", "tests/fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped,", "tests/fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a,", "tests/typing_named_tuple_test.py::test_typing_named_tuple_noop[]", "tests/typing_named_tuple_test.py::test_typing_named_tuple_noop[currently", "tests/typing_named_tuple_test.py::test_typing_named_tuple_noop[no", "tests/typing_named_tuple_test.py::test_typing_named_tuple_noop[not", "tests/typing_named_tuple_test.py::test_typing_named_tuple_noop[namedtuple", "tests/typing_named_tuple_test.py::test_typing_named_tuple_noop[uses", "tests/typing_named_tuple_test.py::test_typing_named_tuple_noop[NamedTuple", "tests/typing_named_tuple_test.py::test_fix_typing_named_tuple[typing", "tests/typing_named_tuple_test.py::test_fix_typing_named_tuple[import", "tests/typing_named_tuple_test.py::test_fix_typing_named_tuple[quoted", "tests/typing_named_tuple_test.py::test_fix_typing_named_tuple[class", "tests/typing_named_tuple_test.py::test_fix_typing_named_tuple[indented]", "tests/typing_named_tuple_test.py::test_fix_typing_named_tuple[indented,", "tests/typing_typed_dict_test.py::test_typing_typed_dict_noop[from", "tests/typing_typed_dict_test.py::test_typing_typed_dict_noop[no", "tests/typing_typed_dict_test.py::test_typing_typed_dict_noop[both]", "tests/typing_typed_dict_test.py::test_typing_typed_dict_noop[not", "tests/typing_typed_dict_test.py::test_typing_typed_dict_noop[key", "tests/typing_typed_dict_test.py::test_typing_typed_dict_noop[dictionary", "tests/typing_typed_dict_test.py::test_typing_typed_dict_noop[starargs]", "tests/typing_typed_dict_test.py::test_typing_typed_dict_noop[starstarkwargs]", "tests/typing_typed_dict_test.py::test_typing_typed_dict[keyword", "tests/typing_typed_dict_test.py::test_typing_typed_dict[TypedDict" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-04-16 02:19:39+00:00
mit
1,158
asottile__pyupgrade-286
diff --git a/pyupgrade.py b/pyupgrade.py index 6173624..8e3bda3 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -2,6 +2,7 @@ import argparse import ast import codecs import collections +import contextlib import keyword import re import string @@ -1199,6 +1200,15 @@ class FindPy3Plus(ast.NodeVisitor): self.def_depth = 0 self.first_arg_name = '' + class Scope: + def __init__(self) -> None: + self.reads: Set[str] = set() + self.writes: Set[str] = set() + + self.yield_from_fors: Set[Offset] = set() + self.yield_from_names: Dict[str, Set[Offset]] + self.yield_from_names = collections.defaultdict(set) + def __init__(self) -> None: self.bases_to_remove: Set[Offset] = set() @@ -1238,6 +1248,7 @@ class FindPy3Plus(ast.NodeVisitor): self._in_comp = 0 self.super_calls: Dict[Offset, ast.Call] = {} self._in_async_def = False + self._scope_stack: List[FindPy3Plus.Scope] = [] self.yield_from_fors: Set[Offset] = set() self.no_arg_decorators: Set[Offset] = set() @@ -1366,15 +1377,40 @@ class FindPy3Plus(ast.NodeVisitor): self.generic_visit(node) self._class_info_stack.pop() - def _visit_func(self, node: AnyFunctionDef) -> None: - if self._class_info_stack: - class_info = self._class_info_stack[-1] - class_info.def_depth += 1 - if class_info.def_depth == 1 and node.args.args: - class_info.first_arg_name = node.args.args[0].arg - self.generic_visit(node) + @contextlib.contextmanager + def _track_def_depth( + self, + node: AnyFunctionDef, + ) -> Generator[None, None, None]: + class_info = self._class_info_stack[-1] + class_info.def_depth += 1 + if class_info.def_depth == 1 and node.args.args: + class_info.first_arg_name = node.args.args[0].arg + try: + yield + finally: class_info.def_depth -= 1 - else: + + @contextlib.contextmanager + def _scope(self) -> Generator[None, None, None]: + self._scope_stack.append(FindPy3Plus.Scope()) + try: + yield + finally: + info = self._scope_stack.pop() + # discard any that were referenced outside of the loop + for name in info.reads: + offsets = info.yield_from_names[name] + info.yield_from_fors.difference_update(offsets) + self.yield_from_fors.update(info.yield_from_fors) + if self._scope_stack: + cell_reads = info.reads - info.writes + self._scope_stack[-1].reads.update(cell_reads) + + def _visit_func(self, node: AnyFunctionDef) -> None: + with contextlib.ExitStack() as ctx, self._scope(): + if self._class_info_stack: + ctx.enter_context(self._track_def_depth(node)) self.generic_visit(node) def _visit_sync_func(self, node: SyncFunctionDef) -> None: @@ -1391,20 +1427,33 @@ class FindPy3Plus(ast.NodeVisitor): def _visit_comp(self, node: ast.expr) -> None: self._in_comp += 1 - self.generic_visit(node) + with self._scope(): + self.generic_visit(node) self._in_comp -= 1 visit_ListComp = visit_SetComp = _visit_comp visit_DictComp = visit_GeneratorExp = _visit_comp - def _visit_simple(self, node: NameOrAttr) -> None: + def visit_Attribute(self, node: ast.Attribute) -> None: if self._is_six(node, SIX_SIMPLE_ATTRS): self.six_simple[_ast_to_offset(node)] = node elif self._is_mock_mock(node): self.mock_mock.add(_ast_to_offset(node)) self.generic_visit(node) - visit_Attribute = visit_Name = _visit_simple + def visit_Name(self, node: ast.Name) -> None: + if self._is_six(node, SIX_SIMPLE_ATTRS): + self.six_simple[_ast_to_offset(node)] = node + + if self._scope_stack: + if isinstance(node.ctx, ast.Load): + self._scope_stack[-1].reads.add(node.id) + elif isinstance(node.ctx, ast.Store): + self._scope_stack[-1].writes.add(node.id) + else: + raise AssertionError(node) + + self.generic_visit(node) def visit_Try(self, node: ast.Try) -> None: for handler in node.handlers: @@ -1632,9 +1681,24 @@ class FindPy3Plus(ast.NodeVisitor): targets_same(node.target, node.body[0].value.value) and not node.orelse ): - self.yield_from_fors.add(_ast_to_offset(node)) - - self.generic_visit(node) + offset = _ast_to_offset(node) + func_info = self._scope_stack[-1] + func_info.yield_from_fors.add(offset) + for target_node in ast.walk(node.target): + if ( + isinstance(target_node, ast.Name) and + isinstance(target_node.ctx, ast.Store) + ): + func_info.yield_from_names[target_node.id].add(offset) + # manually visit, but with target+body as a separate scope + self.visit(node.iter) + with self._scope(): + self.visit(node.target) + for stmt in node.body: + self.visit(stmt) + assert not node.orelse + else: + self.generic_visit(node) def generic_visit(self, node: ast.AST) -> None: self._previous_node = node
asottile/pyupgrade
71fcce45b826a5fe1695f4a8368197c3064cb303
diff --git a/tests/yield_from_test.py b/tests/yield_from_test.py index ce70bfb..bda592a 100644 --- a/tests/yield_from_test.py +++ b/tests/yield_from_test.py @@ -127,6 +127,18 @@ from pyupgrade import targets_same '\n' ' return g', ), + pytest.param( + 'def f():\n' + ' for x in y:\n' + ' yield x\n' + ' for z in x:\n' + ' yield z\n', + 'def f():\n' + ' for x in y:\n' + ' yield x\n' + ' yield from x\n', + id='leave one loop alone (referenced after assignment)', + ), ), ) def test_fix_yield_from(s, expected): @@ -166,6 +178,33 @@ def test_fix_yield_from(s, expected): ' yield x\n' ' else:\n' ' print("boom!")\n', + pytest.param( + 'def f():\n' + ' for x in range(5):\n' + ' yield x\n' + ' print(x)\n', + id='variable referenced after loop', + ), + pytest.param( + 'def f():\n' + ' def g():\n' + ' print(x)\n' + ' for x in range(5):\n' + ' yield x\n' + ' g()\n', + id='variable referenced after loop, but via function', + ), + pytest.param( + 'def f():\n' + ' def g():\n' + ' def h():\n' + ' print(x)\n' + ' return h\n' + ' for x in range(5):\n' + ' yield x\n' + ' g()()\n', + id='variable referenced after loop, but via nested function', + ), ), ) def test_fix_yield_from_noop(s):
'yield from' rewrite unsafe when looping variable is referenced later Consider the example code: ```py def foo(it): item = None for item in it: yield item print("Last item", item) ``` With `--py3-plus`, this is transformed to: ```py def foo(it): item = None yield from it print("Last item", item) ``` But these are not equivalent. The line `print("Last item", item)` now always prints `None` rather than the last item of the passed iterable. This was discovered in more-itertools: https://github.com/erikrose/more-itertools/blob/8d860c355a1dd900e3a9c5fe1303ddf5a778452f/more_itertools/more.py#L1206-L1223
0.0
71fcce45b826a5fe1695f4a8368197c3064cb303
[ "tests/yield_from_test.py::test_fix_yield_from[leave", "tests/yield_from_test.py::test_fix_yield_from_noop[variable" ]
[ "tests/yield_from_test.py::test_fix_yield_from[def", "tests/yield_from_test.py::test_fix_yield_from[async", "tests/yield_from_test.py::test_fix_yield_from_noop[def", "tests/yield_from_test.py::test_targets_same", "tests/yield_from_test.py::test_fields_same" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-04-22 03:07:23+00:00
mit
1,159
asottile__pyupgrade-289
diff --git a/README.md b/README.md index 1a2f764..f6f6ffc 100644 --- a/README.md +++ b/README.md @@ -170,11 +170,19 @@ class C(Base): Availability: - `--py3-plus` is passed on the commandline. +#### rewrites class declaration + ```python class C(object): pass # class C: pass class C(B, object): pass # class C(B): pass ``` +#### removes `__metaclass__ = type` declaration + +```diff +-__metaclass__ = type +``` + ### forced `str("native")` literals Availability: diff --git a/pyupgrade.py b/pyupgrade.py index 8913496..29fbb8f 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -242,8 +242,8 @@ def _victims( return Victims(starts, sorted(set(ends)), first_comma_index, arg_index) -def _find_token(tokens: List[Token], i: int, token: Token) -> int: - while tokens[i].src != token: +def _find_token(tokens: List[Token], i: int, src: str) -> int: + while tokens[i].src != src: i += 1 return i @@ -454,7 +454,7 @@ ESCAPE_RE = re.compile(r'\\.', re.DOTALL) NAMED_ESCAPE_NAME = re.compile(r'\{[^}]+\}') -def _fix_escape_sequences(token: Token) -> str: +def _fix_escape_sequences(token: Token) -> Token: prefix, rest = parse_string_literal(token.src) actual_prefix = prefix.lower() @@ -1204,6 +1204,7 @@ class FindPy3Plus(ast.NodeVisitor): self.if_py3_blocks: Set[Offset] = set() self.if_py2_blocks_else: Set[Offset] = set() self.if_py3_blocks_else: Set[Offset] = set() + self.metaclass_type_assignments: Set[Offset] = set() self.native_literals: Set[Offset] = set() @@ -1486,6 +1487,19 @@ class FindPy3Plus(ast.NodeVisitor): self.generic_visit(node) + def visit_Assign(self, node: ast.Assign) -> None: + if ( + len(node.targets) == 1 and + isinstance(node.targets[0], ast.Name) and + node.targets[0].col_offset == 0 and + node.targets[0].id == '__metaclass__' and + isinstance(node.value, ast.Name) and + node.value.id == 'type' + ): + self.metaclass_type_assignments.add(_ast_to_offset(node)) + + self.generic_visit(node) + @staticmethod def _eq(test: ast.Compare, n: int) -> bool: return ( @@ -1609,7 +1623,7 @@ class Block(NamedTuple): colon: int block: int end: int - line: int + line: bool def _initial_indent(self, tokens: List[Token]) -> int: if tokens[self.start].src.isspace(): @@ -1869,6 +1883,7 @@ def _fix_py3_plus(contents_text: str) -> str: visitor.if_py2_blocks_else, visitor.if_py3_blocks, visitor.if_py3_blocks_else, + visitor.metaclass_type_assignments, visitor.native_literals, visitor.io_open_calls, visitor.open_mode_calls, @@ -1943,6 +1958,16 @@ def _fix_py3_plus(contents_text: str) -> str: if_block, else_block = _find_if_else_block(tokens, j) del tokens[if_block.end:else_block.end] if_block.replace_condition(tokens, [Token('NAME', 'else')]) + elif token.offset in visitor.metaclass_type_assignments: + j = _find_token(tokens, i, 'type') + while tokens[j].name not in {'NEWLINE', 'ENDMARKER'}: + j += 1 + # depending on the version of python, some will not emit + # NEWLINE('') at the end of a file which does not end with a + # newline (for example 3.6.5) + if tokens[j].name == 'ENDMARKER': # pragma: no cover + j -= 1 + del tokens[i:j + 1] elif token.offset in visitor.native_literals: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j)
asottile/pyupgrade
7c740d9f19c50f12c848fd081141dc750096ff30
diff --git a/tests/metaclass_type_test.py b/tests/metaclass_type_test.py new file mode 100644 index 0000000..51b92c2 --- /dev/null +++ b/tests/metaclass_type_test.py @@ -0,0 +1,57 @@ +import pytest + +from pyupgrade import _fix_py3_plus + + [email protected]( + 's', + ( + pytest.param( + 'x = type\n' + '__metaclass__ = x\n', + id='not rewriting "type" rename', + ), + pytest.param( + 'def foo():\n' + ' __metaclass__ = type\n', + id='not rewriting function scope', + ), + pytest.param( + 'class Foo:\n' + ' __metaclass__ = type\n', + id='not rewriting class scope', + ), + pytest.param( + '__metaclass__, __meta_metaclass__ = type, None\n', + id='not rewriting multiple assignment', + ), + ), +) +def test_metaclass_type_assignment_noop(s): + assert _fix_py3_plus(s) == s + + [email protected]( + ('s', 'expected'), + ( + pytest.param( + '__metaclass__ = type', + '', + id='module-scope assignment', + ), + pytest.param( + '__metaclass__ = type', + '', + id='module-scope assignment with extra whitespace', + ), + pytest.param( + '__metaclass__ = (\n' + ' type\n' + ')\n', + '', + id='module-scope assignment across newline', + ), + ), +) +def test_fix_metaclass_type_assignment(s, expected): + assert _fix_py3_plus(s) == expected
Remove `__metaclass__ = type` at module scope in --py3-plus mode this was a way to trigger new-style classes in python2
0.0
7c740d9f19c50f12c848fd081141dc750096ff30
[ "tests/metaclass_type_test.py::test_fix_metaclass_type_assignment[module-scope" ]
[ "tests/metaclass_type_test.py::test_metaclass_type_assignment_noop[not" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-04-24 21:32:21+00:00
mit
1,160
asottile__pyupgrade-308
diff --git a/pyupgrade.py b/pyupgrade.py index 8e3bda3..a49ef68 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -1448,7 +1448,7 @@ class FindPy3Plus(ast.NodeVisitor): if self._scope_stack: if isinstance(node.ctx, ast.Load): self._scope_stack[-1].reads.add(node.id) - elif isinstance(node.ctx, ast.Store): + elif isinstance(node.ctx, (ast.Store, ast.Del)): self._scope_stack[-1].writes.add(node.id) else: raise AssertionError(node)
asottile/pyupgrade
6eed58483836b7c951f9d1173c1c39700b87c722
diff --git a/tests/yield_from_test.py b/tests/yield_from_test.py index bda592a..5aa9c45 100644 --- a/tests/yield_from_test.py +++ b/tests/yield_from_test.py @@ -205,6 +205,11 @@ def test_fix_yield_from(s, expected): ' g()()\n', id='variable referenced after loop, but via nested function', ), + pytest.param( + 'def f(x):\n' + ' del x\n', + id='regression with del ctx (#306)', + ), ), ) def test_fix_yield_from_noop(s):
py3-plus: AssertionError: del statement in function pyupgrade 2.4.2 Minimal test case: ```py def foo(bar): del bar ``` ``` pyupgrade --py3-plus test.py ``` ``` Traceback (most recent call last): File "./venv/bin/pyupgrade", line 8, in <module> sys.exit(main()) File "/home/jon/venv/lib64/python3.8/site-packages/pyupgrade.py", line 2680, in main ret |= _fix_file(filename, args) File "/home/jon/venv/lib64/python3.8/site-packages/pyupgrade.py", line 2638, in _fix_file contents_text = _fix_py3_plus(contents_text, args.min_version) File "/home/jon/venv/lib64/python3.8/site-packages/pyupgrade.py", line 2002, in _fix_py3_plus visitor.visit(ast_obj) File "/usr/lib64/python3.8/ast.py", line 360, in visit return visitor(node) File "/home/jon/venv/lib64/python3.8/site-packages/pyupgrade.py", line 1705, in generic_visit super().generic_visit(node) File "/usr/lib64/python3.8/ast.py", line 368, in generic_visit self.visit(item) File "/usr/lib64/python3.8/ast.py", line 360, in visit return visitor(node) File "/home/jon/venv/lib64/python3.8/site-packages/pyupgrade.py", line 1418, in _visit_sync_func self._visit_func(node) File "/home/jon/venv/lib64/python3.8/site-packages/pyupgrade.py", line 1414, in _visit_func self.generic_visit(node) File "/home/jon/venv/lib64/python3.8/site-packages/pyupgrade.py", line 1705, in generic_visit super().generic_visit(node) File "/usr/lib64/python3.8/ast.py", line 368, in generic_visit self.visit(item) File "/usr/lib64/python3.8/ast.py", line 360, in visit return visitor(node) File "/home/jon/venv/lib64/python3.8/site-packages/pyupgrade.py", line 1705, in generic_visit super().generic_visit(node) File "/usr/lib64/python3.8/ast.py", line 368, in generic_visit self.visit(item) File "/usr/lib64/python3.8/ast.py", line 360, in visit return visitor(node) File "/home/jon/venv/lib64/python3.8/site-packages/pyupgrade.py", line 1454, in visit_Name raise AssertionError(node) AssertionError: <_ast.Name object at 0x7f6b26fd0a90> ``` Encountered in real life code: https://github.com/andymccurdy/redis-py/blob/7c0a67a5cb4a20aea44c590837b0e79c9c09c510/tests/test_multiprocessing.py#L157-L159
0.0
6eed58483836b7c951f9d1173c1c39700b87c722
[ "tests/yield_from_test.py::test_fix_yield_from_noop[regression" ]
[ "tests/yield_from_test.py::test_fix_yield_from[def", "tests/yield_from_test.py::test_fix_yield_from[async", "tests/yield_from_test.py::test_fix_yield_from[leave", "tests/yield_from_test.py::test_fix_yield_from_noop[def", "tests/yield_from_test.py::test_fix_yield_from_noop[variable", "tests/yield_from_test.py::test_targets_same", "tests/yield_from_test.py::test_fields_same" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2020-05-17 00:24:03+00:00
mit
1,161
asottile__pyupgrade-313
diff --git a/pyupgrade.py b/pyupgrade.py index a49ef68..45a13bb 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -1127,7 +1127,7 @@ SIX_NATIVE_STR = frozenset(('ensure_str', 'ensure_text', 'text_type')) U_MODE_REMOVE = frozenset(('U', 'Ur', 'rU', 'r', 'rt', 'tr')) U_MODE_REPLACE_R = frozenset(('Ub', 'bU')) U_MODE_REMOVE_U = frozenset(('rUb', 'Urb', 'rbU', 'Ubr', 'bUr', 'brU')) -U_MODE_ALL = U_MODE_REMOVE | U_MODE_REPLACE_R | U_MODE_REMOVE_U +U_MODE_REPLACE = U_MODE_REPLACE_R | U_MODE_REMOVE_U def _all_isinstance( @@ -1570,10 +1570,12 @@ class FindPy3Plus(ast.NodeVisitor): 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 U_MODE_ALL + len(node.args) >= 2 and + isinstance(node.args[1], ast.Str) and ( + node.args[1].s in U_MODE_REPLACE or + (len(node.args) == 2 and node.args[1].s in U_MODE_REMOVE) + ) ): self.open_mode_calls.add(_ast_to_offset(node)) elif (
asottile/pyupgrade
06444be5513ab77a149b7b4ae44d51803561e36f
diff --git a/tests/open_mode_test.py b/tests/open_mode_test.py index dd306a8..1398792 100644 --- a/tests/open_mode_test.py +++ b/tests/open_mode_test.py @@ -13,6 +13,8 @@ from pyupgrade import _fix_py3_plus 'open("foo", "Uw")', # TODO: could maybe be rewritten to remove t? 'open("foo", "wt")', + # don't remove this, they meant to use `encoding=` + 'open("foo", "r", "utf-8")', ), ) def test_fix_open_mode_noop(s):
open() rewrite doesn't always consider other positional args Minimal input: ```py with open('blah.txt', 'r', 'utf-8') as fp: pass ``` Actual output: ```py with open('blah.txt', 'utf-8') as fp: pass ``` Expected: ```py with open('blah.txt', encoding='utf-8') as fp: pass ``` The rewrite causes the following Python error upon executing the code: ``` Traceback (most recent call last): File "blah.py", line 1, in <module> with open('blah.txt', 'utf-8') as fp: ValueError: invalid mode: 'utf-8' ``` Discovered in a real code base: https://github.com/andialbrecht/sqlparse/blob/28a2acdd9b307c95d2111f1f831b1a5afc634691/sqlparse/cli.py#L175
0.0
06444be5513ab77a149b7b4ae44d51803561e36f
[ "tests/open_mode_test.py::test_fix_open_mode_noop[open(\"foo\"," ]
[ "tests/open_mode_test.py::test_fix_open_mode[open(\"foo\",", "tests/open_mode_test.py::test_fix_open_mode[open(\"f\"," ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2020-05-24 21:01:20+00:00
mit
1,162
asottile__pyupgrade-316
diff --git a/README.md b/README.md index ce8b62e..c16b744 100644 --- a/README.md +++ b/README.md @@ -243,6 +243,7 @@ Availability: Availability: - `--py3-plus` is passed on the commandline. +- [Unless `--keep-mock` is passed on the commandline](https://github.com/asottile/pyupgrade/issues/314). ```diff -from mock import patch diff --git a/pyupgrade.py b/pyupgrade.py index 45a13bb..cb91999 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -1209,7 +1209,9 @@ class FindPy3Plus(ast.NodeVisitor): self.yield_from_names: Dict[str, Set[Offset]] self.yield_from_names = collections.defaultdict(set) - def __init__(self) -> None: + def __init__(self, keep_mock: bool) -> None: + self._find_mock = not keep_mock + self.bases_to_remove: Set[Offset] = set() self.encode_calls: Dict[Offset, ast.Call] = {} @@ -1330,7 +1332,7 @@ class FindPy3Plus(ast.NodeVisitor): for name in node.names: if not name.asname: self._from_imports[node.module].add(name.name) - elif node.module in self.MOCK_MODULES: + elif self._find_mock and node.module in self.MOCK_MODULES: self.mock_relative_imports.add(_ast_to_offset(node)) elif node.module == 'sys' and any( name.name == 'version_info' and not name.asname @@ -1341,6 +1343,7 @@ class FindPy3Plus(ast.NodeVisitor): def visit_Import(self, node: ast.Import) -> None: if ( + self._find_mock and len(node.names) == 1 and node.names[0].name in self.MOCK_MODULES ): @@ -1437,7 +1440,7 @@ class FindPy3Plus(ast.NodeVisitor): def visit_Attribute(self, node: ast.Attribute) -> None: if self._is_six(node, SIX_SIMPLE_ATTRS): self.six_simple[_ast_to_offset(node)] = node - elif self._is_mock_mock(node): + elif self._find_mock and self._is_mock_mock(node): self.mock_mock.add(_ast_to_offset(node)) self.generic_visit(node) @@ -1994,13 +1997,17 @@ def _replace_yield(tokens: List[Token], i: int) -> None: tokens[i:block.end] = [Token('CODE', f'yield from {container}\n')] -def _fix_py3_plus(contents_text: str, min_version: MinVersion) -> str: +def _fix_py3_plus( + contents_text: str, + min_version: MinVersion, + keep_mock: bool = False, +) -> str: try: ast_obj = ast_parse(contents_text) except SyntaxError: return contents_text - visitor = FindPy3Plus() + visitor = FindPy3Plus(keep_mock) visitor.visit(ast_obj) if not any(( @@ -2637,7 +2644,9 @@ def _fix_file(filename: str, args: argparse.Namespace) -> int: if not args.keep_percent_format: contents_text = _fix_percent_format(contents_text) if args.min_version >= (3,): - contents_text = _fix_py3_plus(contents_text, args.min_version) + contents_text = _fix_py3_plus( + contents_text, args.min_version, args.keep_mock, + ) if args.min_version >= (3, 6): contents_text = _fix_py36_plus(contents_text) @@ -2659,6 +2668,7 @@ def main(argv: Optional[Sequence[str]] = None) -> int: parser.add_argument('filenames', nargs='*') parser.add_argument('--exit-zero-even-if-changed', action='store_true') parser.add_argument('--keep-percent-format', action='store_true') + parser.add_argument('--keep-mock', action='store_true') parser.add_argument( '--py3-plus', '--py3-only', action='store_const', dest='min_version', default=(2, 7), const=(3,),
asottile/pyupgrade
400b8bb96f70c7b21c2237dbfd89d4a3664bb875
diff --git a/tests/mock_test.py b/tests/mock_test.py index f57676a..9ca60b0 100644 --- a/tests/mock_test.py +++ b/tests/mock_test.py @@ -20,6 +20,16 @@ def test_mock_noop(s): assert _fix_py3_plus(s, (3,)) == s +def test_mock_noop_keep_mock(): + """This would've been rewritten if keep_mock were False""" + s = ( + 'from mock import patch\n' + '\n' + 'patch("func")' + ) + assert _fix_py3_plus(s, (3,), keep_mock=True) == s + + @pytest.mark.parametrize( ('s', 'expected'), (
some way to skip replacing mock with unittest.mock when you're using python 3.6 or 3.7 `unittest.mock.AsyncMock` is unavailable, but `mock.AsyncMock` is available if you're using the latest backport there should be some way to skip replacing `mock` with `unittest.mock`, or the fixer should be moved to `--py38-plus` and then to a later `--py...-plus` as and when `unittest.mock` gains features
0.0
400b8bb96f70c7b21c2237dbfd89d4a3664bb875
[ "tests/mock_test.py::test_mock_noop_keep_mock" ]
[ "tests/mock_test.py::test_mock_noop[does", "tests/mock_test.py::test_mock_noop[leave", "tests/mock_test.py::test_fix_mock[relative", "tests/mock_test.py::test_fix_mock[absolute", "tests/mock_test.py::test_fix_mock[double" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-05-27 13:19:47+00:00
mit
1,163
asottile__pyupgrade-317
diff --git a/pyupgrade.py b/pyupgrade.py index cb91999..6b84e93 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -1157,8 +1157,8 @@ def fields_same(n1: ast.AST, n2: ast.AST) -> bool: return True -def targets_same(target: ast.AST, yield_value: ast.AST) -> bool: - for t1, t2 in zip(ast.walk(target), ast.walk(yield_value)): +def targets_same(node1: ast.AST, node2: ast.AST) -> bool: + for t1, t2 in zip(ast.walk(node1), ast.walk(node2)): # ignore `ast.Load` / `ast.Store` if _all_isinstance((t1, t2), ast.expr_context): continue @@ -1177,6 +1177,15 @@ def _is_codec(encoding: str, name: str) -> bool: return False +def _is_simple_base(base: ast.AST) -> bool: + return ( + isinstance(base, ast.Name) or ( + isinstance(base, ast.Attribute) and + _is_simple_base(base.value) + ) + ) + + class FindPy3Plus(ast.NodeVisitor): OS_ERROR_ALIASES = frozenset(( 'EnvironmentError', @@ -1195,8 +1204,9 @@ class FindPy3Plus(ast.NodeVisitor): MOCK_MODULES = frozenset(('mock', 'mock.mock')) class ClassInfo: - def __init__(self, name: str) -> None: - self.name = name + def __init__(self, node: ast.ClassDef) -> None: + self.bases = node.bases + self.name = node.name self.def_depth = 0 self.first_arg_name = '' @@ -1249,6 +1259,7 @@ class FindPy3Plus(ast.NodeVisitor): self._class_info_stack: List[FindPy3Plus.ClassInfo] = [] self._in_comp = 0 self.super_calls: Dict[Offset, ast.Call] = {} + self.old_style_super_calls: Set[Offset] = set() self._in_async_def = False self._scope_stack: List[FindPy3Plus.Scope] = [] self.yield_from_fors: Set[Offset] = set() @@ -1376,7 +1387,7 @@ class FindPy3Plus(ast.NodeVisitor): ): self.six_with_metaclass.add(_ast_to_offset(node.bases[0])) - self._class_info_stack.append(FindPy3Plus.ClassInfo(node.name)) + self._class_info_stack.append(FindPy3Plus.ClassInfo(node)) self.generic_visit(node) self._class_info_stack.pop() @@ -1542,6 +1553,21 @@ class FindPy3Plus(ast.NodeVisitor): node.args[1].id == self._class_info_stack[-1].first_arg_name ): self.super_calls[_ast_to_offset(node)] = node + elif ( + not self._in_comp and + self._class_info_stack and + self._class_info_stack[-1].def_depth == 1 and + len(self._class_info_stack[-1].bases) == 1 and + _is_simple_base(self._class_info_stack[-1].bases[0]) and + isinstance(node.func, ast.Attribute) and + targets_same( + self._class_info_stack[-1].bases[0], node.func.value, + ) and + len(node.args) >= 1 and + isinstance(node.args[0], ast.Name) and + node.args[0].id == self._class_info_stack[-1].first_arg_name + ): + self.old_style_super_calls.add(_ast_to_offset(node)) elif ( ( self._is_six(node.func, SIX_NATIVE_STR) or @@ -1771,7 +1797,7 @@ class Block(NamedTuple): diff = self._minimum_indent(tokens) - self._initial_indent(tokens) for i in range(self.block, self.end): if ( - tokens[i - 1].name in ('NL', 'NEWLINE') and + tokens[i - 1].name in ('DEDENT', 'NL', 'NEWLINE') and tokens[i].name in ('INDENT', UNIMPORTANT_WS) ): tokens[i] = tokens[i]._replace(src=tokens[i].src[diff:]) @@ -2038,6 +2064,7 @@ def _fix_py3_plus( visitor.six_type_ctx, visitor.six_with_metaclass, visitor.super_calls, + visitor.old_style_super_calls, visitor.yield_from_fors, )): return contents_text @@ -2197,6 +2224,18 @@ def _fix_py3_plus( call = visitor.super_calls[token.offset] victims = _victims(tokens, i, call, gen=False) del tokens[victims.starts[0] + 1:victims.ends[-1]] + elif token.offset in visitor.old_style_super_calls: + j = _find_open_paren(tokens, i) + k = j - 1 + while tokens[k].src != '.': + k -= 1 + func_args, end = _parse_call_args(tokens, j) + # remove the first argument + if len(func_args) == 1: + del tokens[func_args[0][0]:func_args[0][0] + 1] + else: + del tokens[func_args[0][0]:func_args[1][0] + 1] + tokens[i:k] = [Token('CODE', 'super()')] elif token.offset in visitor.encode_calls: i = _find_open_paren(tokens, i) call = visitor.encode_calls[token.offset]
asottile/pyupgrade
4656fbe8173b927bc215d09db1af0ef739741ad0
diff --git a/tests/super_test.py b/tests/super_test.py index 7ec0095..95eba81 100644 --- a/tests/super_test.py +++ b/tests/super_test.py @@ -121,3 +121,77 @@ def test_fix_super_noop(s): ) def test_fix_super(s, expected): assert _fix_py3_plus(s, (3,)) == expected + + [email protected]( + 's', + ( + pytest.param( + 'class C(B):\n' + ' def f(self):\n' + ' B.f(notself)\n', + id='old style super, first argument is not first function arg', + ), + pytest.param( + 'class C(B1, B2):\n' + ' def f(self):\n' + ' B1.f(self)\n', + # TODO: is this safe to rewrite? I don't think so + id='old-style super, multiple inheritance first class', + ), + pytest.param( + 'class C(B1, B2):\n' + ' def f(self):\n' + ' B2.f(self)\n', + # TODO: is this safe to rewrite? I don't think so + id='old-style super, multiple inheritance not-first class', + ), + pytest.param( + 'class C(Base):\n' + ' def f(self):\n' + ' return [Base.f(self) for _ in ()]\n', + id='super in comprehension', + ), + pytest.param( + 'class C(Base):\n' + ' def f(self):\n' + ' def g():\n' + ' Base.f(self)\n' + ' g()\n', + id='super in nested functions', + ), + pytest.param( + 'class C(not_simple()):\n' + ' def f(self):\n' + ' not_simple().f(self)\n', + id='not a simple base', + ), + pytest.param( + 'class C(a().b):\n' + ' def f(self):\n' + ' a().b.f(self)\n', + id='non simple attribute base', + ), + ), +) +def test_old_style_class_super_noop(s): + assert _fix_py3_plus(s, (3,)) == s + + [email protected]( + ('s', 'expected'), + ( + ( + 'class C(B):\n' + ' def f(self):\n' + ' B.f(self)\n' + ' B.f(self, arg, arg)\n', + 'class C(B):\n' + ' def f(self):\n' + ' super().f()\n' + ' super().f(arg, arg)\n', + ), + ), +) +def test_old_style_class_super(s, expected): + assert _fix_py3_plus(s, (3,)) == expected diff --git a/tests/versioned_branches_test.py b/tests/versioned_branches_test.py index b0512f1..2f93791 100644 --- a/tests/versioned_branches_test.py +++ b/tests/versioned_branches_test.py @@ -264,6 +264,25 @@ def test_fix_py2_block_noop(s): id='six.PY2, comment after', ), + pytest.param( + 'if six.PY2:\n' + ' def f():\n' + ' print("py2")\n' + ' def g():\n' + ' print("py2")\n' + 'else:\n' + ' def f():\n' + ' print("py3")\n' + ' def g():\n' + ' print("py3")\n', + + 'def f():\n' + ' print("py3")\n' + 'def g():\n' + ' print("py3")\n', + + id='six.PY2 multiple functions', + ), pytest.param( 'if True:\n' ' if six.PY3:\n'
Rewrite old-style class `super()` calls as well For example: ```python class H(logging.StreamHandler): def __init__(self) -> None: logging.StreamHandler.__init__(self) # ... ``` should become ```python class H(logging.StreamHandler): def __init__(self) -> None: super().__init__() # ... ```
0.0
4656fbe8173b927bc215d09db1af0ef739741ad0
[ "tests/super_test.py::test_old_style_class_super[class", "tests/versioned_branches_test.py::test_fix_py2_blocks[six.PY2" ]
[ "tests/super_test.py::test_fix_super_noop[x(]", "tests/super_test.py::test_fix_super_noop[class", "tests/super_test.py::test_fix_super_noop[def", "tests/super_test.py::test_fix_super[class", "tests/super_test.py::test_fix_super[async", "tests/super_test.py::test_old_style_class_super_noop[old", "tests/super_test.py::test_old_style_class_super_noop[old-style", "tests/super_test.py::test_old_style_class_super_noop[super", "tests/super_test.py::test_old_style_class_super_noop[not", "tests/super_test.py::test_old_style_class_super_noop[non", "tests/versioned_branches_test.py::test_fix_py2_block_noop[if", "tests/versioned_branches_test.py::test_fix_py2_block_noop[from", "tests/versioned_branches_test.py::test_fix_py2_block_noop[relative", "tests/versioned_branches_test.py::test_fix_py2_blocks[six.PY2]", "tests/versioned_branches_test.py::test_fix_py2_blocks[six.PY2,", "tests/versioned_branches_test.py::test_fix_py2_blocks[not", "tests/versioned_branches_test.py::test_fix_py2_blocks[six.PY3]", "tests/versioned_branches_test.py::test_fix_py2_blocks[indented", "tests/versioned_branches_test.py::test_fix_py2_blocks[six.PY3,", "tests/versioned_branches_test.py::test_fix_py2_blocks[sys.version_info", "tests/versioned_branches_test.py::test_fix_py2_blocks[from", "tests/versioned_branches_test.py::test_fix_py2_blocks[elif", "tests/versioned_branches_test.py::test_fix_py3_only_code[if" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-06-10 23:31:39+00:00
mit
1,164
asottile__pyupgrade-319
diff --git a/pyupgrade.py b/pyupgrade.py index cb91999..f6e8e94 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -1771,7 +1771,7 @@ class Block(NamedTuple): diff = self._minimum_indent(tokens) - self._initial_indent(tokens) for i in range(self.block, self.end): if ( - tokens[i - 1].name in ('NL', 'NEWLINE') and + tokens[i - 1].name in ('DEDENT', 'NL', 'NEWLINE') and tokens[i].name in ('INDENT', UNIMPORTANT_WS) ): tokens[i] = tokens[i]._replace(src=tokens[i].src[diff:])
asottile/pyupgrade
4656fbe8173b927bc215d09db1af0ef739741ad0
diff --git a/tests/versioned_branches_test.py b/tests/versioned_branches_test.py index b0512f1..2f93791 100644 --- a/tests/versioned_branches_test.py +++ b/tests/versioned_branches_test.py @@ -264,6 +264,25 @@ def test_fix_py2_block_noop(s): id='six.PY2, comment after', ), + pytest.param( + 'if six.PY2:\n' + ' def f():\n' + ' print("py2")\n' + ' def g():\n' + ' print("py2")\n' + 'else:\n' + ' def f():\n' + ' print("py3")\n' + ' def g():\n' + ' print("py3")\n', + + 'def f():\n' + ' print("py3")\n' + 'def g():\n' + ' print("py3")\n', + + id='six.PY2 multiple functions', + ), pytest.param( 'if True:\n' ' if six.PY3:\n'
py2 / py3 branch rewrite breaks indentation ```python import six if six.PY2: # pragma: no cover (py2) def wsgi_to_text(s): # Use latin-1, the encoding of ip addresses isn't important (they'll # always be either ascii, or invalidated by the ipaddress module) return s.decode('LATIN-1') def text_to_wsgi(s): return s.encode('US-ASCII') else: # pragma: no cover (py3) def wsgi_to_text(s): return s def text_to_wsgi(s): return s def f(): pass ``` currently rewritten to ```python import six def wsgi_to_text(s): return s def text_to_wsgi(s): return s def f(): pass ```
0.0
4656fbe8173b927bc215d09db1af0ef739741ad0
[ "tests/versioned_branches_test.py::test_fix_py2_blocks[six.PY2" ]
[ "tests/versioned_branches_test.py::test_fix_py2_block_noop[if", "tests/versioned_branches_test.py::test_fix_py2_block_noop[from", "tests/versioned_branches_test.py::test_fix_py2_block_noop[relative", "tests/versioned_branches_test.py::test_fix_py2_blocks[six.PY2]", "tests/versioned_branches_test.py::test_fix_py2_blocks[six.PY2,", "tests/versioned_branches_test.py::test_fix_py2_blocks[not", "tests/versioned_branches_test.py::test_fix_py2_blocks[six.PY3]", "tests/versioned_branches_test.py::test_fix_py2_blocks[indented", "tests/versioned_branches_test.py::test_fix_py2_blocks[six.PY3,", "tests/versioned_branches_test.py::test_fix_py2_blocks[sys.version_info", "tests/versioned_branches_test.py::test_fix_py2_blocks[from", "tests/versioned_branches_test.py::test_fix_py2_blocks[elif", "tests/versioned_branches_test.py::test_fix_py3_only_code[if" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-06-12 00:57:41+00:00
mit
1,165
asottile__pyupgrade-324
diff --git a/pyupgrade.py b/pyupgrade.py index f6e8e94..d740aa0 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -2449,6 +2449,7 @@ class FindPy36Plus(ast.NodeVisitor): isinstance(tup, ast.Tuple) and len(tup.elts) == 2 and isinstance(tup.elts[0], ast.Str) and + tup.elts[0].s.isidentifier() and tup.elts[0].s not in _KEYWORDS for tup in node.value.args[1].elts ) @@ -2475,7 +2476,9 @@ class FindPy36Plus(ast.NodeVisitor): isinstance(node.value.args[1], ast.Dict) and node.value.args[1].keys and all( - isinstance(k, ast.Str) + isinstance(k, ast.Str) and + k.s.isidentifier() and + k.s not in _KEYWORDS for k in node.value.args[1].keys ) ):
asottile/pyupgrade
efd108d02503dc0cba7661d9f5d80420d2ac246c
diff --git a/tests/typing_named_tuple_test.py b/tests/typing_named_tuple_test.py index 3e38502..083d672 100644 --- a/tests/typing_named_tuple_test.py +++ b/tests/typing_named_tuple_test.py @@ -41,6 +41,10 @@ from pyupgrade import _fix_py36_plus 'C = typing.NamedTuple("C", [("def", int)])', id='uses keyword', ), + pytest.param( + 'C = typing.NamedTuple("C", [("not-ok", int)])', + id='uses non-identifier', + ), pytest.param( 'C = typing.NamedTuple("C", *types)', id='NamedTuple starargs', diff --git a/tests/typing_typed_dict_test.py b/tests/typing_typed_dict_test.py index fb39c6b..eea6ef4 100644 --- a/tests/typing_typed_dict_test.py +++ b/tests/typing_typed_dict_test.py @@ -19,6 +19,14 @@ from pyupgrade import _fix_py36_plus 'D = typing.TypedDict("D", {1: str})', id='key is not a string', ), + pytest.param( + 'D = typing.TypedDict("D", {"a-b": str})', + id='key is not an identifier', + ), + pytest.param( + 'D = typing.TypedDict("D", {"class": str})', + id='key is a keyword', + ), pytest.param( 'D = typing.TypedDict("D", {**d, "a": str})', id='dictionary splat operator',
Rewriting TypedDict can lead to SyntaxError pyupgrade checks if the keys of a TypedDict are strings, but not if they are valid for usage in class syntax. Here's a minimal input: ```python from typing_extensions import TypedDict MyDict = TypedDict("MyDict", {"my-key": str, "another key": int}) ``` This is the rewrite produced by `pyupgrade --py36-plus minimal.py`: ```python from typing_extensions import TypedDict class MyDict(TypedDict): my-key: str another key: int ``` The `-` and the space in the keys are invalid syntax.
0.0
efd108d02503dc0cba7661d9f5d80420d2ac246c
[ "tests/typing_named_tuple_test.py::test_typing_named_tuple_noop[uses", "tests/typing_typed_dict_test.py::test_typing_typed_dict_noop[key" ]
[ "tests/typing_named_tuple_test.py::test_typing_named_tuple_noop[]", "tests/typing_named_tuple_test.py::test_typing_named_tuple_noop[currently", "tests/typing_named_tuple_test.py::test_typing_named_tuple_noop[no", "tests/typing_named_tuple_test.py::test_typing_named_tuple_noop[not", "tests/typing_named_tuple_test.py::test_typing_named_tuple_noop[namedtuple", "tests/typing_named_tuple_test.py::test_typing_named_tuple_noop[NamedTuple", "tests/typing_named_tuple_test.py::test_typing_named_tuple_noop[relative", "tests/typing_named_tuple_test.py::test_fix_typing_named_tuple[typing", "tests/typing_named_tuple_test.py::test_fix_typing_named_tuple[import", "tests/typing_named_tuple_test.py::test_fix_typing_named_tuple[generic", "tests/typing_named_tuple_test.py::test_fix_typing_named_tuple[quoted", "tests/typing_named_tuple_test.py::test_fix_typing_named_tuple[type", "tests/typing_named_tuple_test.py::test_fix_typing_named_tuple[class", "tests/typing_named_tuple_test.py::test_fix_typing_named_tuple[indented]", "tests/typing_named_tuple_test.py::test_fix_typing_named_tuple[indented,", "tests/typing_named_tuple_test.py::test_fix_typing_named_tuple[actually", "tests/typing_typed_dict_test.py::test_typing_typed_dict_noop[from", "tests/typing_typed_dict_test.py::test_typing_typed_dict_noop[no", "tests/typing_typed_dict_test.py::test_typing_typed_dict_noop[both]", "tests/typing_typed_dict_test.py::test_typing_typed_dict_noop[not", "tests/typing_typed_dict_test.py::test_typing_typed_dict_noop[dictionary", "tests/typing_typed_dict_test.py::test_typing_typed_dict_noop[starargs]", "tests/typing_typed_dict_test.py::test_typing_typed_dict_noop[starstarkwargs]", "tests/typing_typed_dict_test.py::test_typing_typed_dict[keyword", "tests/typing_typed_dict_test.py::test_typing_typed_dict[TypedDict", "tests/typing_typed_dict_test.py::test_typing_typed_dict[index" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-06-25 05:58:54+00:00
mit
1,166
asottile__pyupgrade-330
diff --git a/pyupgrade.py b/pyupgrade.py index c463fcf..54bbe0d 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -587,6 +587,11 @@ def _fix_format_literal(tokens: List[Token], end: int) -> None: parsed_parts = [] last_int = -1 for i in parts: + # f'foo {0}'.format(...) would get turned into a SyntaxError + prefix, _ = parse_string_literal(tokens[i].src) + if 'f' in prefix.lower(): + return + try: parsed = parse_format(tokens[i].src) except ValueError:
asottile/pyupgrade
162e74ef019982b8c744276103f1efdbac8459d0
diff --git a/tests/format_literals_test.py b/tests/format_literals_test.py index f3610a1..0719138 100644 --- a/tests/format_literals_test.py +++ b/tests/format_literals_test.py @@ -51,6 +51,8 @@ def test_intentionally_not_round_trip(s, expected): '("{0}" # {1}\n"{2}").format(1, 2, 3)', # TODO: this works by accident (extended escape treated as placeholder) r'"\N{snowman} {}".format(1)', + # don't touch f-strings (these are wrong but don't make it worse) + 'f"{0}".format(a)', ), ) def test_format_literals_noop(s):
pyupgrade on f-strings with .format() results in invalid f-string I understand that this is an edge-case because the input was buggy, but it _does_ convert running code into non-running code. ``` $ cat a.py print(f"foo {0}".format("bar")) $ python a.py foo 0 $ pyupgrade a.py Rewriting a.py $ cat a.py print(f"foo {}".format("bar")) $ python a.py File "a.py", line 1 print(f"foo {}".format("bar")) ^ SyntaxError: f-string: empty expression not allowed ``` ``` $ pip freeze | grep pyupgrade pyupgrade==2.7.0 ``` I'm not sure what the right behavior is in this case; maybe just don't touch numbered args inside an f-string?
0.0
162e74ef019982b8c744276103f1efdbac8459d0
[ "tests/format_literals_test.py::test_format_literals_noop[f\"{0}\".format(a)]" ]
[ "tests/format_literals_test.py::test_roundtrip_text[]", "tests/format_literals_test.py::test_roundtrip_text[foo]", "tests/format_literals_test.py::test_roundtrip_text[{}]", "tests/format_literals_test.py::test_roundtrip_text[{0}]", "tests/format_literals_test.py::test_roundtrip_text[{named}]", "tests/format_literals_test.py::test_roundtrip_text[{!r}]", "tests/format_literals_test.py::test_roundtrip_text[{:>5}]", "tests/format_literals_test.py::test_roundtrip_text[{{]", "tests/format_literals_test.py::test_roundtrip_text[}}]", "tests/format_literals_test.py::test_roundtrip_text[{0!s:15}]", "tests/format_literals_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/format_literals_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/format_literals_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/format_literals_test.py::test_format_literals_noop[\"{0}\"format(1)]", "tests/format_literals_test.py::test_format_literals_noop['{}'.format(1)]", "tests/format_literals_test.py::test_format_literals_noop['{'.format(1)]", "tests/format_literals_test.py::test_format_literals_noop['}'.format(1)]", "tests/format_literals_test.py::test_format_literals_noop[x", "tests/format_literals_test.py::test_format_literals_noop['{0}", "tests/format_literals_test.py::test_format_literals_noop['{0:<{1}}'.format(1,", "tests/format_literals_test.py::test_format_literals_noop['{'", "tests/format_literals_test.py::test_format_literals_noop[(\"{0}\"", "tests/format_literals_test.py::test_format_literals_noop[\"\\\\N{snowman}", "tests/format_literals_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/format_literals_test.py::test_format_literals['{0:x}'.format(30)-'{:x}'.format(30)]", "tests/format_literals_test.py::test_format_literals[x", "tests/format_literals_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/format_literals_test.py::test_format_literals['{0}'", "tests/format_literals_test.py::test_format_literals[print(\\n", "tests/format_literals_test.py::test_format_literals[(\"{0}\").format(1)-(\"{}\").format(1)]" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-07-16 18:38:18+00:00
mit
1,167
asottile__pyupgrade-332
diff --git a/pyupgrade.py b/pyupgrade.py index 54bbe0d..8b47463 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -1558,7 +1558,7 @@ class FindPy3Plus(ast.NodeVisitor): elif ( isinstance(self._previous_node, ast.Expr) and self._is_six(node.func, ('reraise',)) and - not _starargs(node) or self._is_star_sys_exc_info(node) + (not _starargs(node) or self._is_star_sys_exc_info(node)) ): self.six_reraise.add(_ast_to_offset(node)) elif (
asottile/pyupgrade
13401ad8d06e9c9986909de5316135fe3dfc49ec
diff --git a/tests/six_test.py b/tests/six_test.py index 0a973c0..9ddffd7 100644 --- a/tests/six_test.py +++ b/tests/six_test.py @@ -41,6 +41,7 @@ from pyupgrade import _fix_py3_plus 'isinstance("foo", text_type)\n', id='relative import might not be six', ), + ('traceback.format_exc(*sys.exc_info())'), ), ) def test_fix_six_noop(s):
exception stack trace is replaced by a bare `raise` With python 3.7.4, the formatted exception stack trace will be replaced by a bare `raise`, and then make a syntax error. But the strange thing is that this occurs only when the statement is executed in the pre-commit hook of git, the replacement disappears if the statement is executed directly. ```python poetry run pyupgrade --py37-plus ``` - Before ```python async def general_exception_handler(request: Request, exc: Exception): return JSONResponse( status_code=HTTP_500_INTERNAL_SERVER_ERROR, content={ 'request': f'{request.method} {request.url}', 'message': str(exc), 'detail': jsonable_encoder(traceback.format_exception(*sys.exc_info())), }, ) ``` - After ```python async def general_exception_handler(request: Request, exc: Exception): return JSONResponse( status_code=HTTP_500_INTERNAL_SERVER_ERROR, content={ 'request': f'{request.method} {request.url}', 'message': str(exc), # the exception stack info is replaced by a bare `raise` 'detail': jsonable_encoder(raise), }, ) ```
0.0
13401ad8d06e9c9986909de5316135fe3dfc49ec
[ "tests/six_test.py::test_fix_six_noop[traceback.format_exc(*sys.exc_info())]" ]
[ "tests/six_test.py::test_fix_six_noop[x", "tests/six_test.py::test_fix_six_noop[from", "tests/six_test.py::test_fix_six_noop[@mydec\\nclass", "tests/six_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/six_test.py::test_fix_six_noop[print(six.b(\"\\xa3\"))]", "tests/six_test.py::test_fix_six_noop[print(six.b(", "tests/six_test.py::test_fix_six_noop[class", "tests/six_test.py::test_fix_six_noop[six.reraise(*err)]", "tests/six_test.py::test_fix_six_noop[six.b(*a)]", "tests/six_test.py::test_fix_six_noop[six.u(*a)]", "tests/six_test.py::test_fix_six_noop[@six.add_metaclass(*a)\\nclass", "tests/six_test.py::test_fix_six_noop[(\\n", "tests/six_test.py::test_fix_six_noop[next()]", "tests/six_test.py::test_fix_six_noop[relative", "tests/six_test.py::test_fix_six[isinstance(s,", "tests/six_test.py::test_fix_six[weird", "tests/six_test.py::test_fix_six[issubclass(tp,", "tests/six_test.py::test_fix_six[STRING_TYPES", "tests/six_test.py::test_fix_six[from", "tests/six_test.py::test_fix_six[six.b(\"123\")-b\"123\"]", "tests/six_test.py::test_fix_six[six.b(r\"123\")-br\"123\"]", "tests/six_test.py::test_fix_six[six.b(\"\\\\x12\\\\xef\")-b\"\\\\x12\\\\xef\"]", "tests/six_test.py::test_fix_six[six.ensure_binary(\"foo\")-b\"foo\"]", "tests/six_test.py::test_fix_six[six.byte2int(b\"f\")-b\"f\"[0]]", "tests/six_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/six_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/six_test.py::test_fix_six[six.get_unbound_function(meth)\\n-meth\\n]", "tests/six_test.py::test_fix_six[six.indexbytes(bs,", "tests/six_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/six_test.py::test_fix_six[six.raise_from(exc,", "tests/six_test.py::test_fix_six[six.reraise(tp,", "tests/six_test.py::test_fix_six[six.reraise(*sys.exc_info())\\n-raise\\n]", "tests/six_test.py::test_fix_six[six.reraise(\\n", "tests/six_test.py::test_fix_six[class", "tests/six_test.py::test_fix_six[elide", "tests/six_test.py::test_fix_six[basic", "tests/six_test.py::test_fix_six[add_metaclass,", "tests/six_test.py::test_fix_six[six.itervalues]", "tests/six_test.py::test_fix_six[six.itervalues", "tests/six_test.py::test_fix_base_classes[import", "tests/six_test.py::test_fix_base_classes[from", "tests/six_test.py::test_fix_base_classes[class" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-07-24 15:24:04+00:00
mit
1,168
asottile__pyupgrade-347
diff --git a/pyupgrade.py b/pyupgrade.py index 8fe8d11..79f2bb2 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -2233,7 +2233,7 @@ def _fix_py3_plus( victims = _victims(tokens, i, call, gen=False) del tokens[victims.starts[0] + 1:victims.ends[-1]] elif token.offset in visitor.encode_calls: - i = _find_open_paren(tokens, i) + i = _find_open_paren(tokens, i + 1) call = visitor.encode_calls[token.offset] victims = _victims(tokens, i, call, gen=False) del tokens[victims.starts[0] + 1:victims.ends[-1]]
asottile/pyupgrade
1510dc5bf302e4218f6202185b6725e6a2653e07
diff --git a/tests/default_encoding_test.py b/tests/default_encoding_test.py index 4385583..f39548d 100644 --- a/tests/default_encoding_test.py +++ b/tests/default_encoding_test.py @@ -13,6 +13,14 @@ from pyupgrade import _fix_py3_plus 'sys.stdout.buffer.write(\n "a"\n "b".encode("utf-8")\n)', 'sys.stdout.buffer.write(\n "a"\n "b".encode()\n)', ), + ( + 'x = (\n' + ' "y\\u2603"\n' + ').encode("utf-8")\n', + 'x = (\n' + ' "y\\u2603"\n' + ').encode()\n', + ), ), ) def test_fix_encode(s, expected):
pyupgrade incorrect output before ```python expectedResult = ( ":example.com \u0442\u0435\u0441\u0442 " "\u043d\u0438\u043a\r\n" ).encode("utf-8") ``` expected ```python b':example.com \xd1\x82\xd0\xb5\xd1\x81\xd1\x82 \xd0\xbd\xd0\xb8\xd0\xba\r\n' ``` or maybe this? ```python ':example.com тест ник\r\n'.encode() ``` actual ```python expectedResult = ().encode("utf-8") ```
0.0
1510dc5bf302e4218f6202185b6725e6a2653e07
[ "tests/default_encoding_test.py::test_fix_encode[x" ]
[ "tests/default_encoding_test.py::test_fix_encode[\"asd\".encode(\"utf-8\")-\"asd\".encode()]", "tests/default_encoding_test.py::test_fix_encode[\"asd\".encode(\"utf8\")-\"asd\".encode()]", "tests/default_encoding_test.py::test_fix_encode[\"asd\".encode(\"UTF-8\")-\"asd\".encode()]", "tests/default_encoding_test.py::test_fix_encode[sys.stdout.buffer.write(\\n", "tests/default_encoding_test.py::test_fix_encode_noop[\"asd\".encode(\"unknown-codec\")]", "tests/default_encoding_test.py::test_fix_encode_noop[\"asd\".encode(\"ascii\")]", "tests/default_encoding_test.py::test_fix_encode_noop[x=\"asd\"\\nx.encode(\"utf-8\")]", "tests/default_encoding_test.py::test_fix_encode_noop[\"asd\".encode(\"utf-8\",", "tests/default_encoding_test.py::test_fix_encode_noop[\"asd\".encode(encoding=\"utf-8\")]" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2020-10-22 18:23:32+00:00
mit
1,169
asottile__pyupgrade-36
diff --git a/README.md b/README.md index 61fa28f..701a77a 100644 --- a/README.md +++ b/README.md @@ -94,9 +94,6 @@ Availability: 0755 # 0o755 ``` - -## Planned features - ### f-strings Availability: @@ -105,4 +102,5 @@ Availability: ```python '{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}' ``` diff --git a/pyupgrade.py b/pyupgrade.py index b4e7ec2..84db080 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -413,8 +413,8 @@ def _imports_unicode_literals(contents_text): STRING_PREFIXES_RE = re.compile('^([^\'"]*)(.*)$', re.DOTALL) -def _fix_unicode_literals(contents_text, py3_only): - if not py3_only and not _imports_unicode_literals(contents_text): +def _fix_unicode_literals(contents_text, py3_plus): + if not py3_plus and not _imports_unicode_literals(contents_text): return contents_text tokens = src_to_tokens(contents_text) for i, token in enumerate(tokens): @@ -511,7 +511,7 @@ def parse_percent_format(s): return tuple(_parse_inner()) -class FindsPercentFormats(ast.NodeVisitor): +class FindPercentFormats(ast.NodeVisitor): def __init__(self): self.found = {} @@ -600,18 +600,12 @@ def _fix_percent_format_tuple(tokens, start, node): elif c.lower() == 'b': # pragma: no cover (py2 only) return - p = start + 4 - ws1, perc, ws2, paren = tokens[start + 1:p + 1] - if ( - ws1.name != UNIMPORTANT_WS or ws1.src != ' ' or - perc.name != 'OP' or perc.src != '%' or - ws2.name != UNIMPORTANT_WS or ws2.src != ' ' or - paren.name != 'OP' or paren.src != '(' - ): - # TODO: this is overly timid + # TODO: this is overly timid + paren = start + 4 + if tokens_to_src(tokens[start + 1:paren + 1]) != ' % (': return - victims = _victims(tokens, p, node.right, gen=False) + victims = _victims(tokens, paren, node.right, gen=False) victims.ends.pop() for index in reversed(victims.starts + victims.ends): @@ -619,7 +613,7 @@ def _fix_percent_format_tuple(tokens, start, node): newsrc = _percent_to_format(tokens[start].src) tokens[start] = tokens[start]._replace(src=newsrc) - tokens[start + 1:p] = [Token('Format', '.format'), Token('OP', '(')] + tokens[start + 1:paren] = [Token('Format', '.format'), Token('OP', '(')] def _fix_percent_format(contents_text): @@ -628,7 +622,7 @@ def _fix_percent_format(contents_text): except SyntaxError: return contents_text - visitor = FindsPercentFormats() + visitor = FindPercentFormats() visitor.visit(ast_obj) tokens = src_to_tokens(contents_text) @@ -644,6 +638,110 @@ def _fix_percent_format(contents_text): return tokens_to_src(tokens) +def _simple_arg(arg): + return ( + isinstance(arg, ast.Name) or + (isinstance(arg, ast.Attribute) and _simple_arg(arg.value)) + ) + + +def _starargs(call): + return ( # pragma: no branch (starred check uncovered in py2) + # py2 + getattr(call, 'starargs', None) or + getattr(call, 'kwargs', None) or + any(k.arg is None for k in call.keywords) or ( + # py3 + getattr(ast, 'Starred', None) and + any(isinstance(a, ast.Starred) for a in call.args) + ) + ) + + +class FindSimpleFormats(ast.NodeVisitor): + def __init__(self): + self.found = {} + + def visit_Call(self, node): + if ( + isinstance(node.func, ast.Attribute) and + isinstance(node.func.value, ast.Str) and + node.func.attr == 'format' and + all(_simple_arg(arg) for arg in node.args) and + all(_simple_arg(k.value) for k in node.keywords) and + not _starargs(node) + ): + seen = set() + for _, name, _, _ in parse_format(node.func.value.s): + if name is not None: + candidate, _, _ = name.partition('.') + # timid: could make the f-string longer + if candidate and candidate in seen: + break + seen.add(candidate) + else: + self.found[Offset(node.lineno, node.col_offset)] = node + + self.generic_visit(node) + + +def _unparse(node): + if isinstance(node, ast.Name): + return node.id + elif isinstance(node, ast.Attribute): + return ''.join((_unparse(node.value), '.', node.attr)) + else: + raise NotImplementedError(ast.dump(node)) + + +def _to_fstring(src, call): + params = {} + for i, arg in enumerate(call.args): + params[str(i)] = _unparse(arg) + for kwd in call.keywords: + params[kwd.arg] = _unparse(kwd.value) + + parts = [] + for i, (s, name, spec, conv) in enumerate(parse_format('f' + src)): + if name is not None: + k, dot, rest = name.partition('.') + name = ''.join((params[k or str(i)], dot, rest)) + parts.append((s, name, spec, conv)) + return unparse_parsed_string(parts) + + +def _fix_fstrings(contents_text): + try: + ast_obj = ast_parse(contents_text) + except SyntaxError: + return contents_text + + visitor = FindSimpleFormats() + visitor.visit(ast_obj) + + tokens = src_to_tokens(contents_text) + for i, token in reversed(tuple(enumerate(tokens))): + node = visitor.found.get(Offset(token.line, token.utf8_byte_offset)) + if node is None: + continue + + paren = i + 3 + if tokens_to_src(tokens[i + 1:paren + 1]) != '.format(': + continue + + # we don't actually care about arg position, so we pass `node` + victims = _victims(tokens, paren, node, gen=False) + end = victims.ends[-1] + # if it spans more than one line, bail + if tokens[end].line != token.line: + continue + + tokens[i] = token._replace(src=_to_fstring(token.src, node)) + del tokens[i + 1:end + 1] + + return tokens_to_src(tokens) + + def fix_file(filename, args): with open(filename, 'rb') as f: contents_bytes = f.read() @@ -657,10 +755,12 @@ def fix_file(filename, args): contents_text = _fix_dictcomps(contents_text) contents_text = _fix_sets(contents_text) contents_text = _fix_format_literals(contents_text) - contents_text = _fix_unicode_literals(contents_text, args.py3_only) + contents_text = _fix_unicode_literals(contents_text, args.py3_plus) contents_text = _fix_long_literals(contents_text) contents_text = _fix_octal_literals(contents_text) contents_text = _fix_percent_format(contents_text) + if args.py36_plus: + contents_text = _fix_fstrings(contents_text) if contents_text != contents_text_orig: print('Rewriting {}'.format(filename)) @@ -674,9 +774,13 @@ def fix_file(filename, args): def main(argv=None): parser = argparse.ArgumentParser() parser.add_argument('filenames', nargs='*') - parser.add_argument('--py3-only', '--py3-plus', action='store_true') + parser.add_argument('--py3-plus', '--py3-only', action='store_true') + parser.add_argument('--py36-plus', action='store_true') args = parser.parse_args(argv) + if args.py36_plus: + args.py3_plus = True + ret = 0 for filename in args.filenames: ret |= fix_file(filename, args)
asottile/pyupgrade
475d34d99844dfc74b62f20309535ba05e876aa5
diff --git a/tests/pyupgrade_test.py b/tests/pyupgrade_test.py index 16353d9..913609d 100644 --- a/tests/pyupgrade_test.py +++ b/tests/pyupgrade_test.py @@ -9,6 +9,7 @@ import pytest from pyupgrade import _fix_dictcomps from pyupgrade import _fix_format_literals +from pyupgrade import _fix_fstrings from pyupgrade import _fix_long_literals from pyupgrade import _fix_octal_literals from pyupgrade import _fix_percent_format @@ -277,7 +278,7 @@ def test_imports_unicode_literals(s, expected): @pytest.mark.parametrize( - ('s', 'py3_only', 'expected'), + ('s', 'py3_plus', 'expected'), ( # Syntax errors are unchanged ('(', False, '('), @@ -297,8 +298,8 @@ def test_imports_unicode_literals(s, expected): ('"""with newline\n"""', True, '"""with newline\n"""'), ), ) -def test_unicode_literals(s, py3_only, expected): - ret = _fix_unicode_literals(s, py3_only=py3_only) +def test_unicode_literals(s, py3_plus, expected): + ret = _fix_unicode_literals(s, py3_plus=py3_plus) assert ret == expected @@ -561,6 +562,44 @@ def test_percent_format_todo(s, expected): assert _fix_percent_format(s) == expected [email protected]( + 's', + ( + # syntax error + '(', + # weird syntax + '"{}" . format(x)', + # spans multiple lines + '"{}".format(\n a,\n)', + # starargs + '"{} {}".format(*a)', '"{foo} {bar}".format(**b)"', + # likely makes the format longer + '"{0} {0}".format(arg)', '"{x} {x}".format(arg)', + '"{x.y} {x.z}".format(arg)', + ), +) +def test_fix_fstrings_noop(s): + assert _fix_fstrings(s) == s + + [email protected]( + ('s', 'expected'), + ( + ('"{} {}".format(a, b)', 'f"{a} {b}"'), + ('"{1} {0}".format(a, b)', 'f"{b} {a}"'), + ('"{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}"'), + ('"hello {}!".format(name)', 'f"hello {name}!"'), + + # TODO: poor man's f-strings? + # '"{foo}".format(**locals())' + ), +) +def test_fix_fstrings(s, expected): + assert _fix_fstrings(s) == expected + + def test_main_trivial(): assert main(()) == 0 @@ -602,10 +641,19 @@ def test_main_non_utf8_bytes(tmpdir, capsys): assert out == '{} is non-utf-8 (not supported)\n'.format(f.strpath) -def test_py3_only_argument_unicode_literals(tmpdir): +def test_py3_plus_argument_unicode_literals(tmpdir): f = tmpdir.join('f.py') f.write('u""') assert main((f.strpath,)) == 0 assert f.read() == 'u""' assert main((f.strpath, '--py3-plus')) == 1 assert f.read() == '""' + + +def test_py36_plus_fstrings(tmpdir): + f = tmpdir.join('f.py') + f.write('"{} {}".format(hello, world)') + assert main((f.strpath,)) == 0 + assert f.read() == '"{} {}".format(hello, world)' + assert main((f.strpath, '--py36-plus')) == 1 + assert f.read() == 'f"{hello} {world}"'
f-string roadmap? You mention that f-string support was planned in the README, and I'm just curious if you had a rough idea of when that might be. Big fan of the project by the way.
0.0
475d34d99844dfc74b62f20309535ba05e876aa5
[ "tests/pyupgrade_test.py::test_roundtrip_text[]", "tests/pyupgrade_test.py::test_roundtrip_text[foo]", "tests/pyupgrade_test.py::test_roundtrip_text[{}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0}]", "tests/pyupgrade_test.py::test_roundtrip_text[{named}]", "tests/pyupgrade_test.py::test_roundtrip_text[{!r}]", "tests/pyupgrade_test.py::test_roundtrip_text[{:>5}]", "tests/pyupgrade_test.py::test_roundtrip_text[{{]", "tests/pyupgrade_test.py::test_roundtrip_text[}}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0!s:15}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/pyupgrade_test.py::test_sets[set()-set()]", "tests/pyupgrade_test.py::test_sets[set((\\n))-set((\\n))]", "tests/pyupgrade_test.py::test_sets[set", "tests/pyupgrade_test.py::test_sets[set(())-set()]", "tests/pyupgrade_test.py::test_sets[set([])-set()]", "tests/pyupgrade_test.py::test_sets[set((", "tests/pyupgrade_test.py::test_sets[set([1,", "tests/pyupgrade_test.py::test_sets[set([(1,", "tests/pyupgrade_test.py::test_sets[set([((1,", "tests/pyupgrade_test.py::test_dictcomps[x", "tests/pyupgrade_test.py::test_dictcomps[dict()-dict()]", "tests/pyupgrade_test.py::test_dictcomps[(-(]", "tests/pyupgrade_test.py::test_dictcomps[dict", "tests/pyupgrade_test.py::test_format_literals['{}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{'.format(1)-'{'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['}'.format(1)-'}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals[x", "tests/pyupgrade_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/pyupgrade_test.py::test_format_literals['{0}'", "tests/pyupgrade_test.py::test_format_literals[print(\\n", "tests/pyupgrade_test.py::test_format_literals['{0:<{1}}'.format(1,", "tests/pyupgrade_test.py::test_imports_unicode_literals[import", "tests/pyupgrade_test.py::test_imports_unicode_literals[from", "tests/pyupgrade_test.py::test_imports_unicode_literals[x", "tests/pyupgrade_test.py::test_imports_unicode_literals[\"\"\"docstring\"\"\"\\nfrom", "tests/pyupgrade_test.py::test_unicode_literals[(-False-(]", "tests/pyupgrade_test.py::test_unicode_literals[u''-False-u'']", "tests/pyupgrade_test.py::test_unicode_literals[u''-True-'']", "tests/pyupgrade_test.py::test_unicode_literals[from", "tests/pyupgrade_test.py::test_unicode_literals[\"\"\"with", "tests/pyupgrade_test.py::test_noop_octal_literals[0-0]", "tests/pyupgrade_test.py::test_noop_octal_literals[00-00]", "tests/pyupgrade_test.py::test_noop_octal_literals[1-1]", "tests/pyupgrade_test.py::test_noop_octal_literals[12345-12345]", "tests/pyupgrade_test.py::test_noop_octal_literals[1.2345-1.2345]", "tests/pyupgrade_test.py::test_parse_percent_format[\"\"-expected0]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%%\"-expected1]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s\"-expected2]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(hi)s\"-expected4]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%()s\"-expected5]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%#o\"-expected6]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%", "tests/pyupgrade_test.py::test_parse_percent_format[\"%5d\"-expected8]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%*d\"-expected9]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.f\"-expected10]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.5f\"-expected11]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.*f\"-expected12]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%ld\"-expected13]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(complete)#4.4f\"-expected14]", "tests/pyupgrade_test.py::test_percent_to_format[%s-{}]", "tests/pyupgrade_test.py::test_percent_to_format[%%%s-%{}]", "tests/pyupgrade_test.py::test_percent_to_format[%(foo)s-{foo}]", "tests/pyupgrade_test.py::test_percent_to_format[%2f-{:2f}]", "tests/pyupgrade_test.py::test_percent_to_format[%r-{!r}]", "tests/pyupgrade_test.py::test_percent_to_format[%a-{!a}]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[-]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[", "tests/pyupgrade_test.py::test_simplify_conversion_flag[#0-", "tests/pyupgrade_test.py::test_simplify_conversion_flag[--<]", "tests/pyupgrade_test.py::test_percent_format_noop[\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[b\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%d\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%i\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%u\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%c\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%#o\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%()s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%4%\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2r\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2a\"", "tests/pyupgrade_test.py::test_percent_format_noop[i", "tests/pyupgrade_test.py::test_percent_format[\"trivial\"", "tests/pyupgrade_test.py::test_percent_format[\"%s%%", "tests/pyupgrade_test.py::test_percent_format[\"%3f\"", "tests/pyupgrade_test.py::test_percent_format[\"%-5s\"", "tests/pyupgrade_test.py::test_percent_format[\"brace", "tests/pyupgrade_test.py::test_fix_fstrings_noop[(]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\"", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{foo}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{0}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{1}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{.x}", "tests/pyupgrade_test.py::test_fix_fstrings[\"hello", "tests/pyupgrade_test.py::test_main_trivial", "tests/pyupgrade_test.py::test_main_noop", "tests/pyupgrade_test.py::test_main_syntax_error", "tests/pyupgrade_test.py::test_main_non_utf8_bytes", "tests/pyupgrade_test.py::test_py3_plus_argument_unicode_literals", "tests/pyupgrade_test.py::test_py36_plus_fstrings" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-06-06 06:37:51+00:00
mit
1,170
asottile__pyupgrade-360
diff --git a/pyupgrade.py b/pyupgrade.py index 79f2bb2..8c9f28c 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -57,6 +57,13 @@ _stdlib_parse_format = string.Formatter().parse _KEYWORDS = frozenset(keyword.kwlist) +_EXPR_NEEDS_PARENS: Tuple[Type[ast.expr], ...] = ( + ast.Await, ast.BinOp, ast.BoolOp, ast.Compare, ast.GeneratorExp, ast.IfExp, + ast.Lambda, ast.UnaryOp, +) +if sys.version_info >= (3, 8): # pragma: no cover (py38+) + _EXPR_NEEDS_PARENS += (ast.NamedExpr,) + def parse_format(s: str) -> Tuple[DotFormatPart, ...]: """Makes the empty string not a special case. In the stdlib, there's @@ -1103,7 +1110,6 @@ SIX_CALLS = { 'u': '{args[0]}', 'byte2int': '{args[0]}[0]', 'indexbytes': '{args[0]}[{rest}]', - 'int2byte': 'bytes(({args[0]},))', 'iteritems': '{args[0]}.items()', 'iterkeys': '{args[0]}.keys()', 'itervalues': '{args[0]}.values()', @@ -1122,6 +1128,7 @@ SIX_CALLS = { 'assertRaisesRegex': '{args[0]}.assertRaisesRegex({rest})', 'assertRegex': '{args[0]}.assertRegex({rest})', } +SIX_INT2BYTE_TMPL = 'bytes(({args[0]},))' SIX_B_TMPL = 'b{args[0]}' WITH_METACLASS_NO_BASES_TMPL = 'metaclass={args[0]}' WITH_METACLASS_BASES_TMPL = '{rest}, metaclass={args[0]}' @@ -1244,6 +1251,7 @@ class FindPy3Plus(ast.NodeVisitor): self.six_add_metaclass: Set[Offset] = set() self.six_b: Set[Offset] = set() self.six_calls: Dict[Offset, ast.Call] = {} + self.six_calls_int2byte: Set[Offset] = set() self.six_iter: Dict[Offset, ast.Call] = {} self._previous_node: Optional[ast.AST] = None self.six_raise_from: Set[Offset] = set() @@ -1534,8 +1542,18 @@ class FindPy3Plus(ast.NodeVisitor): self.six_type_ctx[_ast_to_offset(node.args[1])] = arg elif self._is_six(node.func, ('b', 'ensure_binary')): self.six_b.add(_ast_to_offset(node)) - elif self._is_six(node.func, SIX_CALLS) and not _starargs(node): + elif ( + self._is_six(node.func, SIX_CALLS) and + node.args and + not _starargs(node) + ): self.six_calls[_ast_to_offset(node)] = node + elif ( + self._is_six(node.func, ('int2byte',)) and + node.args and + not _starargs(node) + ): + self.six_calls_int2byte.add(_ast_to_offset(node)) elif ( isinstance(node.func, ast.Name) and node.func.id == 'next' and @@ -2006,8 +2024,12 @@ def _replace_call( end: int, args: List[Tuple[int, int]], tmpl: str, + *, + parens: Sequence[int] = (), ) -> None: arg_strs = [_arg_str(tokens, *arg) for arg in args] + for paren in parens: + arg_strs[paren] = f'({arg_strs[paren]})' start_rest = args[0][1] + 1 while ( @@ -2062,6 +2084,7 @@ def _fix_py3_plus( visitor.six_add_metaclass, visitor.six_b, visitor.six_calls, + visitor.six_calls_int2byte, visitor.six_iter, visitor.six_raise_from, visitor.six_reraise, @@ -2167,7 +2190,14 @@ def _fix_py3_plus( call = visitor.six_calls[token.offset] assert isinstance(call.func, (ast.Name, ast.Attribute)) template = _get_tmpl(SIX_CALLS, call.func) - _replace_call(tokens, i, end, func_args, template) + if isinstance(call.args[0], _EXPR_NEEDS_PARENS): + _replace_call(tokens, i, end, func_args, template, parens=(0,)) + else: + _replace_call(tokens, i, end, func_args, template) + elif token.offset in visitor.six_calls_int2byte: + j = _find_open_paren(tokens, i) + func_args, end = _parse_call_args(tokens, j) + _replace_call(tokens, i, end, func_args, SIX_INT2BYTE_TMPL) elif token.offset in visitor.six_raise_from: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j)
asottile/pyupgrade
20d5c9ef3ca920c6332f2e0605fd0013225640f4
diff --git a/tests/six_test.py b/tests/six_test.py index 9ddffd7..bdcb980 100644 --- a/tests/six_test.py +++ b/tests/six_test.py @@ -1,3 +1,5 @@ +import sys + import pytest from pyupgrade import _fix_py3_plus @@ -42,6 +44,7 @@ from pyupgrade import _fix_py3_plus id='relative import might not be six', ), ('traceback.format_exc(*sys.exc_info())'), + pytest.param('six.iteritems()', id='wrong argument count'), ), ) def test_fix_six_noop(s): @@ -382,12 +385,76 @@ def test_fix_six_noop(s): 'print(next(iter({1:2}.values())))\n', id='six.itervalues inside next(...)', ), + pytest.param( + 'for _ in six.itervalues({} or y): pass', + 'for _ in ({} or y).values(): pass', + id='needs parenthesizing for BoolOp', + ), + pytest.param( + 'for _ in six.itervalues({} | y): pass', + 'for _ in ({} | y).values(): pass', + id='needs parenthesizing for BinOp', + ), + pytest.param( + 'six.int2byte(x | y)', + 'bytes((x | y,))', + id='no parenthesize for int2byte BinOP', + ), + pytest.param( + 'six.iteritems(+weird_dct)', + '(+weird_dct).items()', + id='needs parenthesizing for UnaryOp', + ), + pytest.param( + 'x = six.get_method_function(lambda: x)', + 'x = (lambda: x).__func__', + id='needs parenthesizing for Lambda', + ), + pytest.param( + 'for _ in six.itervalues(x if 1 else y): pass', + 'for _ in (x if 1 else y).values(): pass', + id='needs parenthesizing for IfExp', + ), + # this one is bogus / impossible, but parenthesize it anyway + pytest.param( + 'six.itervalues(x for x in y)', + '(x for x in y).values()', + id='needs parentehsizing for GeneratorExp', + ), + pytest.param( + 'async def f():\n' + ' return six.iteritems(await y)\n', + 'async def f():\n' + ' return (await y).items()\n', + id='needs parenthesizing for Await', + ), + # this one is bogus / impossible, but parenthesize it anyway + pytest.param( + 'six.itervalues(x < y)', + '(x < y).values()', + id='needs parentehsizing for Compare', + ), ), ) def test_fix_six(s, expected): assert _fix_py3_plus(s, (3,)) == expected [email protected](sys.version_info < (3, 8), reason='walrus') [email protected]( + ('s', 'expected'), + ( + pytest.param( + 'for _ in six.itervalues(x := y): pass', + 'for _ in (x := y).values(): pass', + id='needs parenthesizing for NamedExpr', + ), + ), +) +def test_fix_six_py38_plus(s, expected): + assert _fix_py3_plus(s, (3,)) == expected + + @pytest.mark.parametrize( ('s', 'expected'), (
Six call removal breaks logic inside call before: ``` import six result = {} for leg in six.itervalues(result.get('something') or {}): pass ``` after: ``` import six result = {} for leg in result.get('something') or {}.values(): pass ``` should: ``` import six result = {} for leg in (result.get('something') or {}).values(): pass
0.0
20d5c9ef3ca920c6332f2e0605fd0013225640f4
[ "tests/six_test.py::test_fix_six_noop[wrong", "tests/six_test.py::test_fix_six[needs", "tests/six_test.py::test_fix_six_py38_plus[needs" ]
[ "tests/six_test.py::test_fix_six_noop[x", "tests/six_test.py::test_fix_six_noop[from", "tests/six_test.py::test_fix_six_noop[@mydec\\nclass", "tests/six_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/six_test.py::test_fix_six_noop[print(six.b(\"\\xa3\"))]", "tests/six_test.py::test_fix_six_noop[print(six.b(", "tests/six_test.py::test_fix_six_noop[class", "tests/six_test.py::test_fix_six_noop[six.reraise(*err)]", "tests/six_test.py::test_fix_six_noop[six.b(*a)]", "tests/six_test.py::test_fix_six_noop[six.u(*a)]", "tests/six_test.py::test_fix_six_noop[@six.add_metaclass(*a)\\nclass", "tests/six_test.py::test_fix_six_noop[(\\n", "tests/six_test.py::test_fix_six_noop[next()]", "tests/six_test.py::test_fix_six_noop[relative", "tests/six_test.py::test_fix_six_noop[traceback.format_exc(*sys.exc_info())]", "tests/six_test.py::test_fix_six[isinstance(s,", "tests/six_test.py::test_fix_six[weird", "tests/six_test.py::test_fix_six[issubclass(tp,", "tests/six_test.py::test_fix_six[STRING_TYPES", "tests/six_test.py::test_fix_six[from", "tests/six_test.py::test_fix_six[six.b(\"123\")-b\"123\"]", "tests/six_test.py::test_fix_six[six.b(r\"123\")-br\"123\"]", "tests/six_test.py::test_fix_six[six.b(\"\\\\x12\\\\xef\")-b\"\\\\x12\\\\xef\"]", "tests/six_test.py::test_fix_six[six.ensure_binary(\"foo\")-b\"foo\"]", "tests/six_test.py::test_fix_six[six.byte2int(b\"f\")-b\"f\"[0]]", "tests/six_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/six_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/six_test.py::test_fix_six[six.get_unbound_function(meth)\\n-meth\\n]", "tests/six_test.py::test_fix_six[six.indexbytes(bs,", "tests/six_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/six_test.py::test_fix_six[six.raise_from(exc,", "tests/six_test.py::test_fix_six[six.reraise(tp,", "tests/six_test.py::test_fix_six[six.reraise(*sys.exc_info())\\n-raise\\n]", "tests/six_test.py::test_fix_six[six.reraise(\\n", "tests/six_test.py::test_fix_six[class", "tests/six_test.py::test_fix_six[elide", "tests/six_test.py::test_fix_six[basic", "tests/six_test.py::test_fix_six[add_metaclass,", "tests/six_test.py::test_fix_six[six.itervalues]", "tests/six_test.py::test_fix_six[six.itervalues", "tests/six_test.py::test_fix_six[no", "tests/six_test.py::test_fix_base_classes[import", "tests/six_test.py::test_fix_base_classes[from", "tests/six_test.py::test_fix_base_classes[class" ]
{ "failed_lite_validators": [ "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-11-10 23:50:29+00:00
mit
1,171
asottile__pyupgrade-380
diff --git a/pyupgrade.py b/pyupgrade.py index 796064f..254c9ff 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -690,6 +690,7 @@ def _build_import_removals() -> Dict[MinVersion, Dict[str, Tuple[str, ...]]]: ((3, 6), ()), ((3, 7), ('generator_stop',)), ((3, 8), ()), + ((3, 9), ()), ) prev: Tuple[str, ...] = ()
asottile/pyupgrade
d9e1f0886099fdb2d11e11f3d4fc1f4f11ef5fdf
diff --git a/tests/main_test.py b/tests/main_test.py index cd992d1..997f682 100644 --- a/tests/main_test.py +++ b/tests/main_test.py @@ -19,6 +19,7 @@ def test_main_trivial(): ('--py36-plus',), ('--py37-plus',), ('--py38-plus',), + ('--py39-plus',), ), ) def test_main_noop(tmpdir, args):
Fails to run on python3.9 This is because there is no import removals defined for https://github.com/asottile/pyupgrade/blob/5e32666723/pyupgrade.py#L680-L693, and https://github.com/asottile/pyupgrade/blob/5e32666723/pyupgrade.py#L732 lookup fails. Perhaps instead of ``[]`` it should use ``.get``? ``` venv/bin/pyupgrade --py39-plus src/**.py Traceback (most recent call last): File "/Users/bgabor8/git/a/venv/bin/pyupgrade", line 8, in <module> sys.exit(main()) File "/Users/bgabor8/git/a/venv/lib/python3.9/site-packages/pyupgrade.py", line 2823, in main ret |= _fix_file(filename, args) File "/Users/bgabor8/git/a/venv/lib/python3.9/site-packages/pyupgrade.py", line 2770, in _fix_file contents_text = _fix_tokens(contents_text, min_version=args.min_version) File "/Users/bgabor8/git/a/venv/lib/python3.9/site-packages/pyupgrade.py", line 808, in _fix_tokens _fix_import_removals(tokens, i, min_version) File "/Users/bgabor8/git/a/venv/lib/python3.9/site-packages/pyupgrade.py", line 732, in _fix_import_removals if modname not in IMPORT_REMOVALS[min_version]: KeyError: (3, 9) ```
0.0
d9e1f0886099fdb2d11e11f3d4fc1f4f11ef5fdf
[ "tests/main_test.py::test_main_noop[args5]" ]
[ "tests/main_test.py::test_main_trivial", "tests/main_test.py::test_main_noop[args0]", "tests/main_test.py::test_main_noop[args1]", "tests/main_test.py::test_main_noop[args2]", "tests/main_test.py::test_main_noop[args3]", "tests/main_test.py::test_main_noop[args4]", "tests/main_test.py::test_main_changes_a_file", "tests/main_test.py::test_main_keeps_line_endings", "tests/main_test.py::test_main_syntax_error", "tests/main_test.py::test_main_non_utf8_bytes", "tests/main_test.py::test_main_py27_syntaxerror_coding", "tests/main_test.py::test_keep_percent_format", "tests/main_test.py::test_py3_plus_argument_unicode_literals", "tests/main_test.py::test_py3_plus_super", "tests/main_test.py::test_py3_plus_new_style_classes", "tests/main_test.py::test_py3_plus_oserror", "tests/main_test.py::test_py36_plus_fstrings", "tests/main_test.py::test_py37_plus_removes_annotations", "tests/main_test.py::test_py38_plus_removes_no_arg_decorators", "tests/main_test.py::test_noop_token_error", "tests/main_test.py::test_main_exit_zero_even_if_changed", "tests/main_test.py::test_main_stdin_no_changes", "tests/main_test.py::test_main_stdin_with_changes" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2021-01-29 14:45:25+00:00
mit
1,172
asottile__pyupgrade-385
diff --git a/pyupgrade/_main.py b/pyupgrade/_main.py index 5e1a424..bf75a62 100644 --- a/pyupgrade/_main.py +++ b/pyupgrade/_main.py @@ -390,6 +390,7 @@ def _build_import_removals() -> Dict[Version, Dict[str, Tuple[str, ...]]]: ((3, 7), ('generator_stop',)), ((3, 8), ()), ((3, 9), ()), + ((3, 10), ()), ) prev: Tuple[str, ...] = () @@ -874,6 +875,10 @@ def main(argv: Optional[Sequence[str]] = None) -> int: '--py39-plus', action='store_const', dest='min_version', const=(3, 9), ) + parser.add_argument( + '--py310-plus', + action='store_const', dest='min_version', const=(3, 10), + ) args = parser.parse_args(argv) ret = 0 diff --git a/pyupgrade/_plugins/typing_pep604.py b/pyupgrade/_plugins/typing_pep604.py new file mode 100644 index 0000000..6dfc573 --- /dev/null +++ b/pyupgrade/_plugins/typing_pep604.py @@ -0,0 +1,126 @@ +import ast +import functools +import sys +from typing import Iterable +from typing import List +from typing import Tuple + +from tokenize_rt import Offset +from tokenize_rt import Token + +from pyupgrade._ast_helpers import ast_to_offset +from pyupgrade._ast_helpers import is_name_attr +from pyupgrade._data import register +from pyupgrade._data import State +from pyupgrade._data import TokenFunc +from pyupgrade._token_helpers import CLOSING +from pyupgrade._token_helpers import find_closing_bracket +from pyupgrade._token_helpers import find_token +from pyupgrade._token_helpers import OPENING + + +def _fix_optional(i: int, tokens: List[Token]) -> None: + j = find_token(tokens, i, '[') + k = find_closing_bracket(tokens, j) + if tokens[j].line == tokens[k].line: + tokens[k] = Token('CODE', ' | None') + del tokens[i:j + 1] + else: + tokens[j] = tokens[j]._replace(src='(') + tokens[k] = tokens[k]._replace(src=')') + tokens[i:j] = [Token('CODE', 'None | ')] + + +def _fix_union( + i: int, + tokens: List[Token], + *, + arg: ast.expr, + arg_count: int, +) -> None: + arg_offset = ast_to_offset(arg) + j = find_token(tokens, i, '[') + to_delete = [] + commas: List[int] = [] + + arg_depth = -1 + depth = 1 + k = j + 1 + while depth: + if tokens[k].src in OPENING: + if arg_depth == -1: + to_delete.append(k) + depth += 1 + elif tokens[k].src in CLOSING: + depth -= 1 + if 0 < depth < arg_depth: + to_delete.append(k) + elif tokens[k].offset == arg_offset: + arg_depth = depth + elif depth == arg_depth and tokens[k].src == ',': + if len(commas) >= arg_count - 1: + to_delete.append(k) + else: + commas.append(k) + + k += 1 + k -= 1 + + if tokens[j].line == tokens[k].line: + del tokens[k] + for comma in commas: + tokens[comma] = Token('CODE', ' |') + for paren in reversed(to_delete): + del tokens[paren] + del tokens[i:j + 1] + else: + tokens[j] = tokens[j]._replace(src='(') + tokens[k] = tokens[k]._replace(src=')') + + for comma in commas: + tokens[comma] = Token('CODE', ' |') + for paren in reversed(to_delete): + del tokens[paren] + del tokens[i:j] + + +def _supported_version(state: State) -> bool: + return ( + state.in_annotation and ( + state.settings.min_version >= (3, 10) or + 'annotations' in state.from_imports['__future__'] + ) + ) + + +@register(ast.Subscript) +def visit_Subscript( + state: State, + node: ast.Subscript, + parent: ast.AST, +) -> Iterable[Tuple[Offset, TokenFunc]]: + if not _supported_version(state): + return + + if is_name_attr(node.value, state.from_imports, 'typing', ('Optional',)): + yield ast_to_offset(node), _fix_optional + elif is_name_attr(node.value, state.from_imports, 'typing', ('Union',)): + if sys.version_info >= (3, 9): # pragma: no cover (py39+) + node_slice: ast.expr = node.slice + elif isinstance(node.slice, ast.Index): # pragma: no cover (<py39) + node_slice = node.slice.value + else: # pragma: no cover (<py39) + return # unexpected slice type + + if isinstance(node_slice, ast.Tuple): + if node_slice.elts: + arg = node_slice.elts[0] + arg_count = len(node_slice.elts) + else: + return # empty Union + else: + arg = node_slice + arg_count = 1 + + func = functools.partial(_fix_union, arg=arg, arg_count=arg_count) + yield ast_to_offset(node), func diff --git a/pyupgrade/_token_helpers.py b/pyupgrade/_token_helpers.py index 3aa9e05..0ab815c 100644 --- a/pyupgrade/_token_helpers.py +++ b/pyupgrade/_token_helpers.py @@ -425,7 +425,8 @@ def find_and_replace_call( def replace_name(i: int, tokens: List[Token], *, name: str, new: str) -> None: - new_token = Token('CODE', new) + # preserve token offset in case we need to match it later + new_token = tokens[i]._replace(name='CODE', src=new) j = i while tokens[j].src != name: # timid: if we see a parenthesis here, skip it
asottile/pyupgrade
5e4e0ddfdc0e24443e1d12111c57127c3caf90c1
diff --git a/tests/features/typing_pep604_test.py b/tests/features/typing_pep604_test.py new file mode 100644 index 0000000..78d4ea3 --- /dev/null +++ b/tests/features/typing_pep604_test.py @@ -0,0 +1,191 @@ +import pytest + +from pyupgrade._data import Settings +from pyupgrade._main import _fix_plugins + + [email protected]( + ('s', 'version'), + ( + pytest.param( + 'from typing import Union\n' + 'x: Union[int, str]\n', + (3, 9), + id='<3.10 Union', + ), + pytest.param( + 'from typing import Optional\n' + 'x: Optional[str]\n', + (3, 9), + id='<3.10 Optional', + ), + pytest.param( + 'from __future__ import annotations\n' + 'from typing import Union\n' + 'SomeAlias = Union[int, str]\n', + (3, 9), + id='<3.9 not in a type annotation context', + ), + # https://github.com/python/mypy/issues/9945 + pytest.param( + 'from __future__ import annotations\n' + 'from typing import Union\n' + 'SomeAlias = Union[int, str]\n', + (3, 10), + id='3.10+ not in a type annotation context', + ), + # https://github.com/python/mypy/issues/9998 + pytest.param( + 'from typing import Union\n' + 'def f() -> Union[()]: ...\n', + (3, 10), + id='3.10+ empty Union', + ), + ), +) +def test_fix_pep604_types_noop(s, version): + assert _fix_plugins(s, settings=Settings(min_version=version)) == s + + [email protected]( + ('s', 'expected'), + ( + pytest.param( + 'from typing import Union\n' + 'x: Union[int, str]\n', + + 'from typing import Union\n' + 'x: int | str\n', + + id='Union rewrite', + ), + pytest.param( + 'x: typing.Union[int]\n', + + 'x: int\n', + + id='Union of only one value', + ), + pytest.param( + 'x: typing.Union[Foo[str, int], str]\n', + + 'x: Foo[str, int] | str\n', + + id='Union containing a value with brackets', + ), + pytest.param( + 'x: typing.Union[typing.List[str], str]\n', + + 'x: list[str] | str\n', + + id='Union containing pep585 rewritten type', + ), + pytest.param( + 'x: typing.Union[int, str,]\n', + + 'x: int | str\n', + + id='Union trailing comma', + ), + pytest.param( + 'x: typing.Union[(int, str)]\n', + + 'x: int | str\n', + + id='Union, parenthesized tuple', + ), + pytest.param( + 'x: typing.Union[\n' + ' int,\n' + ' str\n' + ']\n', + + 'x: (\n' + ' int |\n' + ' str\n' + ')\n', + + id='Union multiple lines', + ), + pytest.param( + 'x: typing.Union[\n' + ' int,\n' + ' str,\n' + ']\n', + + 'x: (\n' + ' int |\n' + ' str\n' + ')\n', + + id='Union multiple lines with trailing commas', + ), + pytest.param( + 'from typing import Optional\n' + 'x: Optional[str]\n', + + 'from typing import Optional\n' + 'x: str | None\n', + + id='Optional rewrite', + ), + pytest.param( + 'x: typing.Optional[\n' + ' ComplicatedLongType[int]\n' + ']\n', + + 'x: None | (\n' + ' ComplicatedLongType[int]\n' + ')\n', + + id='Optional rewrite multi-line', + ), + ), +) +def test_fix_pep604_types(s, expected): + assert _fix_plugins(s, settings=Settings(min_version=(3, 10))) == expected + + [email protected]( + ('s', 'expected'), + ( + pytest.param( + 'from __future__ import annotations\n' + 'from typing import Union\n' + 'x: Union[int, str]\n', + + 'from __future__ import annotations\n' + 'from typing import Union\n' + 'x: int | str\n', + + id='variable annotations', + ), + pytest.param( + 'from __future__ import annotations\n' + 'from typing import Union\n' + 'def f(x: Union[int, str]) -> None: ...\n', + + 'from __future__ import annotations\n' + 'from typing import Union\n' + 'def f(x: int | str) -> None: ...\n', + + id='argument annotations', + ), + pytest.param( + 'from __future__ import annotations\n' + 'from typing import Union\n' + 'def f() -> Union[int, str]: ...\n', + + 'from __future__ import annotations\n' + 'from typing import Union\n' + 'def f() -> int | str: ...\n', + + id='return annotations', + ), + ), +) +def test_fix_generic_types_future_annotations(s, expected): + assert _fix_plugins(s, settings=Settings(min_version=(3,))) == expected + + +# TODO: test multi-line as well diff --git a/tests/main_test.py b/tests/main_test.py index 1cc939c..da74a0c 100644 --- a/tests/main_test.py +++ b/tests/main_test.py @@ -20,6 +20,7 @@ def test_main_trivial(): ('--py37-plus',), ('--py38-plus',), ('--py39-plus',), + ('--py310-plus',), ), ) def test_main_noop(tmpdir, args):
PEP 604 rewrites Now that mypy supports this, we should as well notably it is these two replacements: `Union[X, Y]` => `X | Y` `Optional[X]` => `X | None`
0.0
5e4e0ddfdc0e24443e1d12111c57127c3caf90c1
[ "tests/features/typing_pep604_test.py::test_fix_pep604_types[Union", "tests/features/typing_pep604_test.py::test_fix_pep604_types[Union,", "tests/features/typing_pep604_test.py::test_fix_pep604_types[Optional", "tests/features/typing_pep604_test.py::test_fix_generic_types_future_annotations[variable", "tests/features/typing_pep604_test.py::test_fix_generic_types_future_annotations[argument", "tests/features/typing_pep604_test.py::test_fix_generic_types_future_annotations[return", "tests/main_test.py::test_main_noop[args6]" ]
[ "tests/features/typing_pep604_test.py::test_fix_pep604_types_noop[<3.10", "tests/features/typing_pep604_test.py::test_fix_pep604_types_noop[<3.9", "tests/features/typing_pep604_test.py::test_fix_pep604_types_noop[3.10+", "tests/main_test.py::test_main_trivial", "tests/main_test.py::test_main_noop[args0]", "tests/main_test.py::test_main_noop[args1]", "tests/main_test.py::test_main_noop[args2]", "tests/main_test.py::test_main_noop[args3]", "tests/main_test.py::test_main_noop[args4]", "tests/main_test.py::test_main_noop[args5]", "tests/main_test.py::test_main_changes_a_file", "tests/main_test.py::test_main_keeps_line_endings", "tests/main_test.py::test_main_syntax_error", "tests/main_test.py::test_main_non_utf8_bytes", "tests/main_test.py::test_main_py27_syntaxerror_coding", "tests/main_test.py::test_keep_percent_format", "tests/main_test.py::test_py3_plus_argument_unicode_literals", "tests/main_test.py::test_py3_plus_super", "tests/main_test.py::test_py3_plus_new_style_classes", "tests/main_test.py::test_py3_plus_oserror", "tests/main_test.py::test_py36_plus_fstrings", "tests/main_test.py::test_py37_plus_removes_annotations", "tests/main_test.py::test_py38_plus_removes_no_arg_decorators", "tests/main_test.py::test_noop_token_error", "tests/main_test.py::test_main_exit_zero_even_if_changed", "tests/main_test.py::test_main_stdin_no_changes", "tests/main_test.py::test_main_stdin_with_changes" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-01-31 01:14:40+00:00
mit
1,173
asottile__pyupgrade-409
diff --git a/pyupgrade/_plugins/typing_pep604.py b/pyupgrade/_plugins/typing_pep604.py index b5e22e1..6ffcc20 100644 --- a/pyupgrade/_plugins/typing_pep604.py +++ b/pyupgrade/_plugins/typing_pep604.py @@ -5,6 +5,7 @@ from typing import Iterable from typing import List from typing import Tuple +from tokenize_rt import NON_CODING_TOKENS from tokenize_rt import Offset from tokenize_rt import Token @@ -35,40 +36,70 @@ def _fix_union( i: int, tokens: List[Token], *, - arg: ast.expr, arg_count: int, ) -> None: - arg_offset = ast_to_offset(arg) - j = find_token(tokens, i, '[') - to_delete = [] - commas: List[int] = [] - - arg_depth = -1 depth = 1 + parens_done = [] + open_parens = [] + commas = [] + coding_depth = None + + j = find_token(tokens, i, '[') k = j + 1 while depth: + # it's possible our first coding token is a close paren + # so make sure this is separate from the if chain below + if ( + tokens[k].name not in NON_CODING_TOKENS and + tokens[k].src != '(' and + coding_depth is None + ): + if tokens[k].src == ')': # the coding token was an empty tuple + coding_depth = depth - 1 + else: + coding_depth = depth + if tokens[k].src in OPENING: - if arg_depth == -1: - to_delete.append(k) + if tokens[k].src == '(': + open_parens.append((depth, k)) + depth += 1 elif tokens[k].src in CLOSING: + if tokens[k].src == ')': + paren_depth, open_paren = open_parens.pop() + parens_done.append((paren_depth, (open_paren, k))) + depth -= 1 - if 0 < depth < arg_depth: - to_delete.append(k) - elif tokens[k].offset == arg_offset: - arg_depth = depth - elif depth == arg_depth and tokens[k].src == ',': - if len(commas) >= arg_count - 1: - to_delete.append(k) - else: - commas.append(k) + elif tokens[k].src == ',': + commas.append((depth, k)) k += 1 k -= 1 + assert coding_depth is not None + assert not open_parens, open_parens + comma_depth = min((depth for depth, _ in commas), default=sys.maxsize) + min_depth = min(comma_depth, coding_depth) + + to_delete = [ + paren + for depth, positions in parens_done + if depth < min_depth + for paren in positions + ] + + if comma_depth <= coding_depth: + comma_positions = [k for depth, k in commas if depth == comma_depth] + if len(comma_positions) == arg_count: + to_delete.append(comma_positions.pop()) + else: + comma_positions = [] + + to_delete.sort() + if tokens[j].line == tokens[k].line: del tokens[k] - for comma in commas: + for comma in comma_positions: tokens[comma] = Token('CODE', ' |') for paren in reversed(to_delete): del tokens[paren] @@ -77,7 +108,7 @@ def _fix_union( tokens[j] = tokens[j]._replace(src='(') tokens[k] = tokens[k]._replace(src=')') - for comma in commas: + for comma in comma_positions: tokens[comma] = Token('CODE', ' |') for paren in reversed(to_delete): del tokens[paren] @@ -116,13 +147,11 @@ def visit_Subscript( if isinstance(node_slice, ast.Tuple): if node_slice.elts: - arg = node_slice.elts[0] arg_count = len(node_slice.elts) else: return # empty Union else: - arg = node_slice arg_count = 1 - func = functools.partial(_fix_union, arg=arg, arg_count=arg_count) + func = functools.partial(_fix_union, arg_count=arg_count) yield ast_to_offset(node), func
asottile/pyupgrade
7849a12f40d0fad949159b1e76e324cc305f80dc
diff --git a/tests/_plugins/__init__.py b/tests/_plugins/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/_plugins/typing_pep604_test.py b/tests/_plugins/typing_pep604_test.py new file mode 100644 index 0000000..ca786b7 --- /dev/null +++ b/tests/_plugins/typing_pep604_test.py @@ -0,0 +1,28 @@ +import pytest +from tokenize_rt import src_to_tokens +from tokenize_rt import tokens_to_src + +from pyupgrade._plugins.typing_pep604 import _fix_union + + [email protected]( + ('s', 'arg_count', 'expected'), + ( + ('Union[a, b]', 2, 'a | b'), + ('Union[(a, b)]', 2, 'a | b'), + ('Union[(a,)]', 1, 'a'), + ('Union[(((a, b)))]', 2, 'a | b'), + pytest.param('Union[((a), b)]', 2, '(a) | b', id='wat'), + ('Union[(((a,), b))]', 2, '(a,) | b'), + ('Union[((a,), (a, b))]', 2, '(a,) | (a, b)'), + ('Union[((a))]', 1, 'a'), + ('Union[a()]', 1, 'a()'), + ('Union[a(b, c)]', 1, 'a(b, c)'), + ('Union[(a())]', 1, 'a()'), + ('Union[(())]', 1, '()'), + ), +) +def test_fix_union_edge_cases(s, arg_count, expected): + tokens = src_to_tokens(s) + _fix_union(0, tokens, arg_count=arg_count) + assert tokens_to_src(tokens) == expected diff --git a/tests/features/typing_pep604_test.py b/tests/features/typing_pep604_test.py index 64c8f5d..503bc2a 100644 --- a/tests/features/typing_pep604_test.py +++ b/tests/features/typing_pep604_test.py @@ -165,6 +165,15 @@ def f(x: int | str) -> None: ... id='Optional rewrite multi-line', ), + pytest.param( + 'from typing import Union, Sequence\n' + 'def f(x: Union[Union[A, B], Sequence[Union[C, D]]]): pass\n', + + 'from typing import Union, Sequence\n' + 'def f(x: A | B | Sequence[C | D]): pass\n', + + id='nested unions', + ), ), ) def test_fix_pep604_types(s, expected):
IndentationError: unindent does not match any outer indentation level To reproduce: ```python # t.py from __future__ import annotations from typing import ( Sequence, Union, ) def sort_index( self, ascending: Union[Union[bool, int], Sequence[Union[bool, int]]], ): indexer = get_indexer_indexer( target, level, ascending, kind, na_position, sort_remaining, key ) ``` Then: ```console $ pyupgrade t.py Traceback (most recent call last): File "/home/marco/tmp/venv/bin/pyupgrade", line 8, in <module> sys.exit(main()) File "/home/marco/tmp/venv/lib/python3.8/site-packages/pyupgrade/_main.py", line 889, in main ret |= _fix_file(filename, args) File "/home/marco/tmp/venv/lib/python3.8/site-packages/pyupgrade/_main.py", line 837, in _fix_file contents_text = _fix_tokens(contents_text, min_version=args.min_version) File "/home/marco/tmp/venv/lib/python3.8/site-packages/pyupgrade/_main.py", line 481, in _fix_tokens tokens = src_to_tokens(contents_text) File "/home/marco/tmp/venv/lib/python3.8/site-packages/tokenize_rt.py", line 68, in src_to_tokens for ( File "/usr/lib/python3.8/tokenize.py", line 512, in _tokenize raise IndentationError( File "<tokenize>", line 15 ) ^ IndentationError: unindent does not match any outer indentation level ``` Removing either the `indexer = ` line, or the `ascending: ` annotation, makes `pyupgrade` pass. Keeping them both in, it fails. Spotted in pandas, when commit 78371ccbd8744326e8535ac8bb9a661b073dfd88 meant that `pyupgrade` could no longer be run on `pandas/core/generic.py` without `--keep-runtime-typing` ---- version info: ```console $ pip freeze | grep pyupgrade pyupgrade==2.10.0 $ pip freeze | grep tokenize-rt tokenize-rt==4.1.0 $ python --version Python 3.8.5 ```
0.0
7849a12f40d0fad949159b1e76e324cc305f80dc
[ "tests/_plugins/typing_pep604_test.py::test_fix_union_edge_cases[Union[a,", "tests/_plugins/typing_pep604_test.py::test_fix_union_edge_cases[Union[(a,", "tests/_plugins/typing_pep604_test.py::test_fix_union_edge_cases[Union[(a,)]-1-a]", "tests/_plugins/typing_pep604_test.py::test_fix_union_edge_cases[Union[(((a,", "tests/_plugins/typing_pep604_test.py::test_fix_union_edge_cases[wat]", "tests/_plugins/typing_pep604_test.py::test_fix_union_edge_cases[Union[(((a,),", "tests/_plugins/typing_pep604_test.py::test_fix_union_edge_cases[Union[((a,),", "tests/_plugins/typing_pep604_test.py::test_fix_union_edge_cases[Union[((a))]-1-a]", "tests/_plugins/typing_pep604_test.py::test_fix_union_edge_cases[Union[a()]-1-a()]", "tests/_plugins/typing_pep604_test.py::test_fix_union_edge_cases[Union[a(b,", "tests/_plugins/typing_pep604_test.py::test_fix_union_edge_cases[Union[(a())]-1-a()]", "tests/_plugins/typing_pep604_test.py::test_fix_union_edge_cases[Union[(())]-1-()]", "tests/features/typing_pep604_test.py::test_fix_pep604_types[nested" ]
[ "tests/features/typing_pep604_test.py::test_fix_pep604_types_noop[<3.10", "tests/features/typing_pep604_test.py::test_fix_pep604_types_noop[<3.9", "tests/features/typing_pep604_test.py::test_fix_pep604_types_noop[3.10+", "tests/features/typing_pep604_test.py::test_noop_keep_runtime_typing", "tests/features/typing_pep604_test.py::test_keep_runtime_typing_ignored_in_py310", "tests/features/typing_pep604_test.py::test_fix_pep604_types[Union", "tests/features/typing_pep604_test.py::test_fix_pep604_types[Union,", "tests/features/typing_pep604_test.py::test_fix_pep604_types[Optional", "tests/features/typing_pep604_test.py::test_fix_generic_types_future_annotations[variable", "tests/features/typing_pep604_test.py::test_fix_generic_types_future_annotations[argument", "tests/features/typing_pep604_test.py::test_fix_generic_types_future_annotations[return" ]
{ "failed_lite_validators": [ "has_git_commit_hash", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-03-16 03:50:20+00:00
mit
1,174
asottile__pyupgrade-438
diff --git a/pyupgrade/_main.py b/pyupgrade/_main.py index d8e359d..b530008 100644 --- a/pyupgrade/_main.py +++ b/pyupgrade/_main.py @@ -391,6 +391,7 @@ def _build_import_removals() -> Dict[Version, Dict[str, Tuple[str, ...]]]: ((3, 8), ()), ((3, 9), ()), ((3, 10), ()), + ((3, 11), ()), ) prev: Tuple[str, ...] = ()
asottile/pyupgrade
4f1369bf114fd60cbe155e29a79fdd715e1e8f3e
diff --git a/tests/main_test.py b/tests/main_test.py index 9f7f16b..b8f507f 100644 --- a/tests/main_test.py +++ b/tests/main_test.py @@ -1,4 +1,5 @@ import io +import re import sys from unittest import mock @@ -11,19 +12,12 @@ def test_main_trivial(): assert main(()) == 0 [email protected]( - 'args', - ( - (), - ('--py3-plus',), - ('--py36-plus',), - ('--py37-plus',), - ('--py38-plus',), - ('--py39-plus',), - ('--py310-plus',), - ), -) -def test_main_noop(tmpdir, args): +def test_main_noop(tmpdir, capsys): + with pytest.raises(SystemExit): + main(('--help',)) + out, err = capsys.readouterr() + version_options = sorted(set(re.findall(r'--py\d+-plus', out))) + s = '''\ from sys import version_info x=version_info @@ -32,9 +26,14 @@ def f(): ''' f = tmpdir.join('f.py') f.write(s) - assert main((f.strpath, *args)) == 0 + + assert main((f.strpath,)) == 0 assert f.read() == s + for version_option in version_options: + assert main((f.strpath, version_option)) == 0 + assert f.read() == s + def test_main_changes_a_file(tmpdir, capsys): f = tmpdir.join('f.py')
`--py311-plus` option not working `--py311-plus` was added in #426 but when I run with it I get this: ``` Traceback (most recent call last): File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main return _run_code(code, main_globals, None, File "/usr/lib/python3.8/runpy.py", line 87, in _run_code exec(code, run_globals) File "/home/molkree/orca-action-venv/lib/python3.8/site-packages/pyupgrade/__main__.py", line 4, in <module> exit(main()) File "/home/molkree/orca-action-venv/lib/python3.8/site-packages/pyupgrade/_main.py", line 927, in main ret |= _fix_file(filename, args) File "/home/molkree/orca-action-venv/lib/python3.8/site-packages/pyupgrade/_main.py", line 871, in _fix_file contents_text = _fix_tokens(contents_text, min_version=args.min_version) File "/home/molkree/orca-action-venv/lib/python3.8/site-packages/pyupgrade/_main.py", line 509, in _fix_tokens _fix_import_removals(tokens, i, min_version) File "/home/molkree/orca-action-venv/lib/python3.8/site-packages/pyupgrade/_main.py", line 433, in _fix_import_removals if modname not in IMPORT_REMOVALS[min_version]: KeyError: (3, 11) ``` I think it just wasn't added here: https://github.com/asottile/pyupgrade/blob/4f1369bf114fd60cbe155e29a79fdd715e1e8f3e/pyupgrade/_main.py#L381-L394 There is still time to fix this before fall 2022 though 👀
0.0
4f1369bf114fd60cbe155e29a79fdd715e1e8f3e
[ "tests/main_test.py::test_main_noop" ]
[ "tests/main_test.py::test_main_trivial", "tests/main_test.py::test_main_changes_a_file", "tests/main_test.py::test_main_keeps_line_endings", "tests/main_test.py::test_main_syntax_error", "tests/main_test.py::test_main_non_utf8_bytes", "tests/main_test.py::test_main_py27_syntaxerror_coding", "tests/main_test.py::test_keep_percent_format", "tests/main_test.py::test_keep_mock", "tests/main_test.py::test_py3_plus_argument_unicode_literals", "tests/main_test.py::test_py3_plus_super", "tests/main_test.py::test_py3_plus_new_style_classes", "tests/main_test.py::test_py3_plus_oserror", "tests/main_test.py::test_py36_plus_fstrings", "tests/main_test.py::test_py37_plus_removes_annotations", "tests/main_test.py::test_py38_plus_removes_no_arg_decorators", "tests/main_test.py::test_noop_token_error", "tests/main_test.py::test_main_exit_zero_even_if_changed", "tests/main_test.py::test_main_stdin_no_changes", "tests/main_test.py::test_main_stdin_with_changes" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2021-05-13 18:12:52+00:00
mit
1,175
asottile__pyupgrade-529
diff --git a/pyupgrade/_plugins/percent_format.py b/pyupgrade/_plugins/percent_format.py index 8dc2c76..1b0599d 100644 --- a/pyupgrade/_plugins/percent_format.py +++ b/pyupgrade/_plugins/percent_format.py @@ -128,8 +128,6 @@ def _percent_to_format(s: str) -> str: if conversion == '%': return s + '%' parts = [s, '{'] - if width and conversion == 's' and not conversion_flag: - conversion_flag = '>' if conversion == 's': conversion = '' if key: @@ -276,6 +274,9 @@ def visit_BinOp( # no equivalent in format if conversion in {'a', 'r'} and nontrivial_fmt: break + # %s with None and width is not supported + if width and conversion == 's': + break # all dict substitutions must be named if isinstance(node.right, ast.Dict) and not key: break
asottile/pyupgrade
6b2d0d8b2293360f91082d4dcd068c36a8c568b8
diff --git a/tests/features/percent_format_test.py b/tests/features/percent_format_test.py index 57ca3c6..0d620ce 100644 --- a/tests/features/percent_format_test.py +++ b/tests/features/percent_format_test.py @@ -158,6 +158,7 @@ def test_simplify_conversion_flag(s, expected): '"%4%" % ()', # no equivalent in format specifier '"%.2r" % (1.25)', '"%.2a" % (1.25)', + pytest.param('"%8s" % (None,)', id='unsafe width-string conversion'), # non-string mod 'i % 3', # dict format but not keyed arguments @@ -208,8 +209,8 @@ def test_percent_format_noop_if_bug_16806(): ('"%s" % ("%s" % ("nested",),)', '"{}".format("{}".format("nested"))'), ('"%s%% percent" % (15,)', '"{}% percent".format(15)'), ('"%3f" % (15,)', '"{:3f}".format(15)'), - ('"%-5s" % ("hi",)', '"{:<5}".format("hi")'), - ('"%9s" % (5,)', '"{:>9}".format(5)'), + ('"%-5f" % (5,)', '"{:<5f}".format(5)'), + ('"%9f" % (5,)', '"{:9f}".format(5)'), ('"brace {} %s" % (1,)', '"brace {{}} {}".format(1)'), ( '"%s" % (\n'
f-string conversion with advanced string formatting & None Failing test case using pyupgrade 2.25.0: ``` $ echo 'a=b=c=None; print("Query:%8s %s %s" % (a, b, c))' > test.py ; pyupgrade --py36-plus test.py ; cat test.py Rewriting test.py a=b=c=None; print(f"Query:{a:>8} {b} {c}") ``` ```pycon >>> a=b=c=None; print("Query:%8s %s %s" % (a, b, c)) Query: None None None >>> a=b=c=None; print(f"Query:{a:>8} {b} {c}") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported format string passed to NoneType.__format__ ``` The problem is while ``f"{None}"`` works, advanced string format arguments do not: ```pycon >>> "%8s" % None ' None' ``` ```pycon >>> f"{None:>8}" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported format string passed to NoneType.__format__ ``` Possible workaround: ```python >>> a=b=c=None; print(f"Query:{str(a):>8} {b} {c}") Query: None None None ``` This issue was found in https://github.com/biopython/biopython/pull/3724
0.0
6b2d0d8b2293360f91082d4dcd068c36a8c568b8
[ "tests/features/percent_format_test.py::test_percent_format_noop[unsafe" ]
[ "tests/features/percent_format_test.py::test_parse_percent_format[\"\"-expected0]", "tests/features/percent_format_test.py::test_parse_percent_format[\"%%\"-expected1]", "tests/features/percent_format_test.py::test_parse_percent_format[\"%s\"-expected2]", "tests/features/percent_format_test.py::test_parse_percent_format[\"%s", "tests/features/percent_format_test.py::test_parse_percent_format[\"%(hi)s\"-expected4]", "tests/features/percent_format_test.py::test_parse_percent_format[\"%()s\"-expected5]", "tests/features/percent_format_test.py::test_parse_percent_format[\"%#o\"-expected6]", "tests/features/percent_format_test.py::test_parse_percent_format[\"%", "tests/features/percent_format_test.py::test_parse_percent_format[\"%5d\"-expected8]", "tests/features/percent_format_test.py::test_parse_percent_format[\"%*d\"-expected9]", "tests/features/percent_format_test.py::test_parse_percent_format[\"%.f\"-expected10]", "tests/features/percent_format_test.py::test_parse_percent_format[\"%.5f\"-expected11]", "tests/features/percent_format_test.py::test_parse_percent_format[\"%.*f\"-expected12]", "tests/features/percent_format_test.py::test_parse_percent_format[\"%ld\"-expected13]", "tests/features/percent_format_test.py::test_parse_percent_format[\"%(complete)#4.4f\"-expected14]", "tests/features/percent_format_test.py::test_percent_to_format[%s-{}]", "tests/features/percent_format_test.py::test_percent_to_format[%%%s-%{}]", "tests/features/percent_format_test.py::test_percent_to_format[%(foo)s-{foo}]", "tests/features/percent_format_test.py::test_percent_to_format[%2f-{:2f}]", "tests/features/percent_format_test.py::test_percent_to_format[%r-{!r}]", "tests/features/percent_format_test.py::test_percent_to_format[%a-{!a}]", "tests/features/percent_format_test.py::test_simplify_conversion_flag[-]", "tests/features/percent_format_test.py::test_simplify_conversion_flag[", "tests/features/percent_format_test.py::test_simplify_conversion_flag[#0-", "tests/features/percent_format_test.py::test_simplify_conversion_flag[--<]", "tests/features/percent_format_test.py::test_percent_format_noop[\"%s\"", "tests/features/percent_format_test.py::test_percent_format_noop[b\"%s\"", "tests/features/percent_format_test.py::test_percent_format_noop[\"%*s\"", "tests/features/percent_format_test.py::test_percent_format_noop[\"%.*s\"", "tests/features/percent_format_test.py::test_percent_format_noop[\"%d\"", "tests/features/percent_format_test.py::test_percent_format_noop[\"%i\"", "tests/features/percent_format_test.py::test_percent_format_noop[\"%u\"", "tests/features/percent_format_test.py::test_percent_format_noop[\"%c\"", "tests/features/percent_format_test.py::test_percent_format_noop[\"%#o\"", "tests/features/percent_format_test.py::test_percent_format_noop[\"%()s\"", "tests/features/percent_format_test.py::test_percent_format_noop[\"%4%\"", "tests/features/percent_format_test.py::test_percent_format_noop[\"%.2r\"", "tests/features/percent_format_test.py::test_percent_format_noop[\"%.2a\"", "tests/features/percent_format_test.py::test_percent_format_noop[i", "tests/features/percent_format_test.py::test_percent_format_noop[\"%(1)s\"", "tests/features/percent_format_test.py::test_percent_format_noop[\"%(a)s\"", "tests/features/percent_format_test.py::test_percent_format_noop[\"%(ab)s\"", "tests/features/percent_format_test.py::test_percent_format_noop[\"%(and)s\"", "tests/features/percent_format_test.py::test_percent_format_noop[\"%\"", "tests/features/percent_format_test.py::test_percent_format_noop[\"%(hi)\"", "tests/features/percent_format_test.py::test_percent_format_noop[\"%2\"", "tests/features/percent_format_test.py::test_percent_format_noop[\"%s", "tests/features/percent_format_test.py::test_percent_format_noop[\"%(foo)s", "tests/features/percent_format_test.py::test_percent_format[\"trivial\"", "tests/features/percent_format_test.py::test_percent_format[\"%s\"", "tests/features/percent_format_test.py::test_percent_format[\"%s%%", "tests/features/percent_format_test.py::test_percent_format[\"%3f\"", "tests/features/percent_format_test.py::test_percent_format[\"%-5f\"", "tests/features/percent_format_test.py::test_percent_format[\"%9f\"", "tests/features/percent_format_test.py::test_percent_format[\"brace", "tests/features/percent_format_test.py::test_percent_format[\"%(k)s\"", "tests/features/percent_format_test.py::test_percent_format[\"%(to_list)s\"" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2021-09-10 13:23:59+00:00
mit
1,176
asottile__pyupgrade-53
diff --git a/pyupgrade.py b/pyupgrade.py index 486a440..b9cb902 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -818,10 +818,12 @@ def _to_fstring(src, call): params[kwd.arg] = _unparse(kwd.value) parts = [] - for i, (s, name, spec, conv) in enumerate(parse_format('f' + src)): + i = 0 + for s, name, spec, conv in parse_format('f' + src): if name is not None: k, dot, rest = name.partition('.') name = ''.join((params[k or str(i)], dot, rest)) + i += 1 parts.append((s, name, spec, conv)) return unparse_parsed_string(parts)
asottile/pyupgrade
a37342a71a84f3046b90d46b656b4cae16266617
diff --git a/tests/pyupgrade_test.py b/tests/pyupgrade_test.py index 80d0b3b..24b47f4 100644 --- a/tests/pyupgrade_test.py +++ b/tests/pyupgrade_test.py @@ -721,6 +721,7 @@ def test_fix_fstrings_noop(s): ('"{.x} {.y}".format(a, b)', 'f"{a.x} {b.y}"'), ('"{} {}".format(a.b, c.d)', 'f"{a.b} {c.d}"'), ('"hello {}!".format(name)', 'f"hello {name}!"'), + ('"{}{{}}{}".format(escaped, y)', 'f"{escaped}{{}}{y}"'), # TODO: poor man's f-strings? # '"{foo}".format(**locals())'
KeyError running with --py36-plus on matplotlib's ticker.py Running pyupgrade 1.5 on matplotlib's ticker.py as of, say, mpl3.0rc2 (https://github.com/matplotlib/matplotlib/blob/v3.0.0rc2/lib/matplotlib/ticker.py) gives me ``` Traceback (most recent call last): File "/usr/bin/pyupgrade", line 11, in <module> sys.exit(main()) File "/usr/lib/python3.7/site-packages/pyupgrade.py", line 907, in main ret |= fix_file(filename, args) File "/usr/lib/python3.7/site-packages/pyupgrade.py", line 884, in fix_file contents_text = _fix_fstrings(contents_text) File "/usr/lib/python3.7/site-packages/pyupgrade.py", line 858, in _fix_fstrings tokens[i] = token._replace(src=_to_fstring(token.src, node)) File "/usr/lib/python3.7/site-packages/pyupgrade.py", line 824, in _to_fstring name = ''.join((params[k or str(i)], dot, rest)) KeyError: '3' ```
0.0
a37342a71a84f3046b90d46b656b4cae16266617
[ "tests/pyupgrade_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped," ]
[ "tests/pyupgrade_test.py::test_roundtrip_text[]", "tests/pyupgrade_test.py::test_roundtrip_text[foo]", "tests/pyupgrade_test.py::test_roundtrip_text[{}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0}]", "tests/pyupgrade_test.py::test_roundtrip_text[{named}]", "tests/pyupgrade_test.py::test_roundtrip_text[{!r}]", "tests/pyupgrade_test.py::test_roundtrip_text[{:>5}]", "tests/pyupgrade_test.py::test_roundtrip_text[{{]", "tests/pyupgrade_test.py::test_roundtrip_text[}}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0!s:15}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/pyupgrade_test.py::test_sets[set()-set()]", "tests/pyupgrade_test.py::test_sets[set((\\n))-set((\\n))]", "tests/pyupgrade_test.py::test_sets[set", "tests/pyupgrade_test.py::test_sets[set(())-set()]", "tests/pyupgrade_test.py::test_sets[set([])-set()]", "tests/pyupgrade_test.py::test_sets[set((", "tests/pyupgrade_test.py::test_sets[set([1,", "tests/pyupgrade_test.py::test_sets[set(x", "tests/pyupgrade_test.py::test_sets[set([(1,", "tests/pyupgrade_test.py::test_sets[set([((1,", "tests/pyupgrade_test.py::test_dictcomps[x", "tests/pyupgrade_test.py::test_dictcomps[dict()-dict()]", "tests/pyupgrade_test.py::test_dictcomps[(-(]", "tests/pyupgrade_test.py::test_dictcomps[dict", "tests/pyupgrade_test.py::test_format_literals['{}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{'.format(1)-'{'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['}'.format(1)-'}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals[x", "tests/pyupgrade_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/pyupgrade_test.py::test_format_literals['{0}'", "tests/pyupgrade_test.py::test_format_literals[print(\\n", "tests/pyupgrade_test.py::test_format_literals['{0:<{1}}'.format(1,", "tests/pyupgrade_test.py::test_imports_unicode_literals[import", "tests/pyupgrade_test.py::test_imports_unicode_literals[from", "tests/pyupgrade_test.py::test_imports_unicode_literals[x", "tests/pyupgrade_test.py::test_imports_unicode_literals[\"\"\"docstring\"\"\"\\nfrom", "tests/pyupgrade_test.py::test_unicode_literals[(-False-(]", "tests/pyupgrade_test.py::test_unicode_literals[u''-False-u'']", "tests/pyupgrade_test.py::test_unicode_literals[u''-True-'']", "tests/pyupgrade_test.py::test_unicode_literals[from", "tests/pyupgrade_test.py::test_unicode_literals[\"\"\"with", "tests/pyupgrade_test.py::test_noop_octal_literals[0-0]", "tests/pyupgrade_test.py::test_noop_octal_literals[00-00]", "tests/pyupgrade_test.py::test_noop_octal_literals[1-1]", "tests/pyupgrade_test.py::test_noop_octal_literals[12345-12345]", "tests/pyupgrade_test.py::test_noop_octal_literals[1.2345-1.2345]", "tests/pyupgrade_test.py::test_is_bytestring_true[b'']", "tests/pyupgrade_test.py::test_is_bytestring_true[b\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B'']", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''0]", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''1]", "tests/pyupgrade_test.py::test_is_bytestring_false[]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false['']", "tests/pyupgrade_test.py::test_is_bytestring_false[u\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"b\"]", "tests/pyupgrade_test.py::test_parse_percent_format[\"\"-expected0]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%%\"-expected1]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s\"-expected2]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(hi)s\"-expected4]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%()s\"-expected5]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%#o\"-expected6]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%", "tests/pyupgrade_test.py::test_parse_percent_format[\"%5d\"-expected8]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%*d\"-expected9]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.f\"-expected10]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.5f\"-expected11]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.*f\"-expected12]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%ld\"-expected13]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(complete)#4.4f\"-expected14]", "tests/pyupgrade_test.py::test_percent_to_format[%s-{}]", "tests/pyupgrade_test.py::test_percent_to_format[%%%s-%{}]", "tests/pyupgrade_test.py::test_percent_to_format[%(foo)s-{foo}]", "tests/pyupgrade_test.py::test_percent_to_format[%2f-{:2f}]", "tests/pyupgrade_test.py::test_percent_to_format[%r-{!r}]", "tests/pyupgrade_test.py::test_percent_to_format[%a-{!a}]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[-]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[", "tests/pyupgrade_test.py::test_simplify_conversion_flag[#0-", "tests/pyupgrade_test.py::test_simplify_conversion_flag[--<]", "tests/pyupgrade_test.py::test_percent_format_noop[\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[b\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%d\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%i\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%u\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%c\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%#o\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%()s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%4%\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2r\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2a\"", "tests/pyupgrade_test.py::test_percent_format_noop[i", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(1)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(a)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(ab)s\"", "tests/pyupgrade_test.py::test_percent_format[\"trivial\"", "tests/pyupgrade_test.py::test_percent_format[\"%s%%", "tests/pyupgrade_test.py::test_percent_format[\"%3f\"", "tests/pyupgrade_test.py::test_percent_format[\"%-5s\"", "tests/pyupgrade_test.py::test_percent_format[\"brace", "tests/pyupgrade_test.py::test_percent_format[\"%(k)s\"", "tests/pyupgrade_test.py::test_fix_super_noop[x(]", "tests/pyupgrade_test.py::test_fix_super_noop[class", "tests/pyupgrade_test.py::test_fix_super_noop[def", "tests/pyupgrade_test.py::test_fix_super[class", "tests/pyupgrade_test.py::test_fix_fstrings_noop[(]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\"", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{foo}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{0}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[b\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{1}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{.x}", "tests/pyupgrade_test.py::test_fix_fstrings[\"hello", "tests/pyupgrade_test.py::test_main_trivial", "tests/pyupgrade_test.py::test_main_noop", "tests/pyupgrade_test.py::test_main_syntax_error", "tests/pyupgrade_test.py::test_main_non_utf8_bytes", "tests/pyupgrade_test.py::test_py3_plus_argument_unicode_literals", "tests/pyupgrade_test.py::test_py3_plus_super", "tests/pyupgrade_test.py::test_py36_plus_fstrings" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2018-09-06 22:54:00+00:00
mit
1,177
asottile__pyupgrade-545
diff --git a/pyupgrade/_plugins/legacy.py b/pyupgrade/_plugins/legacy.py index f7ba376..3ae702a 100644 --- a/pyupgrade/_plugins/legacy.py +++ b/pyupgrade/_plugins/legacy.py @@ -8,6 +8,7 @@ from typing import Iterable from typing import List from typing import Set from typing import Tuple +from typing import Union from tokenize_rt import Offset from tokenize_rt import Token @@ -25,6 +26,7 @@ from pyupgrade._token_helpers import find_token FUNC_TYPES = (ast.Lambda, ast.FunctionDef, ast.AsyncFunctionDef) NON_LAMBDA_FUNC_TYPES = (ast.FunctionDef, ast.AsyncFunctionDef) +NonLambdaFuncTypes_T = Union[ast.FunctionDef, ast.AsyncFunctionDef] def _fix_yield(i: int, tokens: List[Token]) -> None: @@ -44,6 +46,14 @@ def _is_simple_base(base: ast.AST) -> bool: ) +def _is_staticmethod_decorated(node: NonLambdaFuncTypes_T) -> bool: + for decorator in node.decorator_list: + if isinstance(decorator, ast.Name) and decorator.id == 'staticmethod': + return True + else: + return False + + class Scope: def __init__(self, node: ast.AST) -> None: self.node = node @@ -127,6 +137,7 @@ class Visitor(ast.NodeVisitor): isinstance(self._scopes[-1].node, NON_LAMBDA_FUNC_TYPES) and node.func.attr == self._scopes[-1].node.name and node.func.attr != '__new__' and + not _is_staticmethod_decorated(self._scopes[-1].node) and len(self._scopes[-1].node.args.args) >= 1 and node.args[0].id == self._scopes[-1].node.args.args[0].arg and # the function is an attribute of the contained class name
asottile/pyupgrade
a2f517f0103c1f74bffbc06be510bcec4cd181ec
diff --git a/tests/features/super_test.py b/tests/features/super_test.py index 8e3be14..e58ffea 100644 --- a/tests/features/super_test.py +++ b/tests/features/super_test.py @@ -188,6 +188,13 @@ def test_fix_super(s, expected): ' return tuple.__new__(cls, (arg,))\n', id='super() does not work properly for __new__', ), + pytest.param( + 'class C(B):\n' + ' @staticmethod\n' + ' def f(arg):\n' + ' return B.f(arg)\n', + id='skip staticmethod', + ), ), ) def test_old_style_class_super_noop(s): @@ -207,6 +214,17 @@ def test_old_style_class_super_noop(s): ' super().f()\n' ' super().f(arg, arg)\n', ), + pytest.param( + 'class C(B):\n' + ' @classmethod\n' + ' def f(cls):\n' + ' B.f(cls)\n', + 'class C(B):\n' + ' @classmethod\n' + ' def f(cls):\n' + ' super().f()\n', + id='@classmethod', + ), pytest.param( 'class C(B):\n' ' def f(self, a):\n'
Rewriting old-style superclasses removes args for static methods ```python class Parent: @staticmethod def func(arg): return 0 class Child(Parent): @staticmethod def func(arg): return Parent.func(arg) ``` rewrites `Parent._thing(arg)` to `super()._thing()` rather than `super()._thing(arg)`
0.0
a2f517f0103c1f74bffbc06be510bcec4cd181ec
[ "tests/features/super_test.py::test_old_style_class_super_noop[skip" ]
[ "tests/features/super_test.py::test_fix_super_noop[x(]", "tests/features/super_test.py::test_fix_super_noop[class", "tests/features/super_test.py::test_fix_super_noop[def", "tests/features/super_test.py::test_fix_super[class", "tests/features/super_test.py::test_fix_super[async", "tests/features/super_test.py::test_old_style_class_super_noop[old", "tests/features/super_test.py::test_old_style_class_super_noop[old-style", "tests/features/super_test.py::test_old_style_class_super_noop[super", "tests/features/super_test.py::test_old_style_class_super_noop[not", "tests/features/super_test.py::test_old_style_class_super_noop[non", "tests/features/super_test.py::test_old_style_class_super_noop[class", "tests/features/super_test.py::test_old_style_class_super_noop[super()", "tests/features/super_test.py::test_old_style_class_super[class", "tests/features/super_test.py::test_old_style_class_super[@classmethod]", "tests/features/super_test.py::test_old_style_class_super[multi-line" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-09-27 19:16:24+00:00
mit
1,178
asottile__pyupgrade-584
diff --git a/pyupgrade/_plugins/six_calls.py b/pyupgrade/_plugins/six_calls.py index 90c4ee3..ac58fd5 100644 --- a/pyupgrade/_plugins/six_calls.py +++ b/pyupgrade/_plugins/six_calls.py @@ -172,13 +172,21 @@ def visit_Call( ('reraise',), ) ): - if len(node.args) == 2 and not has_starargs(node): + if ( + len(node.args) == 2 and + not node.keywords and + not has_starargs(node) + ): func = functools.partial( find_and_replace_call, template=RERAISE_2_TMPL, ) yield ast_to_offset(node), func - elif len(node.args) == 3 and not has_starargs(node): + elif ( + len(node.args) == 3 and + not node.keywords and + not has_starargs(node) + ): func = functools.partial( find_and_replace_call, template=RERAISE_3_TMPL, @@ -186,6 +194,7 @@ def visit_Call( yield ast_to_offset(node), func elif ( len(node.args) == 1 and + not node.keywords and isinstance(node.args[0], ast.Starred) and isinstance(node.args[0].value, ast.Call) and is_name_attr(
asottile/pyupgrade
234e07160f1d6a171b1100de7046a92d4866e0ba
diff --git a/tests/features/six_test.py b/tests/features/six_test.py index e1f6cd8..4ea3f5b 100644 --- a/tests/features/six_test.py +++ b/tests/features/six_test.py @@ -24,6 +24,7 @@ from pyupgrade._main import _fix_plugins 'class C(six.with_metaclass(Meta, B), D): pass', # cannot determine args to rewrite them 'six.reraise(*err)', 'six.u(*a)', + 'six.reraise(a, b, tb=c)', 'class C(six.with_metaclass(*a)): pass', '@six.add_metaclass(*a)\n' 'class C: pass\n',
Incorrect rewrite of six.reraise with traceback as keyword argument Reduced from real code in Launchpad: ``` $ cat t.py import sys from six import reraise exc_info = sys.exc_info() reraise(exc_info[0], exc_info[1], tb=exc_info[2]) $ pyupgrade --py3-plus t.py Rewriting t.py $ cat t.py import sys from six import reraise exc_info = sys.exc_info() raise exc_info[1].with_traceback(None) ``` pyupgrade has missed the keyword argument here; this should instead be rewritten to `raise exc_info[1].with_traceback(exc_info[2])`. (In fact in Python 3 this can end up just being a plain `raise`: the original code was more complicated and had a second possible exception being raised and handled between `sys.exc_info()` and `reraise()`, which in Python 2 would have caused plain `raise` to raise the second exception, but the exception scoping changes in Python 3 mean that a plain `raise` will do the right thing. I don't expect pyupgrade to do that sort of analysis, though.)
0.0
234e07160f1d6a171b1100de7046a92d4866e0ba
[ "tests/features/six_test.py::test_fix_six_noop[six.reraise(a," ]
[ "tests/features/six_test.py::test_fix_six_noop[x", "tests/features/six_test.py::test_fix_six_noop[from", "tests/features/six_test.py::test_fix_six_noop[a[0]()]", "tests/features/six_test.py::test_fix_six_noop[@mydec\\nclass", "tests/features/six_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/features/six_test.py::test_fix_six_noop[class", "tests/features/six_test.py::test_fix_six_noop[six.reraise(*err)]", "tests/features/six_test.py::test_fix_six_noop[six.u(*a)]", "tests/features/six_test.py::test_fix_six_noop[@six.add_metaclass(*a)\\nclass", "tests/features/six_test.py::test_fix_six_noop[next()]", "tests/features/six_test.py::test_fix_six_noop[traceback.format_exc(*sys.exc_info())]", "tests/features/six_test.py::test_fix_six_noop[wrong", "tests/features/six_test.py::test_fix_six_noop[ignore", "tests/features/six_test.py::test_fix_six[six.byte2int(b\"f\")-b\"f\"[0]]", "tests/features/six_test.py::test_fix_six[six.get_unbound_function(meth)\\n-meth\\n]", "tests/features/six_test.py::test_fix_six[from", "tests/features/six_test.py::test_fix_six[six.indexbytes(bs,", "tests/features/six_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/features/six_test.py::test_fix_six[weird", "tests/features/six_test.py::test_fix_six[six.raise_from(exc,", "tests/features/six_test.py::test_fix_six[six", "tests/features/six_test.py::test_fix_six[six.reraise(tp,", "tests/features/six_test.py::test_fix_six[six.reraise(*sys.exc_info())\\n-raise\\n]", "tests/features/six_test.py::test_fix_six[six.reraise(\\n", "tests/features/six_test.py::test_fix_six[class", "tests/features/six_test.py::test_fix_six[elide", "tests/features/six_test.py::test_fix_six[with_metaclass", "tests/features/six_test.py::test_fix_six[basic", "tests/features/six_test.py::test_fix_six[add_metaclass,", "tests/features/six_test.py::test_fix_six[six.itervalues]", "tests/features/six_test.py::test_fix_six[six.itervalues", "tests/features/six_test.py::test_fix_six[needs", "tests/features/six_test.py::test_fix_six[no", "tests/features/six_test.py::test_fix_six[multiline", "tests/features/six_test.py::test_fix_six_py38_plus[needs", "tests/features/six_test.py::test_fix_base_classes[import", "tests/features/six_test.py::test_fix_base_classes[from", "tests/features/six_test.py::test_fix_base_classes[class" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2021-12-30 16:36:19+00:00
mit
1,179
asottile__pyupgrade-611
diff --git a/pyupgrade/_plugins/subprocess_run.py b/pyupgrade/_plugins/subprocess_run.py index 48affbe..53cc03d 100644 --- a/pyupgrade/_plugins/subprocess_run.py +++ b/pyupgrade/_plugins/subprocess_run.py @@ -79,6 +79,7 @@ def visit_Call( stdout_idx = None stderr_idx = None universal_newlines_idx = None + skip_universal_newlines_rewrite = False for n, keyword in enumerate(node.keywords): if keyword.arg == 'stdout' and is_name_attr( keyword.value, @@ -96,7 +97,12 @@ def visit_Call( stderr_idx = n elif keyword.arg == 'universal_newlines': universal_newlines_idx = n - if universal_newlines_idx is not None: + elif keyword.arg == 'text' or keyword.arg is None: + skip_universal_newlines_rewrite = True + if ( + universal_newlines_idx is not None and + not skip_universal_newlines_rewrite + ): func = functools.partial( _replace_universal_newlines_with_text, arg_idx=len(node.args) + universal_newlines_idx,
asottile/pyupgrade
d71f806ce2fa0799c8dbe8cdcba7f9d5af2fd167
diff --git a/tests/features/universal_newlines_to_text_test.py b/tests/features/universal_newlines_to_text_test.py index 2e7e298..e7acd9e 100644 --- a/tests/features/universal_newlines_to_text_test.py +++ b/tests/features/universal_newlines_to_text_test.py @@ -27,6 +27,26 @@ from pyupgrade._main import _fix_plugins (3, 7), id='universal_newlines not used', ), + pytest.param( + 'import subprocess\n' + 'subprocess.run(\n' + ' ["foo"],\n' + ' text=True,\n' + ' universal_newlines=True\n' + ')\n', + (3, 7), + id='both text and universal_newlines', + ), + pytest.param( + 'import subprocess\n' + 'subprocess.run(\n' + ' ["foo"],\n' + ' universal_newlines=True,\n' + ' **kwargs,\n' + ')\n', + (3, 7), + id='both **kwargs and universal_newlines', + ), ), ) def test_fix_universal_newlines_to_text_noop(s, version):
universal_newlines conversion can lead to doubled "text" If for some reason `universal_newlines` and `text` are both passed to a `subprocess.run()`, replacing the first with the latter causes `text` to be doubled. I suggest to in such case remove `universal_newlines`, if `text` has priority anyway with Python 3.6 and later.
0.0
d71f806ce2fa0799c8dbe8cdcba7f9d5af2fd167
[ "tests/features/universal_newlines_to_text_test.py::test_fix_universal_newlines_to_text_noop[both" ]
[ "tests/features/universal_newlines_to_text_test.py::test_fix_universal_newlines_to_text_noop[not", "tests/features/universal_newlines_to_text_test.py::test_fix_universal_newlines_to_text_noop[run", "tests/features/universal_newlines_to_text_test.py::test_fix_universal_newlines_to_text_noop[universal_newlines", "tests/features/universal_newlines_to_text_test.py::test_fix_universal_newlines_to_text[subprocess.run", "tests/features/universal_newlines_to_text_test.py::test_fix_universal_newlines_to_text[run", "tests/features/universal_newlines_to_text_test.py::test_fix_universal_newlines_to_text[universal_newlines", "tests/features/universal_newlines_to_text_test.py::test_fix_universal_newlines_to_text[with" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2022-03-13 19:09:43+00:00
mit
1,180
asottile__pyupgrade-656
diff --git a/pyupgrade/_plugins/open_mode.py b/pyupgrade/_plugins/open_mode.py index fb3f3b6..bc3169a 100644 --- a/pyupgrade/_plugins/open_mode.py +++ b/pyupgrade/_plugins/open_mode.py @@ -55,8 +55,17 @@ def visit_Call( ) -> Iterable[tuple[Offset, TokenFunc]]: if ( state.settings.min_version >= (3,) and - isinstance(node.func, ast.Name) and - node.func.id == 'open' and + ( + ( + isinstance(node.func, ast.Name) and + node.func.id == 'open' + ) or ( + isinstance(node.func, ast.Attribute) and + isinstance(node.func.value, ast.Name) and + node.func.value.id == 'io' and + node.func.attr == 'open' + ) + ) and not has_starargs(node) ): if len(node.args) >= 2 and isinstance(node.args[1], ast.Str):
asottile/pyupgrade
85f02f45f0d2889f3826f16b60f27188ea84c1ae
diff --git a/tests/features/open_mode_test.py b/tests/features/open_mode_test.py index 9fafc7c..32a2fd1 100644 --- a/tests/features/open_mode_test.py +++ b/tests/features/open_mode_test.py @@ -65,6 +65,11 @@ def test_fix_open_mode_noop(s): 'open(encoding="UTF-8", file="t.py")', ), pytest.param('open(f, u"r")', 'open(f)', id='string with u flag'), + pytest.param( + 'io.open("foo", "r")', + 'open("foo")', + id='io.open also rewrites modes in a single pass', + ), ), ) def test_fix_open_mode(s, expected):
two steps to converge: io.open(..., 'r') the first step goes to `open(..., 'r')` and the second step goes to `open(...)`
0.0
85f02f45f0d2889f3826f16b60f27188ea84c1ae
[ "tests/features/open_mode_test.py::test_fix_open_mode[io.open" ]
[ "tests/features/open_mode_test.py::test_fix_open_mode_noop[open(\"foo\",", "tests/features/open_mode_test.py::test_fix_open_mode_noop[open(mode=\"r\")]", "tests/features/open_mode_test.py::test_fix_open_mode[open(\"foo\",", "tests/features/open_mode_test.py::test_fix_open_mode[open(\"f\",", "tests/features/open_mode_test.py::test_fix_open_mode[open(file=\"f\",", "tests/features/open_mode_test.py::test_fix_open_mode[open(mode=\"r\",", "tests/features/open_mode_test.py::test_fix_open_mode[string" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2022-07-01 18:20:46+00:00
mit
1,181
asottile__pyupgrade-75
diff --git a/README.md b/README.md index 521b142..ec37d48 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,21 @@ u"foo" # 'foo' u'''foo''' # '''foo''' ``` +### Invalid escape sequences + +```python +# strings with only invalid sequences become raw strings +'\d' # r'\d' +# strings with mixed valid / invalid sequences get escaped +'\n\d' # '\n\\d' +# `ur` is not a valid string prefix in python3 +u'\d' # u'\\d' + +# note: pyupgrade is timid in one case (that's usually a mistake) +# in python2.x `'\u2603'` is the same as `'\\u2603'` without `unicode_literals` +# but in python3.x, that's our friend ☃ +``` + ### Long literals Availability: diff --git a/pyupgrade.py b/pyupgrade.py index 8385410..d6a196c 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -8,6 +8,7 @@ import copy import io import re import string +import warnings from tokenize_rt import ESCAPED_NL from tokenize_rt import Offset @@ -60,7 +61,10 @@ def _ast_to_offset(node): def ast_parse(contents_text): - return ast.parse(contents_text.encode('UTF-8')) + # intentionally ignore warnings, we might be fixing warning-ridden syntax + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + return ast.parse(contents_text.encode('UTF-8')) def inty(s): @@ -431,6 +435,65 @@ def _fix_unicode_literals(contents_text, py3_plus): return tokens_to_src(tokens) +# https://docs.python.org/3/reference/lexical_analysis.html +ESCAPE_STARTS = frozenset(( + '\n', '\\', "'", '"', 'a', 'b', 'f', 'n', 'r', 't', 'v', + '0', '1', '2', '3', '4', '5', '6', '7', # octal escapes + 'x', # hex escapes + # only valid in non-bytestrings + 'N', 'u', 'U', +)) +ESCAPE_STARTS_BYTES = ESCAPE_STARTS - frozenset(('N', 'u', 'U')) +ESCAPE_RE = re.compile(r'\\.') + + +def _fix_escape_sequences(contents_text): + last_name = None + tokens = src_to_tokens(contents_text) + for i, token in enumerate(tokens): + if token.name == 'NAME': + last_name = token + continue + elif token.name != 'STRING': + last_name = None + continue + + match = STRING_PREFIXES_RE.match(token.src) + prefix = match.group(1) + rest = match.group(2) + + if last_name is not None: # pragma: no cover (py2 bug) + actual_prefix = (last_name.src + prefix).lower() + else: # pragma: no cover (py3 only) + actual_prefix = prefix.lower() + + if 'r' in actual_prefix or '\\' not in rest: + continue + + if 'b' in actual_prefix: + valid_escapes = ESCAPE_STARTS_BYTES + else: + valid_escapes = ESCAPE_STARTS + + escape_sequences = {m[1] for m in ESCAPE_RE.findall(rest)} + has_valid_escapes = escape_sequences & valid_escapes + has_invalid_escapes = escape_sequences - valid_escapes + + def cb(match): + matched = match.group() + if matched[1] in valid_escapes: + return matched + else: + return r'\{}'.format(matched) + + if has_invalid_escapes and (has_valid_escapes or 'u' in actual_prefix): + tokens[i] = token._replace(src=prefix + ESCAPE_RE.sub(cb, rest)) + elif has_invalid_escapes and not has_valid_escapes: + tokens[i] = token._replace(src=prefix + 'r' + rest) + + return tokens_to_src(tokens) + + def _fix_long_literals(contents_text): tokens = src_to_tokens(contents_text) for i, token in enumerate(tokens): @@ -1248,6 +1311,7 @@ def fix_file(filename, args): contents_text = _fix_sets(contents_text) contents_text = _fix_format_literals(contents_text) contents_text = _fix_unicode_literals(contents_text, args.py3_plus) + contents_text = _fix_escape_sequences(contents_text) contents_text = _fix_long_literals(contents_text) contents_text = _fix_octal_literals(contents_text) if not args.keep_percent_format:
asottile/pyupgrade
ca306cf35fa97586ef55163706d40612052b2d70
diff --git a/tests/pyupgrade_test.py b/tests/pyupgrade_test.py index d468953..82acd34 100644 --- a/tests/pyupgrade_test.py +++ b/tests/pyupgrade_test.py @@ -8,6 +8,7 @@ import sys import pytest from pyupgrade import _fix_dictcomps +from pyupgrade import _fix_escape_sequences from pyupgrade import _fix_format_literals from pyupgrade import _fix_fstrings from pyupgrade import _fix_long_literals @@ -327,6 +328,48 @@ def test_unicode_literals(s, py3_plus, expected): assert ret == expected [email protected]( + 's', + ( + '""', + r'r"\d"', r"r'\d'", r'r"""\d"""', r"r'''\d'''", + # python2 has a bug where `rb'foo'` is tokenized as NAME + STRING + r'rb"\d"', + # make sure we don't replace an already valid string + r'"\\d"', + # in python2 `'\u2603'` is literally \\u2603, but transforming based + # on that would be incorrect in python3. + # intentionally timid here to avoid breaking working python3 code + '"\\u2603"', + # don't touch already valid escapes + r'"\r\n"', + ), +) +def test_fix_escape_sequences_noop(s): + assert _fix_escape_sequences(s) == s + + [email protected]( + ('s', 'expected'), + ( + # no valid escape sequences, make a raw literal + (r'"\d"', r'r"\d"'), + # when there are valid escape sequences, need to use backslashes + (r'"\n\d"', r'"\n\\d"'), + # `ur` is not a valid string prefix in python3.x + (r'u"\d"', r'u"\\d"'), + # `rb` is not a valid string prefix in python2.x + (r'b"\d"', r'br"\d"'), + # 8 and 9 aren't valid octal digits + (r'"\8"', r'r"\8"'), (r'"\9"', r'r"\9"'), + # explicit byte strings should not honor string-specific escapes + ('b"\\u2603"', 'br"\\u2603"'), + ), +) +def test_fix_escape_sequences(s, expected): + assert _fix_escape_sequences(s) == expected + + @pytest.mark.xfail(sys.version_info >= (3,), reason='python2 "feature"') @pytest.mark.parametrize( ('s', 'expected'),
consider fixing invalid escape sequences ``` $ python2 -W once -c 'print("\d test")' \d test $ python3 -W once -c 'print("\d test")' <string>:1: DeprecationWarning: invalid escape sequence \d \d test $ python3 -W once -c 'print(r"\d test")' \d test ```
0.0
ca306cf35fa97586ef55163706d40612052b2d70
[ "tests/pyupgrade_test.py::test_roundtrip_text[]", "tests/pyupgrade_test.py::test_roundtrip_text[foo]", "tests/pyupgrade_test.py::test_roundtrip_text[{}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0}]", "tests/pyupgrade_test.py::test_roundtrip_text[{named}]", "tests/pyupgrade_test.py::test_roundtrip_text[{!r}]", "tests/pyupgrade_test.py::test_roundtrip_text[{:>5}]", "tests/pyupgrade_test.py::test_roundtrip_text[{{]", "tests/pyupgrade_test.py::test_roundtrip_text[}}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0!s:15}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/pyupgrade_test.py::test_sets[set()-set()]", "tests/pyupgrade_test.py::test_sets[set((\\n))-set((\\n))]", "tests/pyupgrade_test.py::test_sets[set", "tests/pyupgrade_test.py::test_sets[set(())-set()]", "tests/pyupgrade_test.py::test_sets[set([])-set()]", "tests/pyupgrade_test.py::test_sets[set((", "tests/pyupgrade_test.py::test_sets[set([1,", "tests/pyupgrade_test.py::test_sets[set(x", "tests/pyupgrade_test.py::test_sets[set([(1,", "tests/pyupgrade_test.py::test_sets[set([((1,", "tests/pyupgrade_test.py::test_dictcomps[x", "tests/pyupgrade_test.py::test_dictcomps[dict()-dict()]", "tests/pyupgrade_test.py::test_dictcomps[(-(]", "tests/pyupgrade_test.py::test_dictcomps[dict", "tests/pyupgrade_test.py::test_format_literals['{}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{'.format(1)-'{'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['}'.format(1)-'}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals[x", "tests/pyupgrade_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/pyupgrade_test.py::test_format_literals['{0}'", "tests/pyupgrade_test.py::test_format_literals[print(\\n", "tests/pyupgrade_test.py::test_format_literals['{0:<{1}}'.format(1,", "tests/pyupgrade_test.py::test_imports_unicode_literals[import", "tests/pyupgrade_test.py::test_imports_unicode_literals[from", "tests/pyupgrade_test.py::test_imports_unicode_literals[x", "tests/pyupgrade_test.py::test_imports_unicode_literals[\"\"\"docstring\"\"\"\\nfrom", "tests/pyupgrade_test.py::test_unicode_literals[(-False-(]", "tests/pyupgrade_test.py::test_unicode_literals[u''-False-u'']", "tests/pyupgrade_test.py::test_unicode_literals[u''-True-'']", "tests/pyupgrade_test.py::test_unicode_literals[from", "tests/pyupgrade_test.py::test_unicode_literals[\"\"\"with", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'\\\\d']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\"\"\\\\d\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'''\\\\d''']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[rb\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\r\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\d\"-r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\n\\\\d\"-\"\\\\n\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[u\"\\\\d\"-u\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\d\"-br\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\8\"-r\"\\\\8\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\9\"-r\"\\\\9\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\u2603\"-br\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_noop_octal_literals[0]", "tests/pyupgrade_test.py::test_noop_octal_literals[00]", "tests/pyupgrade_test.py::test_noop_octal_literals[1]", "tests/pyupgrade_test.py::test_noop_octal_literals[12345]", "tests/pyupgrade_test.py::test_noop_octal_literals[1.2345]", "tests/pyupgrade_test.py::test_is_bytestring_true[b'']", "tests/pyupgrade_test.py::test_is_bytestring_true[b\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B'']", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''0]", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''1]", "tests/pyupgrade_test.py::test_is_bytestring_false[]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false['']", "tests/pyupgrade_test.py::test_is_bytestring_false[u\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"b\"]", "tests/pyupgrade_test.py::test_parse_percent_format[\"\"-expected0]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%%\"-expected1]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s\"-expected2]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(hi)s\"-expected4]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%()s\"-expected5]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%#o\"-expected6]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%", "tests/pyupgrade_test.py::test_parse_percent_format[\"%5d\"-expected8]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%*d\"-expected9]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.f\"-expected10]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.5f\"-expected11]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.*f\"-expected12]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%ld\"-expected13]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(complete)#4.4f\"-expected14]", "tests/pyupgrade_test.py::test_percent_to_format[%s-{}]", "tests/pyupgrade_test.py::test_percent_to_format[%%%s-%{}]", "tests/pyupgrade_test.py::test_percent_to_format[%(foo)s-{foo}]", "tests/pyupgrade_test.py::test_percent_to_format[%2f-{:2f}]", "tests/pyupgrade_test.py::test_percent_to_format[%r-{!r}]", "tests/pyupgrade_test.py::test_percent_to_format[%a-{!a}]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[-]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[", "tests/pyupgrade_test.py::test_simplify_conversion_flag[#0-", "tests/pyupgrade_test.py::test_simplify_conversion_flag[--<]", "tests/pyupgrade_test.py::test_percent_format_noop[\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[b\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%d\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%i\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%u\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%c\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%#o\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%()s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%4%\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2r\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2a\"", "tests/pyupgrade_test.py::test_percent_format_noop[i", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(1)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(a)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(ab)s\"", "tests/pyupgrade_test.py::test_percent_format[\"trivial\"", "tests/pyupgrade_test.py::test_percent_format[\"%s%%", "tests/pyupgrade_test.py::test_percent_format[\"%3f\"", "tests/pyupgrade_test.py::test_percent_format[\"%-5s\"", "tests/pyupgrade_test.py::test_percent_format[\"brace", "tests/pyupgrade_test.py::test_percent_format[\"%(k)s\"", "tests/pyupgrade_test.py::test_percent_format[\"%(to_list)s\"", "tests/pyupgrade_test.py::test_fix_super_noop[x(]", "tests/pyupgrade_test.py::test_fix_super_noop[class", "tests/pyupgrade_test.py::test_fix_super_noop[def", "tests/pyupgrade_test.py::test_fix_super[class", "tests/pyupgrade_test.py::test_fix_new_style_classes_noop[x", "tests/pyupgrade_test.py::test_fix_new_style_classes_noop[class", "tests/pyupgrade_test.py::test_fix_new_style_classes[class", "tests/pyupgrade_test.py::test_fix_six_noop[x", "tests/pyupgrade_test.py::test_fix_six_noop[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six_noop[@", "tests/pyupgrade_test.py::test_fix_six_noop[from", "tests/pyupgrade_test.py::test_fix_six_noop[@mydec\\nclass", "tests/pyupgrade_test.py::test_fix_six_noop[six.u", "tests/pyupgrade_test.py::test_fix_six[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six[issubclass(tp,", "tests/pyupgrade_test.py::test_fix_six[STRING_TYPES", "tests/pyupgrade_test.py::test_fix_six[from", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/pyupgrade_test.py::test_fix_six[six.get_unbound_method(meth)\\n-meth\\n]", "tests/pyupgrade_test.py::test_fix_six[six.indexbytes(bs,", "tests/pyupgrade_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/pyupgrade_test.py::test_fix_new_style_classes_py3only[class", "tests/pyupgrade_test.py::test_fix_fstrings_noop[(]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\"", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{foo}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{0}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[b\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{1}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{.x}", "tests/pyupgrade_test.py::test_fix_fstrings[\"hello", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped,", "tests/pyupgrade_test.py::test_main_trivial", "tests/pyupgrade_test.py::test_main_noop", "tests/pyupgrade_test.py::test_main_syntax_error", "tests/pyupgrade_test.py::test_main_non_utf8_bytes", "tests/pyupgrade_test.py::test_keep_percent_format", "tests/pyupgrade_test.py::test_py3_plus_argument_unicode_literals", "tests/pyupgrade_test.py::test_py3_plus_super", "tests/pyupgrade_test.py::test_py3_plus_new_style_classes", "tests/pyupgrade_test.py::test_py36_plus_fstrings" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2018-10-28 22:34:18+00:00
mit
1,182
asottile__pyupgrade-77
diff --git a/pyupgrade.py b/pyupgrade.py index d6a196c..928b97e 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -437,7 +437,7 @@ def _fix_unicode_literals(contents_text, py3_plus): # https://docs.python.org/3/reference/lexical_analysis.html ESCAPE_STARTS = frozenset(( - '\n', '\\', "'", '"', 'a', 'b', 'f', 'n', 'r', 't', 'v', + '\n', '\r', '\\', "'", '"', 'a', 'b', 'f', 'n', 'r', 't', 'v', '0', '1', '2', '3', '4', '5', '6', '7', # octal escapes 'x', # hex escapes # only valid in non-bytestrings
asottile/pyupgrade
8fd39bbab6e34046300b4f6d7300153e511137ce
diff --git a/tests/pyupgrade_test.py b/tests/pyupgrade_test.py index 82acd34..c571357 100644 --- a/tests/pyupgrade_test.py +++ b/tests/pyupgrade_test.py @@ -343,6 +343,8 @@ def test_unicode_literals(s, py3_plus, expected): '"\\u2603"', # don't touch already valid escapes r'"\r\n"', + # don't touch escaped newlines + '"""\\\n"""', '"""\\\r\n"""', '"""\\\r"""', ), ) def test_fix_escape_sequences_noop(s):
pyupgrade is introducing a raw string where a line continuation is being used. Hi. The pyupgrade tool is introducing a raw string where a line continuation is being used. Check this example below: ```python import textwrap def test_importerror(tmpdir): print(tmpdir) p1 = tmpdir.join("test1.txt") p2 = tmpdir.join("test2.txt") p1.write( textwrap.dedent( """\ import doesnotexist x = 1 """ ) ) p2.write( textwrap.dedent( """ import doesnotexist x = 2 """ ) ) ``` after running pyupgrade on this file, a `r"""` is introduced as it's demonstrated above. ```python def test_importerror(tmpdir): print(tmpdir) p1 = tmpdir.join("test1.txt") p2 = tmpdir.join("test2.txt") p1.write( textwrap.dedent( r"""\ import doesnotexist x = 1 """ ) ) p2.write( textwrap.dedent( """ import doesnotexist x = 2 """ ) ) ``` I'm running `pyupgrade (1.10.0)` with `python Python 3.6.2` on `Windows 10, version 1709`
0.0
8fd39bbab6e34046300b4f6d7300153e511137ce
[ "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\"\"\"]" ]
[ "tests/pyupgrade_test.py::test_roundtrip_text[]", "tests/pyupgrade_test.py::test_roundtrip_text[foo]", "tests/pyupgrade_test.py::test_roundtrip_text[{}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0}]", "tests/pyupgrade_test.py::test_roundtrip_text[{named}]", "tests/pyupgrade_test.py::test_roundtrip_text[{!r}]", "tests/pyupgrade_test.py::test_roundtrip_text[{:>5}]", "tests/pyupgrade_test.py::test_roundtrip_text[{{]", "tests/pyupgrade_test.py::test_roundtrip_text[}}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0!s:15}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/pyupgrade_test.py::test_sets[set()-set()]", "tests/pyupgrade_test.py::test_sets[set((\\n))-set((\\n))]", "tests/pyupgrade_test.py::test_sets[set", "tests/pyupgrade_test.py::test_sets[set(())-set()]", "tests/pyupgrade_test.py::test_sets[set([])-set()]", "tests/pyupgrade_test.py::test_sets[set((", "tests/pyupgrade_test.py::test_sets[set([1,", "tests/pyupgrade_test.py::test_sets[set(x", "tests/pyupgrade_test.py::test_sets[set([(1,", "tests/pyupgrade_test.py::test_sets[set([((1,", "tests/pyupgrade_test.py::test_dictcomps[x", "tests/pyupgrade_test.py::test_dictcomps[dict()-dict()]", "tests/pyupgrade_test.py::test_dictcomps[(-(]", "tests/pyupgrade_test.py::test_dictcomps[dict", "tests/pyupgrade_test.py::test_format_literals['{}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{'.format(1)-'{'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['}'.format(1)-'}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals[x", "tests/pyupgrade_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/pyupgrade_test.py::test_format_literals['{0}'", "tests/pyupgrade_test.py::test_format_literals[print(\\n", "tests/pyupgrade_test.py::test_format_literals['{0:<{1}}'.format(1,", "tests/pyupgrade_test.py::test_imports_unicode_literals[import", "tests/pyupgrade_test.py::test_imports_unicode_literals[from", "tests/pyupgrade_test.py::test_imports_unicode_literals[x", "tests/pyupgrade_test.py::test_imports_unicode_literals[\"\"\"docstring\"\"\"\\nfrom", "tests/pyupgrade_test.py::test_unicode_literals[(-False-(]", "tests/pyupgrade_test.py::test_unicode_literals[u''-False-u'']", "tests/pyupgrade_test.py::test_unicode_literals[u''-True-'']", "tests/pyupgrade_test.py::test_unicode_literals[from", "tests/pyupgrade_test.py::test_unicode_literals[\"\"\"with", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'\\\\d']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\"\"\\\\d\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'''\\\\d''']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[rb\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\r\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\d\"-r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\n\\\\d\"-\"\\\\n\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[u\"\\\\d\"-u\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\d\"-br\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\8\"-r\"\\\\8\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\9\"-r\"\\\\9\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\u2603\"-br\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_noop_octal_literals[0]", "tests/pyupgrade_test.py::test_noop_octal_literals[00]", "tests/pyupgrade_test.py::test_noop_octal_literals[1]", "tests/pyupgrade_test.py::test_noop_octal_literals[12345]", "tests/pyupgrade_test.py::test_noop_octal_literals[1.2345]", "tests/pyupgrade_test.py::test_is_bytestring_true[b'']", "tests/pyupgrade_test.py::test_is_bytestring_true[b\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B'']", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''0]", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''1]", "tests/pyupgrade_test.py::test_is_bytestring_false[]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false['']", "tests/pyupgrade_test.py::test_is_bytestring_false[u\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"b\"]", "tests/pyupgrade_test.py::test_parse_percent_format[\"\"-expected0]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%%\"-expected1]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s\"-expected2]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(hi)s\"-expected4]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%()s\"-expected5]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%#o\"-expected6]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%", "tests/pyupgrade_test.py::test_parse_percent_format[\"%5d\"-expected8]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%*d\"-expected9]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.f\"-expected10]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.5f\"-expected11]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.*f\"-expected12]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%ld\"-expected13]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(complete)#4.4f\"-expected14]", "tests/pyupgrade_test.py::test_percent_to_format[%s-{}]", "tests/pyupgrade_test.py::test_percent_to_format[%%%s-%{}]", "tests/pyupgrade_test.py::test_percent_to_format[%(foo)s-{foo}]", "tests/pyupgrade_test.py::test_percent_to_format[%2f-{:2f}]", "tests/pyupgrade_test.py::test_percent_to_format[%r-{!r}]", "tests/pyupgrade_test.py::test_percent_to_format[%a-{!a}]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[-]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[", "tests/pyupgrade_test.py::test_simplify_conversion_flag[#0-", "tests/pyupgrade_test.py::test_simplify_conversion_flag[--<]", "tests/pyupgrade_test.py::test_percent_format_noop[\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[b\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%d\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%i\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%u\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%c\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%#o\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%()s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%4%\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2r\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2a\"", "tests/pyupgrade_test.py::test_percent_format_noop[i", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(1)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(a)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(ab)s\"", "tests/pyupgrade_test.py::test_percent_format[\"trivial\"", "tests/pyupgrade_test.py::test_percent_format[\"%s%%", "tests/pyupgrade_test.py::test_percent_format[\"%3f\"", "tests/pyupgrade_test.py::test_percent_format[\"%-5s\"", "tests/pyupgrade_test.py::test_percent_format[\"brace", "tests/pyupgrade_test.py::test_percent_format[\"%(k)s\"", "tests/pyupgrade_test.py::test_percent_format[\"%(to_list)s\"", "tests/pyupgrade_test.py::test_fix_super_noop[x(]", "tests/pyupgrade_test.py::test_fix_super_noop[class", "tests/pyupgrade_test.py::test_fix_super_noop[def", "tests/pyupgrade_test.py::test_fix_super[class", "tests/pyupgrade_test.py::test_fix_new_style_classes_noop[x", "tests/pyupgrade_test.py::test_fix_new_style_classes_noop[class", "tests/pyupgrade_test.py::test_fix_new_style_classes[class", "tests/pyupgrade_test.py::test_fix_six_noop[x", "tests/pyupgrade_test.py::test_fix_six_noop[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six_noop[@", "tests/pyupgrade_test.py::test_fix_six_noop[from", "tests/pyupgrade_test.py::test_fix_six_noop[@mydec\\nclass", "tests/pyupgrade_test.py::test_fix_six_noop[six.u", "tests/pyupgrade_test.py::test_fix_six[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six[issubclass(tp,", "tests/pyupgrade_test.py::test_fix_six[STRING_TYPES", "tests/pyupgrade_test.py::test_fix_six[from", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/pyupgrade_test.py::test_fix_six[six.get_unbound_method(meth)\\n-meth\\n]", "tests/pyupgrade_test.py::test_fix_six[six.indexbytes(bs,", "tests/pyupgrade_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/pyupgrade_test.py::test_fix_new_style_classes_py3only[class", "tests/pyupgrade_test.py::test_fix_fstrings_noop[(]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\"", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{foo}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{0}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[b\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{1}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{.x}", "tests/pyupgrade_test.py::test_fix_fstrings[\"hello", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped,", "tests/pyupgrade_test.py::test_main_trivial", "tests/pyupgrade_test.py::test_main_noop", "tests/pyupgrade_test.py::test_main_syntax_error", "tests/pyupgrade_test.py::test_main_non_utf8_bytes", "tests/pyupgrade_test.py::test_keep_percent_format", "tests/pyupgrade_test.py::test_py3_plus_argument_unicode_literals", "tests/pyupgrade_test.py::test_py3_plus_super", "tests/pyupgrade_test.py::test_py3_plus_new_style_classes", "tests/pyupgrade_test.py::test_py36_plus_fstrings" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2018-10-31 20:14:16+00:00
mit
1,183
asottile__pyupgrade-84
diff --git a/pyupgrade.py b/pyupgrade.py index 66e1094..18345dc 100644 --- a/pyupgrade.py +++ b/pyupgrade.py @@ -609,6 +609,8 @@ def _percent_to_format(s): if conversion == '%': return s + '%' parts = [s, '{'] + if width and conversion == 's' and not conversion_flag: + conversion_flag = '>' if conversion == 's': conversion = None if key:
asottile/pyupgrade
bbe34c45db1fa1c54969f590fc35571a636132b4
diff --git a/tests/pyupgrade_test.py b/tests/pyupgrade_test.py index ad9d751..3818f20 100644 --- a/tests/pyupgrade_test.py +++ b/tests/pyupgrade_test.py @@ -615,6 +615,7 @@ def test_percent_format_noop_if_bug_16806(): ('"%s%% percent" % (15,)', '"{}% percent".format(15)'), ('"%3f" % (15,)', '"{:3f}".format(15)'), ('"%-5s" % ("hi",)', '"{:<5}".format("hi")'), + ('"%9s" % (5,)', '"{:>9}".format(5)'), ('"brace {} %s" % (1,)', '"brace {{}} {}".format(1)'), ( '"%s" % (\n'
Behaviour change after upgrading '%9s' to '{:9}' This pyupgrade change (https://github.com/hugovk/yamllint/commit/25e8e9be0838bff930b3b204360fc24385b6edbf) fails indentation-related unit tests which previously passed: ```diff - output += '%9s %s\n' % (token_type, + output += '{:9} {}\n'.format(token_type, self.format_stack(context['stack'])) ``` https://travis-ci.org/hugovk/yamllint/jobs/459076859#L860 Small example: ```python Python 3.7.1 (default, Nov 6 2018, 18:45:35) [Clang 10.0.0 (clang-1000.11.45.5)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> '%9s %s\n' % ("abc", "def") ' abc def\n' >>> '{:9} {}\n'.format("abc", "def") 'abc def\n' ``` It would have worked if they were integers: ```python >>> '%9s %s\n' % (123, 456) ' 123 456\n' >>> '{:9} {}\n'.format(123, 456) ' 123 456\n' ``` --- Another issue with this example, it'd be nice if the indentation of the second line was adjusted, as this often causes flake8 errors. But I understand if this is out of scope of pyupgrade. For example, instead of this: ```diff - output += '%9s %s\n' % (token_type, + output += '{:9} {}\n'.format(token_type, self.format_stack(context['stack'])) ``` Do this: ```diff - output += '%9s %s\n' % (token_type, - self.format_stack(context['stack'])) + output += '{:9} {}\n'.format(token_type, + self.format_stack(context['stack'])) ```
0.0
bbe34c45db1fa1c54969f590fc35571a636132b4
[ "tests/pyupgrade_test.py::test_percent_format[\"%9s\"" ]
[ "tests/pyupgrade_test.py::test_roundtrip_text[]", "tests/pyupgrade_test.py::test_roundtrip_text[foo]", "tests/pyupgrade_test.py::test_roundtrip_text[{}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0}]", "tests/pyupgrade_test.py::test_roundtrip_text[{named}]", "tests/pyupgrade_test.py::test_roundtrip_text[{!r}]", "tests/pyupgrade_test.py::test_roundtrip_text[{:>5}]", "tests/pyupgrade_test.py::test_roundtrip_text[{{]", "tests/pyupgrade_test.py::test_roundtrip_text[}}]", "tests/pyupgrade_test.py::test_roundtrip_text[{0!s:15}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{:}-{}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0:}-{0}]", "tests/pyupgrade_test.py::test_intentionally_not_round_trip[{0!r:}-{0!r}]", "tests/pyupgrade_test.py::test_sets[set()-set()]", "tests/pyupgrade_test.py::test_sets[set((\\n))-set((\\n))]", "tests/pyupgrade_test.py::test_sets[set", "tests/pyupgrade_test.py::test_sets[set(())-set()]", "tests/pyupgrade_test.py::test_sets[set([])-set()]", "tests/pyupgrade_test.py::test_sets[set((", "tests/pyupgrade_test.py::test_sets[set([1,", "tests/pyupgrade_test.py::test_sets[set(x", "tests/pyupgrade_test.py::test_sets[set([(1,", "tests/pyupgrade_test.py::test_sets[set([((1,", "tests/pyupgrade_test.py::test_dictcomps[x", "tests/pyupgrade_test.py::test_dictcomps[dict()-dict()]", "tests/pyupgrade_test.py::test_dictcomps[(-(]", "tests/pyupgrade_test.py::test_dictcomps[dict", "tests/pyupgrade_test.py::test_format_literals[\"{0}\"format(1)-\"{0}\"format(1)]", "tests/pyupgrade_test.py::test_format_literals['{}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{'.format(1)-'{'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['}'.format(1)-'}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals[x", "tests/pyupgrade_test.py::test_format_literals['{0}", "tests/pyupgrade_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/pyupgrade_test.py::test_format_literals['{0:x}'.format(30)-'{:x}'.format(30)]", "tests/pyupgrade_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/pyupgrade_test.py::test_format_literals['{0}'", "tests/pyupgrade_test.py::test_format_literals[print(\\n", "tests/pyupgrade_test.py::test_format_literals['{0:<{1}}'.format(1,", "tests/pyupgrade_test.py::test_imports_unicode_literals[import", "tests/pyupgrade_test.py::test_imports_unicode_literals[from", "tests/pyupgrade_test.py::test_imports_unicode_literals[x", "tests/pyupgrade_test.py::test_imports_unicode_literals[\"\"\"docstring\"\"\"\\nfrom", "tests/pyupgrade_test.py::test_unicode_literals[(-False-(]", "tests/pyupgrade_test.py::test_unicode_literals[u''-False-u'']", "tests/pyupgrade_test.py::test_unicode_literals[u''-True-'']", "tests/pyupgrade_test.py::test_unicode_literals[from", "tests/pyupgrade_test.py::test_unicode_literals[\"\"\"with", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'\\\\d']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r\"\"\"\\\\d\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[r'''\\\\d''']", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[rb\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\\\\r\\\\n\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\\n\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences_noop[\"\"\"\\\\\\r\"\"\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\d\"-r\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\n\\\\d\"-\"\\\\n\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[u\"\\\\d\"-u\"\\\\\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\d\"-br\"\\\\d\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\8\"-r\"\\\\8\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[\"\\\\9\"-r\"\\\\9\"]", "tests/pyupgrade_test.py::test_fix_escape_sequences[b\"\\\\u2603\"-br\"\\\\u2603\"]", "tests/pyupgrade_test.py::test_noop_octal_literals[0]", "tests/pyupgrade_test.py::test_noop_octal_literals[00]", "tests/pyupgrade_test.py::test_noop_octal_literals[1]", "tests/pyupgrade_test.py::test_noop_octal_literals[12345]", "tests/pyupgrade_test.py::test_noop_octal_literals[1.2345]", "tests/pyupgrade_test.py::test_is_bytestring_true[b'']", "tests/pyupgrade_test.py::test_is_bytestring_true[b\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_true[B'']", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''0]", "tests/pyupgrade_test.py::test_is_bytestring_true[rb''1]", "tests/pyupgrade_test.py::test_is_bytestring_false[]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false['']", "tests/pyupgrade_test.py::test_is_bytestring_false[u\"\"]", "tests/pyupgrade_test.py::test_is_bytestring_false[\"b\"]", "tests/pyupgrade_test.py::test_parse_percent_format[\"\"-expected0]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%%\"-expected1]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s\"-expected2]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%s", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(hi)s\"-expected4]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%()s\"-expected5]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%#o\"-expected6]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%", "tests/pyupgrade_test.py::test_parse_percent_format[\"%5d\"-expected8]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%*d\"-expected9]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.f\"-expected10]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.5f\"-expected11]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%.*f\"-expected12]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%ld\"-expected13]", "tests/pyupgrade_test.py::test_parse_percent_format[\"%(complete)#4.4f\"-expected14]", "tests/pyupgrade_test.py::test_percent_to_format[%s-{}]", "tests/pyupgrade_test.py::test_percent_to_format[%%%s-%{}]", "tests/pyupgrade_test.py::test_percent_to_format[%(foo)s-{foo}]", "tests/pyupgrade_test.py::test_percent_to_format[%2f-{:2f}]", "tests/pyupgrade_test.py::test_percent_to_format[%r-{!r}]", "tests/pyupgrade_test.py::test_percent_to_format[%a-{!a}]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[-]", "tests/pyupgrade_test.py::test_simplify_conversion_flag[", "tests/pyupgrade_test.py::test_simplify_conversion_flag[#0-", "tests/pyupgrade_test.py::test_simplify_conversion_flag[--<]", "tests/pyupgrade_test.py::test_percent_format_noop[\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[b\"%s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.*s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%d\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%i\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%u\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%c\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%#o\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%()s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%4%\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2r\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%.2a\"", "tests/pyupgrade_test.py::test_percent_format_noop[i", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(1)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(a)s\"", "tests/pyupgrade_test.py::test_percent_format_noop[\"%(ab)s\"", "tests/pyupgrade_test.py::test_percent_format[\"trivial\"", "tests/pyupgrade_test.py::test_percent_format[\"%s%%", "tests/pyupgrade_test.py::test_percent_format[\"%3f\"", "tests/pyupgrade_test.py::test_percent_format[\"%-5s\"", "tests/pyupgrade_test.py::test_percent_format[\"brace", "tests/pyupgrade_test.py::test_percent_format[\"%(k)s\"", "tests/pyupgrade_test.py::test_percent_format[\"%(to_list)s\"", "tests/pyupgrade_test.py::test_fix_super_noop[x(]", "tests/pyupgrade_test.py::test_fix_super_noop[class", "tests/pyupgrade_test.py::test_fix_super_noop[def", "tests/pyupgrade_test.py::test_fix_super[class", "tests/pyupgrade_test.py::test_fix_new_style_classes_noop[x", "tests/pyupgrade_test.py::test_fix_new_style_classes_noop[class", "tests/pyupgrade_test.py::test_fix_new_style_classes[class", "tests/pyupgrade_test.py::test_fix_six_noop[x", "tests/pyupgrade_test.py::test_fix_six_noop[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six_noop[@", "tests/pyupgrade_test.py::test_fix_six_noop[from", "tests/pyupgrade_test.py::test_fix_six_noop[@mydec\\nclass", "tests/pyupgrade_test.py::test_fix_six_noop[six.u", "tests/pyupgrade_test.py::test_fix_six_noop[six.raise_from", "tests/pyupgrade_test.py::test_fix_six_noop[print(six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six[isinstance(s,", "tests/pyupgrade_test.py::test_fix_six[issubclass(tp,", "tests/pyupgrade_test.py::test_fix_six[STRING_TYPES", "tests/pyupgrade_test.py::test_fix_six[from", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\nclass", "tests/pyupgrade_test.py::test_fix_six[@six.python_2_unicode_compatible\\n@other_decorator\\nclass", "tests/pyupgrade_test.py::test_fix_six[six.get_unbound_method(meth)\\n-meth\\n]", "tests/pyupgrade_test.py::test_fix_six[six.indexbytes(bs,", "tests/pyupgrade_test.py::test_fix_six[six.assertCountEqual(\\n", "tests/pyupgrade_test.py::test_fix_six[six.raise_from(exc,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(tp,", "tests/pyupgrade_test.py::test_fix_six[six.reraise(\\n", "tests/pyupgrade_test.py::test_fix_new_style_classes_py3only[class", "tests/pyupgrade_test.py::test_fix_fstrings_noop[(]", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\"", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}\".format(\\n", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{foo}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{0}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{x.y}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[b\"{}", "tests/pyupgrade_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x,", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{1}", "tests/pyupgrade_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]", "tests/pyupgrade_test.py::test_fix_fstrings[\"{.x}", "tests/pyupgrade_test.py::test_fix_fstrings[\"hello", "tests/pyupgrade_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped,", "tests/pyupgrade_test.py::test_main_trivial", "tests/pyupgrade_test.py::test_main_noop", "tests/pyupgrade_test.py::test_main_syntax_error", "tests/pyupgrade_test.py::test_main_non_utf8_bytes", "tests/pyupgrade_test.py::test_keep_percent_format", "tests/pyupgrade_test.py::test_py3_plus_argument_unicode_literals", "tests/pyupgrade_test.py::test_py3_plus_super", "tests/pyupgrade_test.py::test_py3_plus_new_style_classes", "tests/pyupgrade_test.py::test_py36_plus_fstrings" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2018-11-24 23:46:51+00:00
mit
1,184
asottile__pyupgrade-855
diff --git a/README.md b/README.md index 0ad6edd..e750447 100644 --- a/README.md +++ b/README.md @@ -634,6 +634,15 @@ Availability: ... ``` +### shlex.join + +Availability: +- `--py38-plus` is passed on the commandline. + +```diff +-' '.join(shlex.quote(arg) for arg in cmd) ++shlex.join(cmd) +``` ### replace `@functools.lru_cache(maxsize=None)` with shorthand diff --git a/pyupgrade/_plugins/shlex_join.py b/pyupgrade/_plugins/shlex_join.py new file mode 100644 index 0000000..3b5410e --- /dev/null +++ b/pyupgrade/_plugins/shlex_join.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +import ast +import functools +from typing import Iterable + +from tokenize_rt import NON_CODING_TOKENS +from tokenize_rt import Offset +from tokenize_rt import Token + +from pyupgrade._ast_helpers import ast_to_offset +from pyupgrade._data import register +from pyupgrade._data import State +from pyupgrade._data import TokenFunc +from pyupgrade._token_helpers import find_open_paren +from pyupgrade._token_helpers import find_token +from pyupgrade._token_helpers import victims + + +def _fix_shlex_join(i: int, tokens: list[Token], *, arg: ast.expr) -> None: + j = find_open_paren(tokens, i) + comp_victims = victims(tokens, j, arg, gen=True) + k = find_token(tokens, comp_victims.arg_index, 'in') + 1 + while tokens[k].name in NON_CODING_TOKENS: + k += 1 + tokens[comp_victims.ends[0]:comp_victims.ends[-1] + 1] = [Token('OP', ')')] + tokens[i:k] = [Token('CODE', 'shlex.join'), Token('OP', '(')] + + +@register(ast.Call) +def visit_Call( + state: State, + node: ast.Call, + parent: ast.AST, +) -> Iterable[tuple[Offset, TokenFunc]]: + if state.settings.min_version < (3, 8): + return + + if ( + isinstance(node.func, ast.Attribute) and + isinstance(node.func.value, ast.Constant) and + isinstance(node.func.value.value, str) and + node.func.attr == 'join' and + not node.keywords and + len(node.args) == 1 and + isinstance(node.args[0], (ast.ListComp, ast.GeneratorExp)) and + isinstance(node.args[0].elt, ast.Call) and + isinstance(node.args[0].elt.func, ast.Attribute) and + isinstance(node.args[0].elt.func.value, ast.Name) and + node.args[0].elt.func.value.id == 'shlex' and + node.args[0].elt.func.attr == 'quote' and + not node.args[0].elt.keywords and + len(node.args[0].elt.args) == 1 and + isinstance(node.args[0].elt.args[0], ast.Name) and + len(node.args[0].generators) == 1 and + isinstance(node.args[0].generators[0].target, ast.Name) and + not node.args[0].generators[0].ifs and + not node.args[0].generators[0].is_async and + node.args[0].elt.args[0].id == node.args[0].generators[0].target.id + ): + func = functools.partial(_fix_shlex_join, arg=node.args[0]) + yield ast_to_offset(node), func
asottile/pyupgrade
908b05599f2dc730dfb6b7c6e4c3e5b8ad639536
diff --git a/tests/features/shlex_join_test.py b/tests/features/shlex_join_test.py new file mode 100644 index 0000000..fc6abe5 --- /dev/null +++ b/tests/features/shlex_join_test.py @@ -0,0 +1,72 @@ +from __future__ import annotations + +import pytest + +from pyupgrade._data import Settings +from pyupgrade._main import _fix_plugins + + [email protected]( + ('s', 'version'), + ( + pytest.param( + 'from shlex import quote\n' + '" ".join(quote(arg) for arg in cmd)\n', + (3, 8), + id='quote from-imported', + ), + pytest.param( + 'import shlex\n' + '" ".join(shlex.quote(arg) for arg in cmd)\n', + (3, 7), + id='3.8+ feature', + ), + ), +) +def test_shlex_join_noop(s, version): + assert _fix_plugins(s, settings=Settings(min_version=version)) == s + + [email protected]( + ('s', 'expected'), + ( + pytest.param( + 'import shlex\n' + '" ".join(shlex.quote(arg) for arg in cmd)\n', + + 'import shlex\n' + 'shlex.join(cmd)\n', + + id='generator expression', + ), + pytest.param( + 'import shlex\n' + '" ".join([shlex.quote(arg) for arg in cmd])\n', + + 'import shlex\n' + 'shlex.join(cmd)\n', + + id='list comprehension', + ), + pytest.param( + 'import shlex\n' + '" ".join([shlex.quote(arg) for arg in cmd],)\n', + + 'import shlex\n' + 'shlex.join(cmd)\n', + + id='removes trailing comma', + ), + pytest.param( + 'import shlex\n' + '" ".join([shlex.quote(arg) for arg in ["a", "b", "c"]],)\n', + + 'import shlex\n' + 'shlex.join(["a", "b", "c"])\n', + + id='more complicated iterable', + ), + ), +) +def test_shlex_join_fixes(s, expected): + assert _fix_plugins(s, settings=Settings(min_version=(3, 8))) == expected
' '.join(shlex.quote(arg) for arg in cmd) => shelx.quote(cmd) `--py38-plus` -- this one might be tricky!
0.0
908b05599f2dc730dfb6b7c6e4c3e5b8ad639536
[ "tests/features/shlex_join_test.py::test_shlex_join_fixes[generator", "tests/features/shlex_join_test.py::test_shlex_join_fixes[list", "tests/features/shlex_join_test.py::test_shlex_join_fixes[removes", "tests/features/shlex_join_test.py::test_shlex_join_fixes[more" ]
[ "tests/features/shlex_join_test.py::test_shlex_join_noop[quote", "tests/features/shlex_join_test.py::test_shlex_join_noop[3.8+" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_added_files" ], "has_test_patch": true, "is_lite": false }
2023-07-03 17:16:39+00:00
mit
1,185
asottile__pyupgrade-890
diff --git a/pyupgrade/_string_helpers.py b/pyupgrade/_string_helpers.py index 4271839..1c15655 100644 --- a/pyupgrade/_string_helpers.py +++ b/pyupgrade/_string_helpers.py @@ -19,7 +19,7 @@ def parse_format(s: str) -> list[DotFormatPart]: for part in NAMED_UNICODE_RE.split(s): if NAMED_UNICODE_RE.fullmatch(part): - if not ret: + if not ret or ret[-1][1:] != (None, None, None): ret.append((part, None, None, None)) else: ret[-1] = (ret[-1][0] + part, None, None, None)
asottile/pyupgrade
a61ea875545997641089caf87b9f1cf623d059fe
diff --git a/tests/features/format_literals_test.py b/tests/features/format_literals_test.py index aaa6ef0..837e593 100644 --- a/tests/features/format_literals_test.py +++ b/tests/features/format_literals_test.py @@ -25,6 +25,8 @@ from pyupgrade._main import _fix_tokens '("{0}" # {1}\n"{2}").format(1, 2, 3)', # don't touch f-strings (these are wrong but don't make it worse) 'f"{0}".format(a)', + # shouldn't touch the format spec + r'"{}\N{SNOWMAN}".format("")', ), ) def test_format_literals_noop(s):
Error after upgrading a formatted sting starting with a variable If I run pyupgrade on this string : **'{}\N{NO-BREAK SPACE}'.format(currency.symbol or "")** I get this line as an output : "\N{NO-BREAK SPACE}".format(currency.symbol or "") Wich causes an error
0.0
a61ea875545997641089caf87b9f1cf623d059fe
[ "tests/features/format_literals_test.py::test_format_literals_noop[\"{}\\\\N{SNOWMAN}\".format(\"\")]" ]
[ "tests/features/format_literals_test.py::test_format_literals_noop[\"{0}\"format(1)]", "tests/features/format_literals_test.py::test_format_literals_noop[already", "tests/features/format_literals_test.py::test_format_literals_noop['{'.format(1)]", "tests/features/format_literals_test.py::test_format_literals_noop['}'.format(1)]", "tests/features/format_literals_test.py::test_format_literals_noop[x", "tests/features/format_literals_test.py::test_format_literals_noop['{0}", "tests/features/format_literals_test.py::test_format_literals_noop['{0:<{1}}'.format(1,", "tests/features/format_literals_test.py::test_format_literals_noop['{'", "tests/features/format_literals_test.py::test_format_literals_noop[(\"{0}\"", "tests/features/format_literals_test.py::test_format_literals_noop[f\"{0}\".format(a)]", "tests/features/format_literals_test.py::test_format_literals['{0}'.format(1)-'{}'.format(1)]", "tests/features/format_literals_test.py::test_format_literals['{0:x}'.format(30)-'{:x}'.format(30)]", "tests/features/format_literals_test.py::test_format_literals[x", "tests/features/format_literals_test.py::test_format_literals['''{0}\\n{1}\\n'''.format(1,", "tests/features/format_literals_test.py::test_format_literals['{0}'", "tests/features/format_literals_test.py::test_format_literals[print(\\n", "tests/features/format_literals_test.py::test_format_literals[(\"{0}\").format(1)-(\"{}\").format(1)]", "tests/features/format_literals_test.py::test_format_literals[named" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2023-09-19 17:57:57+00:00
mit
1,186
asottile__pyupgrade-898
diff --git a/README.md b/README.md index e1b4caf..9576436 100644 --- a/README.md +++ b/README.md @@ -154,6 +154,22 @@ A fix for [python-modernize/python-modernize#178] [python-modernize/python-modernize#178]: https://github.com/python-modernize/python-modernize/issues/178 +### constant fold `isinstance` / `issubclass` / `except` + +```diff +-isinstance(x, (int, int)) ++isinstance(x, int) + +-issubclass(y, (str, str)) ++issubclass(y, str) + + try: + raises() +-except (Error1, Error1, Error2): ++except (Error1, Error2): + pass +``` + ### unittest deprecated aliases Rewrites [deprecated unittest method aliases](https://docs.python.org/3/library/unittest.html#deprecated-aliases) to their non-deprecated forms. diff --git a/pyupgrade/_ast_helpers.py b/pyupgrade/_ast_helpers.py index 9bcd981..8a79d3a 100644 --- a/pyupgrade/_ast_helpers.py +++ b/pyupgrade/_ast_helpers.py @@ -56,3 +56,13 @@ def is_async_listcomp(node: ast.ListComp) -> bool: any(gen.is_async for gen in node.generators) or contains_await(node) ) + + +def is_type_check(node: ast.AST) -> bool: + return ( + isinstance(node, ast.Call) and + isinstance(node.func, ast.Name) and + node.func.id in {'isinstance', 'issubclass'} and + len(node.args) == 2 and + not has_starargs(node) + ) diff --git a/pyupgrade/_plugins/constant_fold.py b/pyupgrade/_plugins/constant_fold.py new file mode 100644 index 0000000..07c3de5 --- /dev/null +++ b/pyupgrade/_plugins/constant_fold.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +import ast +from typing import Iterable + +from tokenize_rt import Offset + +from pyupgrade._ast_helpers import ast_to_offset +from pyupgrade._ast_helpers import is_type_check +from pyupgrade._data import register +from pyupgrade._data import State +from pyupgrade._data import TokenFunc +from pyupgrade._token_helpers import constant_fold_tuple + + +def _to_name(node: ast.AST) -> str | None: + if isinstance(node, ast.Name): + return node.id + elif isinstance(node, ast.Attribute): + base = _to_name(node.value) + if base is None: + return None + else: + return f'{base}.{node.attr}' + else: + return None + + +def _can_constant_fold(node: ast.Tuple) -> bool: + seen = set() + for el in node.elts: + name = _to_name(el) + if name is not None: + if name in seen: + return True + else: + seen.add(name) + else: + return False + + +def _cbs(node: ast.AST | None) -> Iterable[tuple[Offset, TokenFunc]]: + if isinstance(node, ast.Tuple) and _can_constant_fold(node): + yield ast_to_offset(node), constant_fold_tuple + + +@register(ast.Call) +def visit_Call( + state: State, + node: ast.Call, + parent: ast.AST, +) -> Iterable[tuple[Offset, TokenFunc]]: + if is_type_check(node): + yield from _cbs(node.args[1]) + + +@register(ast.Try) +def visit_Try( + state: State, + node: ast.Try, + parent: ast.AST, +) -> Iterable[tuple[Offset, TokenFunc]]: + for handler in node.handlers: + yield from _cbs(handler.type) diff --git a/pyupgrade/_plugins/exceptions.py b/pyupgrade/_plugins/exceptions.py index 64dabd6..37b39fa 100644 --- a/pyupgrade/_plugins/exceptions.py +++ b/pyupgrade/_plugins/exceptions.py @@ -13,7 +13,7 @@ from pyupgrade._data import register from pyupgrade._data import State from pyupgrade._data import TokenFunc from pyupgrade._data import Version -from pyupgrade._token_helpers import arg_str +from pyupgrade._token_helpers import constant_fold_tuple from pyupgrade._token_helpers import find_op from pyupgrade._token_helpers import parse_call_args from pyupgrade._token_helpers import replace_name @@ -45,34 +45,13 @@ def _fix_except( *, at_idx: dict[int, _Target], ) -> None: - # find all the arg strs in the tuple - except_index = i - while tokens[except_index].src != 'except': - except_index -= 1 - start = find_op(tokens, except_index, '(') + start = find_op(tokens, i, '(') func_args, end = parse_call_args(tokens, start) - arg_strs = [arg_str(tokens, *arg) for arg in func_args] + for i, target in reversed(at_idx.items()): + tokens[slice(*func_args[i])] = [Token('NAME', target.target)] - # rewrite the block without dupes - args = [] - for i, arg in enumerate(arg_strs): - target = at_idx.get(i) - if target is not None: - args.append(target.target) - else: - args.append(arg) - - unique_args = tuple(dict.fromkeys(args)) - - if len(unique_args) > 1: - joined = '({})'.format(', '.join(unique_args)) - elif tokens[start - 1].name != 'UNIMPORTANT_WS': - joined = f' {unique_args[0]}' - else: - joined = unique_args[0] - - tokens[start:end] = [Token('CODE', joined)] + constant_fold_tuple(start, tokens) def _get_rewrite( diff --git a/pyupgrade/_plugins/six_simple.py b/pyupgrade/_plugins/six_simple.py index e583a7b..d490d9e 100644 --- a/pyupgrade/_plugins/six_simple.py +++ b/pyupgrade/_plugins/six_simple.py @@ -7,6 +7,7 @@ from typing import Iterable from tokenize_rt import Offset from pyupgrade._ast_helpers import ast_to_offset +from pyupgrade._ast_helpers import is_type_check from pyupgrade._data import register from pyupgrade._data import State from pyupgrade._data import TokenFunc @@ -36,14 +37,6 @@ NAMES_TYPE_CTX = { } -def _is_type_check(node: ast.AST | None) -> bool: - return ( - isinstance(node, ast.Call) and - isinstance(node.func, ast.Name) and - node.func.id in {'isinstance', 'issubclass'} - ) - - @register(ast.Attribute) def visit_Attribute( state: State, @@ -62,7 +55,7 @@ def visit_Attribute( ): return - if node.attr in NAMES_TYPE_CTX and _is_type_check(parent): + if node.attr in NAMES_TYPE_CTX and is_type_check(parent): new = NAMES_TYPE_CTX[node.attr] else: new = NAMES[node.attr] @@ -106,7 +99,7 @@ def visit_Name( ): return - if node.id in NAMES_TYPE_CTX and _is_type_check(parent): + if node.id in NAMES_TYPE_CTX and is_type_check(parent): new = NAMES_TYPE_CTX[node.id] else: new = NAMES[node.id] diff --git a/pyupgrade/_token_helpers.py b/pyupgrade/_token_helpers.py index 3d28bc7..5936ab7 100644 --- a/pyupgrade/_token_helpers.py +++ b/pyupgrade/_token_helpers.py @@ -470,6 +470,23 @@ def replace_argument( tokens[start_idx:end_idx] = [Token('SRC', new)] +def constant_fold_tuple(i: int, tokens: list[Token]) -> None: + start = find_op(tokens, i, '(') + func_args, end = parse_call_args(tokens, start) + arg_strs = [arg_str(tokens, *arg) for arg in func_args] + + unique_args = tuple(dict.fromkeys(arg_strs)) + + if len(unique_args) > 1: + joined = '({})'.format(', '.join(unique_args)) + elif tokens[start - 1].name != 'UNIMPORTANT_WS': + joined = f' {unique_args[0]}' + else: + joined = unique_args[0] + + tokens[start:end] = [Token('CODE', joined)] + + def has_space_before(i: int, tokens: list[Token]) -> bool: return i >= 1 and tokens[i - 1].name in {UNIMPORTANT_WS, 'INDENT'}
asottile/pyupgrade
0d46cba772a6968e3c8c024d340a675ff88c9f8a
diff --git a/tests/features/constant_fold_test.py b/tests/features/constant_fold_test.py new file mode 100644 index 0000000..142ab02 --- /dev/null +++ b/tests/features/constant_fold_test.py @@ -0,0 +1,91 @@ +from __future__ import annotations + +import pytest + +from pyupgrade._data import Settings +from pyupgrade._main import _fix_plugins + + [email protected]( + 's', + ( + pytest.param( + 'isinstance(x, str)', + id='isinstance nothing duplicated', + ), + pytest.param( + 'issubclass(x, str)', + id='issubclass nothing duplicated', + ), + pytest.param( + 'try: ...\n' + 'except Exception: ...\n', + id='try-except nothing duplicated', + ), + pytest.param( + 'isinstance(x, (str, (str,)))', + id='only consider flat tuples', + ), + pytest.param( + 'isinstance(x, (f(), a().g))', + id='only consider names and dotted names', + ), + ), +) +def test_constant_fold_noop(s): + assert _fix_plugins(s, settings=Settings()) == s + + [email protected]( + ('s', 'expected'), + ( + pytest.param( + 'isinstance(x, (str, str, int))', + + 'isinstance(x, (str, int))', + + id='isinstance', + ), + pytest.param( + 'issubclass(x, (str, str, int))', + + 'issubclass(x, (str, int))', + + id='issubclass', + ), + pytest.param( + 'try: ...\n' + 'except (Exception, Exception, TypeError): ...\n', + + 'try: ...\n' + 'except (Exception, TypeError): ...\n', + + id='except', + ), + + pytest.param( + 'isinstance(x, (str, str))', + + 'isinstance(x, str)', + + id='folds to 1', + ), + + pytest.param( + 'isinstance(x, (a.b, a.b, a.c))', + 'isinstance(x, (a.b, a.c))', + id='folds dotted names', + ), + pytest.param( + 'try: ...\n' + 'except(a, a): ...\n', + + 'try: ...\n' + 'except a: ...\n', + + id='deduplication to 1 does not cause syntax error with except', + ), + ), +) +def test_constant_fold(s, expected): + assert _fix_plugins(s, settings=Settings()) == expected
constant fold isinstance(x, (str, str)) input ```python import ham, value import six if isinstance(value, (six.text_type, str)): ham() ``` actual output (with pyupgrade --py38-plus) ```python import ham, value import six if isinstance(value, (str, str)): ham() ``` expected output: ```python import ham, value import six if isinstance(value, str): ham() ```
0.0
0d46cba772a6968e3c8c024d340a675ff88c9f8a
[ "tests/features/constant_fold_test.py::test_constant_fold[isinstance]", "tests/features/constant_fold_test.py::test_constant_fold[issubclass]", "tests/features/constant_fold_test.py::test_constant_fold[except]", "tests/features/constant_fold_test.py::test_constant_fold[folds", "tests/features/constant_fold_test.py::test_constant_fold[deduplication" ]
[ "tests/features/constant_fold_test.py::test_constant_fold_noop[isinstance", "tests/features/constant_fold_test.py::test_constant_fold_noop[issubclass", "tests/features/constant_fold_test.py::test_constant_fold_noop[try-except", "tests/features/constant_fold_test.py::test_constant_fold_noop[only" ]
{ "failed_lite_validators": [ "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-09-23 20:14:46+00:00
mit
1,187
asottile__pyupgrade-901
diff --git a/README.md b/README.md index 410100d..b7c5ca5 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,32 @@ Sample `.pre-commit-config.yaml`: +{a: b for a, b in y} ``` +### Replace unnecessary lambdas in `collections.defaultdict` calls + +```diff +-defaultdict(lambda: []) ++defaultdict(list) +-defaultdict(lambda: list()) ++defaultdict(list) +-defaultdict(lambda: {}) ++defaultdict(dict) +-defaultdict(lambda: dict()) ++defaultdict(dict) +-defaultdict(lambda: ()) ++defaultdict(tuple) +-defaultdict(lambda: tuple()) ++defaultdict(tuple) +-defaultdict(lambda: set()) ++defaultdict(set) +-defaultdict(lambda: 0) ++defaultdict(int) +-defaultdict(lambda: 0.0) ++defaultdict(float) +-defaultdict(lambda: 0j) ++defaultdict(complex) +-defaultdict(lambda: '') ++defaultdict(str) +``` ### Format Specifiers diff --git a/pyupgrade/_data.py b/pyupgrade/_data.py index ee54b3f..ab3a494 100644 --- a/pyupgrade/_data.py +++ b/pyupgrade/_data.py @@ -39,6 +39,7 @@ ASTFunc = Callable[[State, AST_T, ast.AST], Iterable[Tuple[Offset, TokenFunc]]] RECORD_FROM_IMPORTS = frozenset(( '__future__', 'asyncio', + 'collections', 'functools', 'mmap', 'os', diff --git a/pyupgrade/_plugins/defauldict_lambda.py b/pyupgrade/_plugins/defauldict_lambda.py new file mode 100644 index 0000000..1cfa746 --- /dev/null +++ b/pyupgrade/_plugins/defauldict_lambda.py @@ -0,0 +1,81 @@ +from __future__ import annotations + +import ast +import functools +from typing import Iterable + +from tokenize_rt import Offset +from tokenize_rt import Token + +from pyupgrade._ast_helpers import ast_to_offset +from pyupgrade._ast_helpers import is_name_attr +from pyupgrade._data import register +from pyupgrade._data import State +from pyupgrade._data import TokenFunc +from pyupgrade._token_helpers import find_op +from pyupgrade._token_helpers import parse_call_args + + +def _eligible_lambda_replacement(lambda_expr: ast.Lambda) -> str | None: + if isinstance(lambda_expr.body, ast.Constant): + if lambda_expr.body.value == 0: + return type(lambda_expr.body.value).__name__ + elif lambda_expr.body.value == '': + return 'str' + else: + return None + elif isinstance(lambda_expr.body, ast.List) and not lambda_expr.body.elts: + return 'list' + elif isinstance(lambda_expr.body, ast.Tuple) and not lambda_expr.body.elts: + return 'tuple' + elif isinstance(lambda_expr.body, ast.Dict) and not lambda_expr.body.keys: + return 'dict' + elif ( + isinstance(lambda_expr.body, ast.Call) and + isinstance(lambda_expr.body.func, ast.Name) and + not lambda_expr.body.args and + not lambda_expr.body.keywords and + lambda_expr.body.func.id in {'dict', 'list', 'set', 'tuple'} + ): + return lambda_expr.body.func.id + else: + return None + + +def _fix_defaultdict_first_arg( + i: int, + tokens: list[Token], + *, + replacement: str, +) -> None: + start = find_op(tokens, i, '(') + func_args, end = parse_call_args(tokens, start) + + tokens[slice(*func_args[0])] = [Token('CODE', replacement)] + + +@register(ast.Call) +def visit_Call( + state: State, + node: ast.Call, + parent: ast.AST, +) -> Iterable[tuple[Offset, TokenFunc]]: + if ( + is_name_attr( + node.func, + state.from_imports, + ('collections',), + ('defaultdict',), + ) and + node.args and + isinstance(node.args[0], ast.Lambda) + ): + replacement = _eligible_lambda_replacement(node.args[0]) + if replacement is None: + return + + func = functools.partial( + _fix_defaultdict_first_arg, + replacement=replacement, + ) + yield ast_to_offset(node), func
asottile/pyupgrade
72041b1e37bb793b00ee45132c1a5c3e7afd84bd
diff --git a/tests/features/defauldict_lambda_test.py b/tests/features/defauldict_lambda_test.py new file mode 100644 index 0000000..241d5cb --- /dev/null +++ b/tests/features/defauldict_lambda_test.py @@ -0,0 +1,220 @@ +from __future__ import annotations + +import pytest + +from pyupgrade._data import Settings +from pyupgrade._main import _fix_plugins + + [email protected]( + ('s',), + ( + pytest.param( + 'from collections import defaultdict as dd\n\n' + 'dd(lambda: set())\n', + id='not following as imports', + ), + pytest.param( + 'from collections2 import defaultdict\n\n' + 'dd(lambda: dict())\n', + id='not following unknown import', + ), + pytest.param( + 'from .collections import defaultdict\n' + 'defaultdict(lambda: list())\n', + id='relative imports', + ), + pytest.param( + 'from collections import defaultdict\n\n' + 'defaultdict(lambda: {1}))\n', + id='non empty set', + ), + pytest.param( + 'from collections import defaultdict\n\n' + 'defaultdict(lambda: [1]))\n' + 'defaultdict(lambda: list([1])))\n', + id='non empty list', + ), + pytest.param( + 'from collections import defaultdict\n\n' + 'defaultdict(lambda: {1: 2})\n', + id='non empty dict, literal', + ), + pytest.param( + 'from collections import defaultdict\n\n' + 'defaultdict(lambda: dict([(1,2),])))\n', + id='non empty dict, call with args', + ), + pytest.param( + 'from collections import defaultdict\n\n' + 'defaultdict(lambda: dict(a=[1]))\n', + id='non empty dict, call with kwargs', + ), + pytest.param( + 'from collections import defaultdict\n\n' + 'defaultdict(lambda: (1,))\n', + id='non empty tuple, literal', + ), + pytest.param( + 'from collections import defaultdict\n\n' + 'defaultdict(lambda: tuple([1]))\n', + id='non empty tuple, calls with arg', + ), + pytest.param( + 'from collections import defaultdict\n\n' + 'defaultdict(lambda: "AAA")\n' + 'defaultdict(lambda: \'BBB\')\n', + id='non empty string', + ), + pytest.param( + 'from collections import defaultdict\n\n' + 'defaultdict(lambda: 10)\n' + 'defaultdict(lambda: -2)\n', + id='non zero integer', + ), + pytest.param( + 'from collections import defaultdict\n\n' + 'defaultdict(lambda: 0.2)\n' + 'defaultdict(lambda: 0.00000001)\n' + 'defaultdict(lambda: -2.3)\n', + id='non zero float', + ), + pytest.param( + 'import collections\n' + 'collections.defaultdict(lambda: None)\n', + id='lambda: None is not equivalent to defaultdict()', + ), + ), +) +def test_fix_noop(s): + assert _fix_plugins(s, settings=Settings()) == s + + [email protected]( + ('s', 'expected'), + ( + pytest.param( + 'from collections import defaultdict\n\n' + 'defaultdict(lambda: set())\n', + 'from collections import defaultdict\n\n' + 'defaultdict(set)\n', + id='call with attr, set()', + ), + pytest.param( + 'from collections import defaultdict\n\n' + 'defaultdict(lambda: list())\n', + 'from collections import defaultdict\n\n' + 'defaultdict(list)\n', + id='call with attr, list()', + ), + pytest.param( + 'from collections import defaultdict\n\n' + 'defaultdict(lambda: dict())\n', + 'from collections import defaultdict\n\n' + 'defaultdict(dict)\n', + id='call with attr, dict()', + ), + pytest.param( + 'from collections import defaultdict\n\n' + 'defaultdict(lambda: tuple())\n', + 'from collections import defaultdict\n\n' + 'defaultdict(tuple)\n', + id='call with attr, tuple()', + ), + pytest.param( + 'from collections import defaultdict\n\n' + 'defaultdict(lambda: [])\n', + 'from collections import defaultdict\n\n' + 'defaultdict(list)\n', + id='call with attr, []', + ), + pytest.param( + 'from collections import defaultdict\n\n' + 'defaultdict(lambda: {})\n', + 'from collections import defaultdict\n\n' + 'defaultdict(dict)\n', + id='call with attr, {}', + ), + pytest.param( + 'from collections import defaultdict\n\n' + 'defaultdict(lambda: ())\n', + 'from collections import defaultdict\n\n' + 'defaultdict(tuple)\n', + id='call with attr, ()', + ), + pytest.param( + 'from collections import defaultdict\n\n' + 'defaultdict(lambda: "")\n', + 'from collections import defaultdict\n\n' + 'defaultdict(str)\n', + id='call with attr, empty string (double quote)', + ), + pytest.param( + 'from collections import defaultdict\n\n' + 'defaultdict(lambda: \'\')\n', + 'from collections import defaultdict\n\n' + 'defaultdict(str)\n', + id='call with attr, empty string (single quote)', + ), + pytest.param( + 'from collections import defaultdict\n\n' + 'defaultdict(lambda: 0)\n', + 'from collections import defaultdict\n\n' + 'defaultdict(int)\n', + id='call with attr, int', + ), + pytest.param( + 'from collections import defaultdict\n\n' + 'defaultdict(lambda: 0.0)\n', + 'from collections import defaultdict\n\n' + 'defaultdict(float)\n', + id='call with attr, float', + ), + pytest.param( + 'from collections import defaultdict\n\n' + 'defaultdict(lambda: 0.0000)\n', + 'from collections import defaultdict\n\n' + 'defaultdict(float)\n', + id='call with attr, long float', + ), + pytest.param( + 'from collections import defaultdict\n\n' + 'defaultdict(lambda: [], {1: []})\n', + 'from collections import defaultdict\n\n' + 'defaultdict(list, {1: []})\n', + id='defauldict with kwargs', + ), + pytest.param( + 'import collections\n\n' + 'collections.defaultdict(lambda: set())\n' + 'collections.defaultdict(lambda: list())\n' + 'collections.defaultdict(lambda: dict())\n' + 'collections.defaultdict(lambda: tuple())\n' + 'collections.defaultdict(lambda: [])\n' + 'collections.defaultdict(lambda: {})\n' + 'collections.defaultdict(lambda: "")\n' + 'collections.defaultdict(lambda: \'\')\n' + 'collections.defaultdict(lambda: 0)\n' + 'collections.defaultdict(lambda: 0.0)\n' + 'collections.defaultdict(lambda: 0.00000)\n' + 'collections.defaultdict(lambda: 0j)\n', + 'import collections\n\n' + 'collections.defaultdict(set)\n' + 'collections.defaultdict(list)\n' + 'collections.defaultdict(dict)\n' + 'collections.defaultdict(tuple)\n' + 'collections.defaultdict(list)\n' + 'collections.defaultdict(dict)\n' + 'collections.defaultdict(str)\n' + 'collections.defaultdict(str)\n' + 'collections.defaultdict(int)\n' + 'collections.defaultdict(float)\n' + 'collections.defaultdict(float)\n' + 'collections.defaultdict(complex)\n', + id='call with attr', + ), + ), +) +def test_fix_defaultdict(s, expected): + ret = _fix_plugins(s, settings=Settings()) + assert ret == expected
Upgrade `defaultdict` default_factory (simple lambdas) Hello! It is quite common to see lambda expression used as `default_factory` in `defaultdict`, however sometime there are some shorter / more idiomatic options, especially for builtin types. Some exemples: ```diff -defaultdict(lambda: set()) +defaultdict(set) -defaultdict(lambda: []) +defaultdict(list) -defaultdict(lambda: list()) +defaultdict(list) -defaultdict(lambda: {}) +defaultdict(dict) -defaultdict(lambda: 0) +defaultdict(int) -defaultdict(lambda: 0.0) +defaultdict(float) # Doesn't make much sense to use a tuple here thought -defaultdict(lambda: ()) +defaultdict(tuple) ``` I was wondering if that kind of fixer would be in scope for pyupgrade ? Checking open source python code, the lambda pattern seems quite common so I think this fixer could benefit many people: https://sourcegraph.com/search?q=context%3Aglobal+language%3Apython+defaultdict%5C%28%28lambda%3A+.*%29%5C%29&patternType=regexp&sm=1&groupBy=group&expanded= If you find it's worth implementing, I'll be happy to work on it. Thanks
0.0
72041b1e37bb793b00ee45132c1a5c3e7afd84bd
[ "tests/features/defauldict_lambda_test.py::test_fix_defaultdict[call", "tests/features/defauldict_lambda_test.py::test_fix_defaultdict[defauldict" ]
[ "tests/features/defauldict_lambda_test.py::test_fix_noop[not", "tests/features/defauldict_lambda_test.py::test_fix_noop[relative", "tests/features/defauldict_lambda_test.py::test_fix_noop[non", "tests/features/defauldict_lambda_test.py::test_fix_noop[lambda:" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-10-02 07:24:59+00:00
mit
1,188
asottile__pyupgrade-933
diff --git a/pyupgrade/_token_helpers.py b/pyupgrade/_token_helpers.py index 5936ab7..e932c04 100644 --- a/pyupgrade/_token_helpers.py +++ b/pyupgrade/_token_helpers.py @@ -369,6 +369,14 @@ def arg_str(tokens: list[Token], start: int, end: int) -> str: return tokens_to_src(tokens[start:end]).strip() +def _arg_str_no_comment(tokens: list[Token], start: int, end: int) -> str: + arg_tokens = [ + token for token in tokens[start:end] + if token.name != 'COMMENT' + ] + return tokens_to_src(arg_tokens).strip() + + def _arg_contains_newline(tokens: list[Token], start: int, end: int) -> bool: while tokens[start].name in {'NL', 'NEWLINE', UNIMPORTANT_WS}: start += 1 @@ -473,7 +481,7 @@ def replace_argument( def constant_fold_tuple(i: int, tokens: list[Token]) -> None: start = find_op(tokens, i, '(') func_args, end = parse_call_args(tokens, start) - arg_strs = [arg_str(tokens, *arg) for arg in func_args] + arg_strs = [_arg_str_no_comment(tokens, *arg) for arg in func_args] unique_args = tuple(dict.fromkeys(arg_strs))
asottile/pyupgrade
85c6837431a2eebdc9809f80b7adc529525ea73c
diff --git a/tests/features/exceptions_test.py b/tests/features/exceptions_test.py index e855bf2..335e1d4 100644 --- a/tests/features/exceptions_test.py +++ b/tests/features/exceptions_test.py @@ -225,6 +225,30 @@ def test_fix_exceptions_version_specific_noop(s, version): id='leave unrelated error names alone', ), + pytest.param( + 'try: ...\n' + 'except (\n' + ' BaseException,\n' + ' BaseException # b\n' + '): ...\n', + + 'try: ...\n' + 'except BaseException: ...\n', + + id='dedupe with comment. see #932', + ), + pytest.param( + 'try: ...\n' + 'except (\n' + ' A, A,\n' + ' B # b\n' + '): ...\n', + + 'try: ...\n' + 'except (A, B): ...\n', + + id='dedupe other exception, one contains comment. see #932', + ), ), ) def test_fix_exceptions(s, expected):
multi-line exception with duplicate BaseException and comments gives invalid code ## before ```python try: ... except ( BaseException, BaseException # b ): ... ``` ## after ```python try: ... except (BaseException, BaseException # b): ... ``` ## info * flags: none (and any I tried seemed to make no difference) * version: 3.15.0 * real-life code (although it's an intentionally "bad" test file): https://github.com/Zac-HD/flake8-trio/blob/main/tests/eval_files/trio103.py#L195 I expect you never intend to output invalid code, and similar errors could probably pop up in normal usage. I don't have much of an opinion on whether pyupgrade does nothing, or actually manages to remove the `BaseException` and move the comment somewhere else.
0.0
85c6837431a2eebdc9809f80b7adc529525ea73c
[ "tests/features/exceptions_test.py::test_fix_exceptions[dedupe" ]
[ "tests/features/exceptions_test.py::test_fix_exceptions_noop[empty", "tests/features/exceptions_test.py::test_fix_exceptions_noop[unrelated", "tests/features/exceptions_test.py::test_fix_exceptions_noop[already", "tests/features/exceptions_test.py::test_fix_exceptions_noop[same", "tests/features/exceptions_test.py::test_fix_exceptions_noop[not", "tests/features/exceptions_test.py::test_fix_exceptions_noop[ignoring", "tests/features/exceptions_test.py::test_fix_exceptions_noop[weird", "tests/features/exceptions_test.py::test_fix_exceptions_version_specific_noop[raise", "tests/features/exceptions_test.py::test_fix_exceptions_version_specific_noop[except", "tests/features/exceptions_test.py::test_fix_exceptions[mmap.error]", "tests/features/exceptions_test.py::test_fix_exceptions[os.error]", "tests/features/exceptions_test.py::test_fix_exceptions[select.error]", "tests/features/exceptions_test.py::test_fix_exceptions[socket.error]", "tests/features/exceptions_test.py::test_fix_exceptions[IOError]", "tests/features/exceptions_test.py::test_fix_exceptions[EnvironmentError]", "tests/features/exceptions_test.py::test_fix_exceptions[WindowsError]", "tests/features/exceptions_test.py::test_fix_exceptions[raise", "tests/features/exceptions_test.py::test_fix_exceptions[except", "tests/features/exceptions_test.py::test_fix_exceptions[deduplicates", "tests/features/exceptions_test.py::test_fix_exceptions[leave", "tests/features/exceptions_test.py::test_fix_exceptions_versioned[socket.timeout]", "tests/features/exceptions_test.py::test_fix_exceptions_versioned[asyncio.TimeoutError]", "tests/features/exceptions_test.py::test_can_rewrite_disparate_names" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2024-02-18 16:50:26+00:00
mit
1,189
asottile__pyupgrade-939
diff --git a/pyupgrade/_plugins/shlex_join.py b/pyupgrade/_plugins/shlex_join.py index 1406756..1718ff9 100644 --- a/pyupgrade/_plugins/shlex_join.py +++ b/pyupgrade/_plugins/shlex_join.py @@ -39,7 +39,7 @@ def visit_Call( if ( isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Constant) and - isinstance(node.func.value.value, str) and + node.func.value.value == ' ' and node.func.attr == 'join' and not node.keywords and len(node.args) == 1 and
asottile/pyupgrade
3e4103f24bfd10701d1913f7cc969b44fe165525
diff --git a/tests/features/shlex_join_test.py b/tests/features/shlex_join_test.py index fc6abe5..e3835f6 100644 --- a/tests/features/shlex_join_test.py +++ b/tests/features/shlex_join_test.py @@ -15,6 +15,12 @@ from pyupgrade._main import _fix_plugins (3, 8), id='quote from-imported', ), + pytest.param( + 'import shlex\n' + '"wat".join(shlex.quote(arg) for arg in cmd)\n', + (3, 8), + id='not joined with space', + ), pytest.param( 'import shlex\n' '" ".join(shlex.quote(arg) for arg in cmd)\n',
"".join(shlex.quote(...) ...) to shlex.join(...) is too eager Consider the following: ``` import shlex trash_bin = "garbage".join(shlex.quote(a) for a in ["some", "quotable strings"]) ``` If I run `pyupgrade --py310-plus` on this, I get `trash_bin = shlex.join(["some", "quotable strings"])`. But this is not equivalent. This is a very contrived case, but there are real cases I could envision, like `", "`, where one might want to keep the `str.join` pyupgrade==3.15.1
0.0
3e4103f24bfd10701d1913f7cc969b44fe165525
[ "tests/features/shlex_join_test.py::test_shlex_join_noop[not" ]
[ "tests/features/shlex_join_test.py::test_shlex_join_noop[quote", "tests/features/shlex_join_test.py::test_shlex_join_noop[3.8+", "tests/features/shlex_join_test.py::test_shlex_join_fixes[generator", "tests/features/shlex_join_test.py::test_shlex_join_fixes[list", "tests/features/shlex_join_test.py::test_shlex_join_fixes[removes", "tests/features/shlex_join_test.py::test_shlex_join_fixes[more" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2024-03-24 17:04:13+00:00
mit
1,190
asottile__setup-cfg-fmt-107
diff --git a/setup_cfg_fmt.py b/setup_cfg_fmt.py index be8eb0d..a2b637e 100644 --- a/setup_cfg_fmt.py +++ b/setup_cfg_fmt.py @@ -259,7 +259,8 @@ def _normalize_lib(lib: str) -> str: def _req_base(lib: str) -> str: basem = re.match(BASE_NAME_REGEX, lib) assert basem - return basem.group(0) + # pip replaces _ with - in package names + return basem.group(0).replace('_', '-') def _py_classifiers(
asottile/setup-cfg-fmt
1663a68ea45ed764f22ff1415edaea28ccbe118d
diff --git a/tests/setup_cfg_fmt_test.py b/tests/setup_cfg_fmt_test.py index 05a7b8d..d7e7f36 100644 --- a/tests/setup_cfg_fmt_test.py +++ b/tests/setup_cfg_fmt_test.py @@ -72,6 +72,7 @@ def test_noop(tmpdir): 'name = pkg\n' '[options]\n' '{} =\n' + ' req_req\n' ' req03\n' ' req05 <= 2,!=1\n' ' req06 ;python_version==2.7\n' @@ -97,6 +98,7 @@ def test_noop(tmpdir): '[options]\n' '{} =\n' ' req>=2\n' + ' req-req\n' ' req01\n' ' req02\n' ' req03\n'
normalize requirements names to be dashed-names
0.0
1663a68ea45ed764f22ff1415edaea28ccbe118d
[ "tests/setup_cfg_fmt_test.py::test_rewrite_requires[install_requires-normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite_requires[setup_requires-normalizes" ]
[ "tests/setup_cfg_fmt_test.py::test_ver_type_ok", "tests/setup_cfg_fmt_test.py::test_ver_type_error", "tests/setup_cfg_fmt_test.py::test_ver_type_not_a_version", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[foo-[Ff][Oo][Oo]]", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[FOO-[Ff][Oo][Oo]]", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[licen[sc]e-[Ll][Ii][Cc][Ee][Nn][SsCc][Ee]]", "tests/setup_cfg_fmt_test.py::test_noop", "tests/setup_cfg_fmt_test.py::test_rewrite[orders", "tests/setup_cfg_fmt_test.py::test_rewrite[normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite[sorts", "tests/setup_cfg_fmt_test.py::test_rewrite[normalize", "tests/setup_cfg_fmt_test.py::test_normalize_lib[no", "tests/setup_cfg_fmt_test.py::test_normalize_lib[whitespace", "tests/setup_cfg_fmt_test.py::test_normalize_lib[<=", "tests/setup_cfg_fmt_test.py::test_normalize_lib[>=", "tests/setup_cfg_fmt_test.py::test_normalize_lib[b/w", "tests/setup_cfg_fmt_test.py::test_normalize_lib[compatible", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.rst-text/x-rst]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.markdown-text/markdown]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.md-text/markdown]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README-text/plain]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[readme.txt-text/plain]", "tests/setup_cfg_fmt_test.py::test_readme_discover_prefers_file_over_directory", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENSE]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENCE]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENSE.md]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[license.txt]", "tests/setup_cfg_fmt_test.py::test_license_does_not_match_directories", "tests/setup_cfg_fmt_test.py::test_rewrite_sets_license_type_and_classifier", "tests/setup_cfg_fmt_test.py::test_rewrite_identifies_license", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[already", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[weird", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[not", "tests/setup_cfg_fmt_test.py::test_strips_empty_options_and_sections[only", "tests/setup_cfg_fmt_test.py::test_strips_empty_options_and_sections[entire", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_python2_tox_ini", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_tox_ini_dashed_name", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_ignores_insufficient_version_envs", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_from_classifiers", "tests/setup_cfg_fmt_test.py::test_min_py3_version_updates_python_requires", "tests/setup_cfg_fmt_test.py::test_min_py3_version_greater_than_minimum", "tests/setup_cfg_fmt_test.py::test_min_version_removes_classifiers", "tests/setup_cfg_fmt_test.py::test_python_requires_with_patch_version", "tests/setup_cfg_fmt_test.py::test_classifiers_left_alone_for_odd_python_requires", "tests/setup_cfg_fmt_test.py::test_min_py3_version_less_than_minimum", "tests/setup_cfg_fmt_test.py::test_rewrite_extras", "tests/setup_cfg_fmt_test.py::test_imp_classifiers_from_tox_ini", "tests/setup_cfg_fmt_test.py::test_imp_classifiers_no_change", "tests/setup_cfg_fmt_test.py::test_imp_classifiers_pypy_only", "tests/setup_cfg_fmt_test.py::test_natural_sort" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2021-10-30 20:47:26+00:00
mit
1,191
asottile__setup-cfg-fmt-132
diff --git a/setup_cfg_fmt.py b/setup_cfg_fmt.py index 34e3824..afd3a45 100644 --- a/setup_cfg_fmt.py +++ b/setup_cfg_fmt.py @@ -75,6 +75,12 @@ TOX_TO_CLASSIFIERS = { } +class NoTransformConfigParser(configparser.RawConfigParser): + def optionxform(self, s: str) -> str: + """disable default lower-casing""" + return s + + def _adjacent_filename(setup_cfg: str, filename: str) -> str: return os.path.join(os.path.dirname(setup_cfg), filename) @@ -153,7 +159,7 @@ def _parse_python_requires( def _tox_envlist(setup_cfg: str) -> Generator[str, None, None]: tox_ini = _adjacent_filename(setup_cfg, 'tox.ini') if os.path.exists(tox_ini): - cfg = configparser.ConfigParser() + cfg = NoTransformConfigParser() cfg.read(tox_ini) envlist = cfg.get('tox', 'envlist', fallback='') @@ -166,7 +172,7 @@ def _tox_envlist(setup_cfg: str) -> Generator[str, None, None]: def _python_requires( setup_cfg: str, *, min_py3_version: tuple[int, int], ) -> str | None: - cfg = configparser.ConfigParser() + cfg = NoTransformConfigParser() cfg.read(setup_cfg) current_value = cfg.get('options', 'python_requires', fallback='') classifiers = cfg.get('metadata', 'classifiers', fallback='') @@ -207,7 +213,7 @@ def _python_requires( def _requires( - cfg: configparser.ConfigParser, which: str, section: str = 'options', + cfg: NoTransformConfigParser, which: str, section: str = 'options', ) -> list[str]: raw = cfg.get(section, which, fallback='') @@ -356,7 +362,7 @@ def format_file( with open(filename) as f: contents = f.read() - cfg = configparser.ConfigParser() + cfg = NoTransformConfigParser() cfg.read_string(contents) _clean_sections(cfg) @@ -467,7 +473,7 @@ def format_file( return new_contents != contents -def _clean_sections(cfg: configparser.ConfigParser) -> None: +def _clean_sections(cfg: NoTransformConfigParser) -> None: """Removes any empty options and sections.""" for section in cfg.sections(): new_options = {k: v for k, v in cfg[section].items() if v}
asottile/setup-cfg-fmt
5efd7109ad526cf4b5b5de7dff003eb5aa1e4058
diff --git a/tests/setup_cfg_fmt_test.py b/tests/setup_cfg_fmt_test.py index 0bc8310..b3372a7 100644 --- a/tests/setup_cfg_fmt_test.py +++ b/tests/setup_cfg_fmt_test.py @@ -951,6 +951,22 @@ def test_imp_classifiers_pypy_only(tmpdir): ) +def test_leaves_casing_of_unrelated_settings(tmpdir): + setup_cfg = tmpdir.join('setup.cfg') + setup_cfg.write( + '[metadata]\n' + 'name = pkg\n' + 'version = 1.0\n' + 'classifiers =\n' + ' Programming Language :: Python :: Implementation :: CPython\n' + '\n' + '[tool:pytest]\n' + 'DJANGO_SETTINGS_MODULE = test.test\n', + ) + + assert not main((str(setup_cfg),)) + + def test_natural_sort(): classifiers = [ 'Programming Language :: Python :: 3',
configparser is downcasing keys in unrelated sections for instance this doesn't roundtrip: ```ini [tool:pytest] DJANGO_SETTINGS_MODULE = test.test ```
0.0
5efd7109ad526cf4b5b5de7dff003eb5aa1e4058
[ "tests/setup_cfg_fmt_test.py::test_leaves_casing_of_unrelated_settings" ]
[ "tests/setup_cfg_fmt_test.py::test_ver_type_ok", "tests/setup_cfg_fmt_test.py::test_ver_type_error", "tests/setup_cfg_fmt_test.py::test_ver_type_not_a_version", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[foo-[Ff][Oo][Oo]]", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[FOO-[Ff][Oo][Oo]]", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[licen[sc]e-[Ll][Ii][Cc][Ee][Nn][SsCc][Ee]]", "tests/setup_cfg_fmt_test.py::test_noop", "tests/setup_cfg_fmt_test.py::test_rewrite_requires[install_requires-normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite_requires[setup_requires-normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite[orders", "tests/setup_cfg_fmt_test.py::test_rewrite[normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite[sorts", "tests/setup_cfg_fmt_test.py::test_rewrite[normalize", "tests/setup_cfg_fmt_test.py::test_normalize_lib[no", "tests/setup_cfg_fmt_test.py::test_normalize_lib[whitespace", "tests/setup_cfg_fmt_test.py::test_normalize_lib[<=", "tests/setup_cfg_fmt_test.py::test_normalize_lib[>=", "tests/setup_cfg_fmt_test.py::test_normalize_lib[b/w", "tests/setup_cfg_fmt_test.py::test_normalize_lib[compatible", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.rst-text/x-rst]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.markdown-text/markdown]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.md-text/markdown]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README-text/plain]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[readme.txt-text/plain]", "tests/setup_cfg_fmt_test.py::test_readme_discover_prefers_file_over_directory", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENSE]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENCE]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENSE.md]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[license.txt]", "tests/setup_cfg_fmt_test.py::test_license_does_not_match_directories", "tests/setup_cfg_fmt_test.py::test_rewrite_sets_license_type_and_classifier", "tests/setup_cfg_fmt_test.py::test_rewrite_identifies_license", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[already", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[weird", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[not", "tests/setup_cfg_fmt_test.py::test_strips_empty_options_and_sections[only", "tests/setup_cfg_fmt_test.py::test_strips_empty_options_and_sections[entire", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_python2_tox_ini", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_tox_ini_dashed_name", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_ignores_insufficient_version_envs", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_from_classifiers", "tests/setup_cfg_fmt_test.py::test_min_py3_version_updates_python_requires", "tests/setup_cfg_fmt_test.py::test_min_py3_version_greater_than_minimum", "tests/setup_cfg_fmt_test.py::test_min_version_removes_classifiers", "tests/setup_cfg_fmt_test.py::test_python_requires_with_patch_version", "tests/setup_cfg_fmt_test.py::test_classifiers_left_alone_for_odd_python_requires", "tests/setup_cfg_fmt_test.py::test_min_py3_version_less_than_minimum", "tests/setup_cfg_fmt_test.py::test_rewrite_extras", "tests/setup_cfg_fmt_test.py::test_imp_classifiers_from_tox_ini", "tests/setup_cfg_fmt_test.py::test_imp_classifiers_no_change", "tests/setup_cfg_fmt_test.py::test_imp_classifiers_pypy_only", "tests/setup_cfg_fmt_test.py::test_natural_sort" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-04-02 16:02:50+00:00
mit
1,192
asottile__setup-cfg-fmt-150
diff --git a/README.md b/README.md index f6c2f8c..cd5ecc3 100644 --- a/README.md +++ b/README.md @@ -95,7 +95,7 @@ setuptools allows dashed names but does not document them. +long_description = file: README.md ``` -### adds `long_description` if `README.md` is present +### adds `long_description` if `README` is present This will show up on the pypi project page diff --git a/setup_cfg_fmt.py b/setup_cfg_fmt.py index afd3a45..299d670 100644 --- a/setup_cfg_fmt.py +++ b/setup_cfg_fmt.py @@ -103,7 +103,13 @@ def _case_insensitive_glob(s: str) -> str: def _first_file(setup_cfg: str, prefix: str) -> str | None: prefix = _case_insensitive_glob(prefix) path = _adjacent_filename(setup_cfg, prefix) - for filename in sorted(glob.iglob(f'{path}*')): + + # prefer non-asciidoc because pypi does not render it + # https://github.com/asottile/setup-cfg-fmt/issues/149 + def sort_key(filename: str) -> tuple[bool, str]: + return (filename.endswith(('.adoc', '.asciidoc')), filename) + + for filename in sorted(glob.iglob(f'{path}*'), key=sort_key): if os.path.isfile(filename): return filename else: @@ -369,7 +375,7 @@ def format_file( # normalize names to underscores so sdist / wheel have the same prefix cfg['metadata']['name'] = cfg['metadata']['name'].replace('-', '_') - # if README.md exists, set `long_description` + content type + # if README exists, set `long_description` + content type readme = _first_file(filename, 'readme') if readme is not None: long_description = f'file: {os.path.basename(readme)}'
asottile/setup-cfg-fmt
97c79d263a803b0dd7a5cea649b3ac1ae4b9e2de
diff --git a/tests/setup_cfg_fmt_test.py b/tests/setup_cfg_fmt_test.py index b3372a7..4527f1b 100644 --- a/tests/setup_cfg_fmt_test.py +++ b/tests/setup_cfg_fmt_test.py @@ -296,6 +296,68 @@ def test_adds_long_description_with_readme(filename, content_type, tmpdir): ) [email protected]( + ('filename', 'content_type'), + ( + ('README.rst', 'text/x-rst'), + ('README.markdown', 'text/markdown'), + ('README.md', 'text/markdown'), + ('README', 'text/plain'), + ('README.txt', 'text/plain'), + ('readme.txt', 'text/plain'), + ), +) +def test_readme_discover_does_not_prefer_adoc(filename, content_type, tmpdir): + tmpdir.join(filename).write('my project!') + tmpdir.join('README.adoc').write('my project!') + tmpdir.join('README.asciidoc').write('my project!') + + setup_cfg = tmpdir.join('setup.cfg') + setup_cfg.write( + '[metadata]\n' + 'name = pkg\n' + 'version = 1.0\n', + ) + + assert main((str(setup_cfg),)) + + assert setup_cfg.read() == ( + f'[metadata]\n' + f'name = pkg\n' + f'version = 1.0\n' + f'long_description = file: {filename}\n' + f'long_description_content_type = {content_type}\n' + ) + + [email protected]( + 'filename', + ( + 'README.adoc', + 'README.asciidoc', + ), +) +def test_readme_discover_uses_asciidoc_if_none_other_found(filename, tmpdir): + tmpdir.join(filename).write('my project!') + + setup_cfg = tmpdir.join('setup.cfg') + setup_cfg.write( + '[metadata]\n' + 'name = pkg\n' + 'version = 1.0\n', + ) + + assert main((str(setup_cfg),)) + + assert setup_cfg.read() == ( + f'[metadata]\n' + f'name = pkg\n' + f'version = 1.0\n' + f'long_description = file: {filename}\n' + f'long_description_content_type = text/plain\n' + ) + + def test_readme_discover_prefers_file_over_directory(tmpdir): tmpdir.join('README').mkdir() tmpdir.join('README.md').write('my project!')
fix: add option for defining long_description Hello! Thanks for this awesome project and you determination to open source. I use Asciidoctor for documentation. Because PyPI does not support rendering this format, I made a CI workflow to convert my README.adoc to a README.md before building the python wheels and uploading to PyPI etc (unrelevant to this ticket, just a info). The current alphabetical-sort determination made by this hook ranks `.adoc` (with content_type of `text/plain`) as first, which results in PyPI showing `The author of this package has not provided a project description` as it does not support Asciidoctor. I tried to do a workaround by renaming the markdown file to `README-.md` for it to rank first but then python/pypi does not like it: ``` ...(README-.md file is not being copied)... /tmp/build-env-cbglbinp/lib/python3.8/site-packages/setuptools/config/expand.py:142: UserWarning: File '/tmp/build-via-sdist-wi26p40b/test_application-0.3.6/README-.md' cannot be found warnings.warn(f"File {path!r} cannot be found") warning: sdist: standard file not found: should have one of README, README.rst, README.txt, README.md ``` I then tried to do a workaround by renaming the markdown file to `README`, but then this hook determines it as `text/plain`. I reverted to commenting this pre-commit hook out for now. I'd like to add an option for defining the filename for `long_description` like this: ```yaml - repo: https://github.com/asottile/setup-cfg-fmt rev: v1.20.2 hooks: - id: setup-cfg-fmt long_description: README.md ``` I'd love to make my first PR for this!
0.0
97c79d263a803b0dd7a5cea649b3ac1ae4b9e2de
[ "tests/setup_cfg_fmt_test.py::test_readme_discover_does_not_prefer_adoc[README.rst-text/x-rst]", "tests/setup_cfg_fmt_test.py::test_readme_discover_does_not_prefer_adoc[README.markdown-text/markdown]", "tests/setup_cfg_fmt_test.py::test_readme_discover_does_not_prefer_adoc[README.md-text/markdown]", "tests/setup_cfg_fmt_test.py::test_readme_discover_does_not_prefer_adoc[README.txt-text/plain]", "tests/setup_cfg_fmt_test.py::test_readme_discover_does_not_prefer_adoc[readme.txt-text/plain]" ]
[ "tests/setup_cfg_fmt_test.py::test_ver_type_ok", "tests/setup_cfg_fmt_test.py::test_ver_type_error", "tests/setup_cfg_fmt_test.py::test_ver_type_not_a_version", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[foo-[Ff][Oo][Oo]]", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[FOO-[Ff][Oo][Oo]]", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[licen[sc]e-[Ll][Ii][Cc][Ee][Nn][SsCc][Ee]]", "tests/setup_cfg_fmt_test.py::test_noop", "tests/setup_cfg_fmt_test.py::test_rewrite_requires[install_requires-normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite_requires[setup_requires-normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite[orders", "tests/setup_cfg_fmt_test.py::test_rewrite[normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite[sorts", "tests/setup_cfg_fmt_test.py::test_rewrite[normalize", "tests/setup_cfg_fmt_test.py::test_normalize_lib[no", "tests/setup_cfg_fmt_test.py::test_normalize_lib[whitespace", "tests/setup_cfg_fmt_test.py::test_normalize_lib[<=", "tests/setup_cfg_fmt_test.py::test_normalize_lib[>=", "tests/setup_cfg_fmt_test.py::test_normalize_lib[b/w", "tests/setup_cfg_fmt_test.py::test_normalize_lib[compatible", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.rst-text/x-rst]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.markdown-text/markdown]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.md-text/markdown]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README-text/plain]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[readme.txt-text/plain]", "tests/setup_cfg_fmt_test.py::test_readme_discover_does_not_prefer_adoc[README-text/plain]", "tests/setup_cfg_fmt_test.py::test_readme_discover_uses_asciidoc_if_none_other_found[README.adoc]", "tests/setup_cfg_fmt_test.py::test_readme_discover_uses_asciidoc_if_none_other_found[README.asciidoc]", "tests/setup_cfg_fmt_test.py::test_readme_discover_prefers_file_over_directory", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENSE]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENCE]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENSE.md]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[license.txt]", "tests/setup_cfg_fmt_test.py::test_license_does_not_match_directories", "tests/setup_cfg_fmt_test.py::test_rewrite_sets_license_type_and_classifier", "tests/setup_cfg_fmt_test.py::test_rewrite_identifies_license", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[already", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[weird", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[not", "tests/setup_cfg_fmt_test.py::test_strips_empty_options_and_sections[only", "tests/setup_cfg_fmt_test.py::test_strips_empty_options_and_sections[entire", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_python2_tox_ini", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_tox_ini_dashed_name", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_ignores_insufficient_version_envs", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_from_classifiers", "tests/setup_cfg_fmt_test.py::test_min_py3_version_updates_python_requires", "tests/setup_cfg_fmt_test.py::test_min_py3_version_greater_than_minimum", "tests/setup_cfg_fmt_test.py::test_min_version_removes_classifiers", "tests/setup_cfg_fmt_test.py::test_python_requires_with_patch_version", "tests/setup_cfg_fmt_test.py::test_classifiers_left_alone_for_odd_python_requires", "tests/setup_cfg_fmt_test.py::test_min_py3_version_less_than_minimum", "tests/setup_cfg_fmt_test.py::test_rewrite_extras", "tests/setup_cfg_fmt_test.py::test_imp_classifiers_from_tox_ini", "tests/setup_cfg_fmt_test.py::test_imp_classifiers_no_change", "tests/setup_cfg_fmt_test.py::test_imp_classifiers_pypy_only", "tests/setup_cfg_fmt_test.py::test_leaves_casing_of_unrelated_settings", "tests/setup_cfg_fmt_test.py::test_natural_sort" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2022-07-21 14:51:19+00:00
mit
1,193
asottile__setup-cfg-fmt-16
diff --git a/setup_cfg_fmt.py b/setup_cfg_fmt.py index 8a8da69..678c851 100644 --- a/setup_cfg_fmt.py +++ b/setup_cfg_fmt.py @@ -196,6 +196,55 @@ def _python_requires( return _format_python_requires(minimum, excluded) +def _install_requires(cfg: configparser.ConfigParser) -> List[str]: + raw = cfg.get('options', 'install_requires', fallback='') + + install_requires = raw.strip().splitlines() + + normalized = sorted( + (_normalize_req(req) for req in install_requires), + key=lambda req: (';' in req, req), + ) + + if len(normalized) > 1: + normalized.insert(0, '') + + return normalized + + +def _normalize_req(req: str) -> str: + lib, _, envs = req.partition(';') + normalized = _normalize_lib(lib) + + envs = envs.strip() + if not envs: + return normalized + + return f'{normalized};{envs}' + + +BASE_NAME_REGEX = re.compile(r'[^!=><\s]+') +REQ_REGEX = re.compile(r'(===|==|!=|~=|>=?|<=?)\s*([^,]+)') + + +def _normalize_lib(lib: str) -> str: + basem = re.match(BASE_NAME_REGEX, lib) + assert basem + base = basem.group(0) + + conditions = ','.join( + sorted( + ( + f'{m.group(1)}{m.group(2)}' + for m in REQ_REGEX.finditer(lib) + ), + key=lambda c: ('<' in c, '>' in 'c', c), + ), + ) + + return f'{base}{conditions}' + + def _py_classifiers( python_requires: Optional[str], *, max_py_version: Tuple[int, int], ) -> Optional[str]: @@ -308,6 +357,10 @@ def format_file( cfg.add_section('options') cfg['options']['python_requires'] = requires + install_requires = _install_requires(cfg) + if install_requires: + cfg['options']['install_requires'] = '\n'.join(install_requires) + py_classifiers = _py_classifiers(requires, max_py_version=max_py_version) if py_classifiers: cfg['metadata']['classifiers'] = (
asottile/setup-cfg-fmt
a19c422ae3cb484a3164205709339d7ac0abe1d8
diff --git a/tests/setup_cfg_fmt_test.py b/tests/setup_cfg_fmt_test.py index 7de86ab..9454631 100644 --- a/tests/setup_cfg_fmt_test.py +++ b/tests/setup_cfg_fmt_test.py @@ -3,6 +3,7 @@ import argparse import pytest from setup_cfg_fmt import _case_insensitive_glob +from setup_cfg_fmt import _normalize_lib from setup_cfg_fmt import _ver_type from setup_cfg_fmt import main @@ -56,6 +57,67 @@ def test_noop(tmpdir): @pytest.mark.parametrize( ('input_s', 'expected'), ( + pytest.param( + '[metadata]\n' + 'version = 1.0\n' + 'name = pkg\n' + '[options]\n' + 'install_requires =\n' + ' req03\n' + ' req05 <= 2,!=1\n' + ' req06 ;python_version==2.7\n' + ' req07 ;os_version!=windows\n' + ' req13 !=2, >= 7\n' + ' req14 <=2, >= 1\n' + ' req01\n' + ' req02\n' + ' req09 ~= 7\n' + ' req10 === 8\n' + ' req11; python_version=="2.7"\n' + ' req08 == 2\n' + ' req12;\n' + ' req04 >= 1\n', + + '[metadata]\n' + 'name = pkg\n' + 'version = 1.0\n' + '\n' + '[options]\n' + 'install_requires =\n' + ' req01\n' + ' req02\n' + ' req03\n' + ' req04>=1\n' + ' req05!=1,<=2\n' + ' req08==2\n' + ' req09~=7\n' + ' req10===8\n' + ' req12\n' + ' req13!=2,>=7\n' + ' req14>=1,<=2\n' + ' req06;python_version==2.7\n' + ' req07;os_version!=windows\n' + ' req11;python_version=="2.7"\n', + + id='normalizes install_requires', + ), + pytest.param( + '[metadata]\n' + 'version = 1.0\n' + 'name = pkg\n' + '[options]\n' + 'install_requires =\n' + ' req03\n', + + '[metadata]\n' + 'name = pkg\n' + 'version = 1.0\n' + '\n' + '[options]\n' + 'install_requires = req03\n', + + id='normalize single install_requires req to one line', + ), pytest.param( '[bdist_wheel]\n' 'universal = true\n' @@ -114,6 +176,20 @@ def test_rewrite(input_s, expected, tmpdir): assert setup_cfg.read() == expected [email protected]( + ('lib', 'expected'), + ( + pytest.param('req01', 'req01', id='no conditions'), + pytest.param('req04 >= 1', 'req04>=1', id='whitespace stripped'), + pytest.param('req05 <= 2,!=1', 'req05!=1,<=2', id='<= cond at end'), + pytest.param('req13 !=2, >= 7', 'req13!=2,>=7', id='>= cond at end'), + pytest.param('req14 <=2, >= 1', 'req14>=1,<=2', id='b/w conds sorted'), + ), +) +def test_normalize_lib(lib, expected): + assert _normalize_lib(lib) == expected + + @pytest.mark.parametrize( ('filename', 'content_type'), (
sort install_requires / setup_requires probably: 1. sort any non-version-qualified ones 2. group + sort by version qualifier
0.0
a19c422ae3cb484a3164205709339d7ac0abe1d8
[ "tests/setup_cfg_fmt_test.py::test_ver_type_ok", "tests/setup_cfg_fmt_test.py::test_ver_type_error", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[foo-[Ff][Oo][Oo]]", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[FOO-[Ff][Oo][Oo]]", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[licen[sc]e-[Ll][Ii][Cc][Ee][Nn][SsCc][Ee]]", "tests/setup_cfg_fmt_test.py::test_noop", "tests/setup_cfg_fmt_test.py::test_rewrite[normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite[normalize", "tests/setup_cfg_fmt_test.py::test_rewrite[orders", "tests/setup_cfg_fmt_test.py::test_rewrite[sorts", "tests/setup_cfg_fmt_test.py::test_normalize_lib[no", "tests/setup_cfg_fmt_test.py::test_normalize_lib[whitespace", "tests/setup_cfg_fmt_test.py::test_normalize_lib[<=", "tests/setup_cfg_fmt_test.py::test_normalize_lib[>=", "tests/setup_cfg_fmt_test.py::test_normalize_lib[b/w", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.rst-text/x-rst]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.markdown-text/markdown]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.md-text/markdown]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README-text/plain]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[readme.txt-text/plain]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENSE]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENCE]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENSE.md]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[license.txt]", "tests/setup_cfg_fmt_test.py::test_rewrite_sets_license_type_and_classifier", "tests/setup_cfg_fmt_test.py::test_rewrite_identifies_license", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[already", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[weird", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_python2_tox_ini", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_tox_ini_dashed_name", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_ignores_insufficient_version_envs", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_from_classifiers", "tests/setup_cfg_fmt_test.py::test_min_py3_version_updates_python_requires", "tests/setup_cfg_fmt_test.py::test_min_py3_version_greater_than_minimum", "tests/setup_cfg_fmt_test.py::test_min_version_removes_classifiers", "tests/setup_cfg_fmt_test.py::test_classifiers_left_alone_for_odd_python_requires", "tests/setup_cfg_fmt_test.py::test_min_py3_version_less_than_minimum" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2019-06-28 15:55:55+00:00
mit
1,194
asottile__setup-cfg-fmt-41
diff --git a/setup_cfg_fmt.py b/setup_cfg_fmt.py index f7c674e..1dee7b6 100644 --- a/setup_cfg_fmt.py +++ b/setup_cfg_fmt.py @@ -20,8 +20,10 @@ KEYS_ORDER: Tuple[Tuple[str, Tuple[str, ...]], ...] = ( 'metadata', ( 'name', 'version', 'description', 'long_description', 'long_description_content_type', - 'url', 'author', 'author_email', 'license', 'license_file', - 'license_files', 'platforms', 'classifiers', + 'url', + 'author', 'author_email', 'maintainer', 'maintainer_email', + 'license', 'license_file', 'license_files', + 'platforms', 'classifiers', ), ), (
asottile/setup-cfg-fmt
d6dc55e3b6e5b77c93f9641b6c7cbead7e6cfa8f
diff --git a/tests/setup_cfg_fmt_test.py b/tests/setup_cfg_fmt_test.py index 50062d9..36762f3 100644 --- a/tests/setup_cfg_fmt_test.py +++ b/tests/setup_cfg_fmt_test.py @@ -168,6 +168,25 @@ def test_rewrite_requires(which, input_tpl, expected_tpl, tmpdir): id='sorts classifiers', ), + pytest.param( + '[metadata]\n' + 'maintainer_email = [email protected]\n' + 'maintainer = jane\n' + 'license = foo\n' + 'name = pkg\n' + 'author_email = [email protected]\n' + 'author = john\n', + + '[metadata]\n' + 'name = pkg\n' + 'author = john\n' + 'author_email = [email protected]\n' + 'maintainer = jane\n' + 'maintainer_email = [email protected]\n' + 'license = foo\n', + + id='orders authors and maintainers', + ), ), ) def test_rewrite(input_s, expected, tmpdir):
author and maintainer should be kept beside each other found via https://github.com/pfmoore/editables/pull/2
0.0
d6dc55e3b6e5b77c93f9641b6c7cbead7e6cfa8f
[ "tests/setup_cfg_fmt_test.py::test_rewrite[orders" ]
[ "tests/setup_cfg_fmt_test.py::test_ver_type_ok", "tests/setup_cfg_fmt_test.py::test_ver_type_error", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[foo-[Ff][Oo][Oo]]", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[FOO-[Ff][Oo][Oo]]", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[licen[sc]e-[Ll][Ii][Cc][Ee][Nn][SsCc][Ee]]", "tests/setup_cfg_fmt_test.py::test_noop", "tests/setup_cfg_fmt_test.py::test_rewrite_requires[install_requires-normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite_requires[setup_requires-normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite[normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite[sorts", "tests/setup_cfg_fmt_test.py::test_normalize_lib[no", "tests/setup_cfg_fmt_test.py::test_normalize_lib[whitespace", "tests/setup_cfg_fmt_test.py::test_normalize_lib[<=", "tests/setup_cfg_fmt_test.py::test_normalize_lib[>=", "tests/setup_cfg_fmt_test.py::test_normalize_lib[b/w", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.rst-text/x-rst]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.markdown-text/markdown]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.md-text/markdown]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README-text/plain]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[readme.txt-text/plain]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENSE]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENCE]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENSE.md]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[license.txt]", "tests/setup_cfg_fmt_test.py::test_license_does_not_match_directories", "tests/setup_cfg_fmt_test.py::test_rewrite_sets_license_type_and_classifier", "tests/setup_cfg_fmt_test.py::test_rewrite_identifies_license", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[already", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[weird", "tests/setup_cfg_fmt_test.py::test_strips_empty_options_and_sections[only", "tests/setup_cfg_fmt_test.py::test_strips_empty_options_and_sections[entire", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_python2_tox_ini", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_tox_ini_dashed_name", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_ignores_insufficient_version_envs", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_from_classifiers", "tests/setup_cfg_fmt_test.py::test_min_py3_version_updates_python_requires", "tests/setup_cfg_fmt_test.py::test_min_py3_version_greater_than_minimum", "tests/setup_cfg_fmt_test.py::test_min_version_removes_classifiers", "tests/setup_cfg_fmt_test.py::test_classifiers_left_alone_for_odd_python_requires", "tests/setup_cfg_fmt_test.py::test_min_py3_version_less_than_minimum" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2020-07-07 01:46:04+00:00
mit
1,195
asottile__setup-cfg-fmt-48
diff --git a/setup_cfg_fmt.py b/setup_cfg_fmt.py index b1967b2..d541a70 100644 --- a/setup_cfg_fmt.py +++ b/setup_cfg_fmt.py @@ -398,11 +398,11 @@ def format_file( if section not in cfg: continue - new_section = { - k: cfg[section].pop(k) for k in key_order if k in cfg[section] - } + entries = {k.replace('-', '_'): v for k, v in cfg[section].items()} + + new_section = {k: entries.pop(k) for k in key_order if k in entries} # sort any remaining keys - new_section.update(sorted(cfg[section].items())) + new_section.update(sorted(entries.items())) sections[section] = new_section cfg.pop(section)
asottile/setup-cfg-fmt
696ec3afe7956eb032dfbafa33efadb12ebb8079
diff --git a/tests/setup_cfg_fmt_test.py b/tests/setup_cfg_fmt_test.py index 6558886..677291b 100644 --- a/tests/setup_cfg_fmt_test.py +++ b/tests/setup_cfg_fmt_test.py @@ -192,6 +192,19 @@ def test_rewrite_requires(which, input_tpl, expected_tpl, tmpdir): id='orders authors and maintainers', ), + pytest.param( + '[metadata]\n' + 'name = pkg\n' + 'author-email = [email protected]\n' + 'maintainer-email = [email protected]\n', + + '[metadata]\n' + 'name = pkg\n' + 'author_email = [email protected]\n' + 'maintainer_email = [email protected]\n', + + id='normalize dashes to underscores in keys', + ), ), ) def test_rewrite(input_s, expected, tmpdir):
normalize dashed-keys to underscored_keys setuptools apparently allows both, but canonically spells them with underscores found in https://github.com/pfmoore/editables/pull/2
0.0
696ec3afe7956eb032dfbafa33efadb12ebb8079
[ "tests/setup_cfg_fmt_test.py::test_rewrite[normalize" ]
[ "tests/setup_cfg_fmt_test.py::test_ver_type_ok", "tests/setup_cfg_fmt_test.py::test_ver_type_error", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[foo-[Ff][Oo][Oo]]", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[FOO-[Ff][Oo][Oo]]", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[licen[sc]e-[Ll][Ii][Cc][Ee][Nn][SsCc][Ee]]", "tests/setup_cfg_fmt_test.py::test_noop", "tests/setup_cfg_fmt_test.py::test_rewrite_requires[install_requires-normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite_requires[setup_requires-normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite[orders", "tests/setup_cfg_fmt_test.py::test_rewrite[normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite[sorts", "tests/setup_cfg_fmt_test.py::test_normalize_lib[no", "tests/setup_cfg_fmt_test.py::test_normalize_lib[whitespace", "tests/setup_cfg_fmt_test.py::test_normalize_lib[<=", "tests/setup_cfg_fmt_test.py::test_normalize_lib[>=", "tests/setup_cfg_fmt_test.py::test_normalize_lib[b/w", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.rst-text/x-rst]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.markdown-text/markdown]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.md-text/markdown]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README-text/plain]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[readme.txt-text/plain]", "tests/setup_cfg_fmt_test.py::test_readme_discover_prefers_file_over_directory", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENSE]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENCE]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENSE.md]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[license.txt]", "tests/setup_cfg_fmt_test.py::test_license_does_not_match_directories", "tests/setup_cfg_fmt_test.py::test_rewrite_sets_license_type_and_classifier", "tests/setup_cfg_fmt_test.py::test_rewrite_identifies_license", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[already", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[weird", "tests/setup_cfg_fmt_test.py::test_strips_empty_options_and_sections[only", "tests/setup_cfg_fmt_test.py::test_strips_empty_options_and_sections[entire", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_python2_tox_ini", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_tox_ini_dashed_name", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_ignores_insufficient_version_envs", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_from_classifiers", "tests/setup_cfg_fmt_test.py::test_min_py3_version_updates_python_requires", "tests/setup_cfg_fmt_test.py::test_min_py3_version_greater_than_minimum", "tests/setup_cfg_fmt_test.py::test_min_version_removes_classifiers", "tests/setup_cfg_fmt_test.py::test_classifiers_left_alone_for_odd_python_requires", "tests/setup_cfg_fmt_test.py::test_min_py3_version_less_than_minimum", "tests/setup_cfg_fmt_test.py::test_rewrite_extras" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2020-10-04 14:53:39+00:00
mit
1,196
asottile__setup-cfg-fmt-51
diff --git a/setup.cfg b/setup.cfg index d93b1b6..a8c0cb8 100644 --- a/setup.cfg +++ b/setup.cfg @@ -16,6 +16,7 @@ classifiers = Programming Language :: Python :: 3.6 Programming Language :: Python :: 3.7 Programming Language :: Python :: 3.8 + Programming Language :: Python :: 3.9 [options] py_modules = setup_cfg_fmt diff --git a/setup_cfg_fmt.py b/setup_cfg_fmt.py index 75b0c2c..d12d92c 100644 --- a/setup_cfg_fmt.py +++ b/setup_cfg_fmt.py @@ -14,6 +14,7 @@ from typing import Tuple from identify import identify +Version = Tuple[int, ...] KEYS_ORDER: Tuple[Tuple[str, Tuple[str, ...]], ...] = ( ( @@ -103,10 +104,7 @@ def _py3_excluded(min_py3_version: Tuple[int, int]) -> Set[Tuple[int, int]]: return {(3, i) for i in range(end)} -def _format_python_requires( - minimum: Tuple[int, int], - excluded: Set[Tuple[int, int]], -) -> str: +def _format_python_requires(minimum: Version, excluded: Set[Version]) -> str: return ', '.join(( f'>={_v(minimum)}', *(f'!={_v(v)}.*' for v in sorted(excluded)), )) @@ -116,21 +114,21 @@ class UnknownVersionError(ValueError): pass -def _to_ver(s: str) -> Tuple[int, int]: +def _to_ver(s: str) -> Version: parts = [part for part in s.split('.') if part != '*'] - if len(parts) != 2: + if len(parts) < 2: raise UnknownVersionError() else: - return int(parts[0]), int(parts[1]) + return tuple(int(part) for part in parts) -def _v(x: Tuple[int, ...]) -> str: +def _v(x: Version) -> str: return '.'.join(str(p) for p in x) def _parse_python_requires( - python_requires: Optional[str], -) -> Tuple[Optional[Tuple[int, int]], Set[Tuple[int, int]]]: + python_requires: Optional[str], +) -> Tuple[Optional[Version], Set[Version]]: minimum = None excluded = set() @@ -176,7 +174,7 @@ def _python_requires( env[2:].isdigit() ): version = _to_ver('.'.join(env[2:])) - if minimum is None or version < minimum: + if minimum is None or version < minimum[:2]: minimum = version for classifier in classifiers.strip().splitlines(): @@ -185,7 +183,7 @@ def _python_requires( if '.' not in version_part: continue version = _to_ver(version_part) - if minimum is None or version < minimum: + if minimum is None or version < minimum[:2]: minimum = version if minimum is None: @@ -263,8 +261,11 @@ def _py_classifiers( if minimum is None: # don't have a sequence of versions to iterate over return None + else: + # classifiers only use the first two segments of version + minimum = minimum[:2] - versions: Set[Tuple[int, ...]] = set() + versions: Set[Version] = set() while minimum <= max_py_version: if minimum not in exclude: versions.add(minimum) @@ -437,11 +438,16 @@ def _clean_sections(cfg: configparser.ConfigParser) -> None: cfg.pop(section) -def _ver_type(s: str) -> Tuple[int, int]: +def _ver_type(s: str) -> Version: try: - return _to_ver(s) + version = _to_ver(s) except UnknownVersionError: + version = () + + if len(version) != 2: raise argparse.ArgumentTypeError(f'expected #.#, got {s!r}') + else: + return version def main(argv: Optional[Sequence[str]] = None) -> int:
asottile/setup-cfg-fmt
dff9e90e8ee5d1eb883efab50137a45be666cca2
diff --git a/tests/setup_cfg_fmt_test.py b/tests/setup_cfg_fmt_test.py index 677291b..9cfa690 100644 --- a/tests/setup_cfg_fmt_test.py +++ b/tests/setup_cfg_fmt_test.py @@ -20,6 +20,13 @@ def test_ver_type_error(): assert msg == "expected #.#, got '1.2.3'" +def test_ver_type_not_a_version(): + with pytest.raises(argparse.ArgumentTypeError) as excinfo: + _ver_type('wat') + msg, = excinfo.value.args + assert msg == "expected #.#, got 'wat'" + + @pytest.mark.parametrize( ('s', 'expected'), ( @@ -381,6 +388,7 @@ freely, subject to the following restrictions: id='already correct', ), pytest.param('~=3.6', id='weird comparator'), + pytest.param('>=3', id='not enough version segments'), ), ) def test_python_requires_left_alone(tmpdir, s): @@ -662,6 +670,45 @@ def test_min_version_removes_classifiers(tmpdir): ) +def test_python_requires_with_patch_version(tmpdir): + setup_cfg = tmpdir.join('setup.cfg') + setup_cfg.write( + '[metadata]\n' + 'name = pkg\n' + 'version = 1.0\n' + 'classifiers =\n' + ' Programming Language :: Python :: 3\n' + ' Programming Language :: Python :: 3 :: Only\n' + # added this to make sure that it doesn't revert to 3.6 + ' Programming Language :: Python :: 3.6\n' + ' Programming Language :: Python :: 3.7\n' + '\n' + '[options]\n' + 'python_requires = >=3.6.1\n', + ) + + # added this to make sure it doesn't revert to 3.6 + tmpdir.join('tox.ini').write('[tox]\nenvlist=py36\n') + + args = (str(setup_cfg), '--min-py3-version=3.4', '--max-py-version=3.8') + assert main(args) + + assert setup_cfg.read() == ( + '[metadata]\n' + 'name = pkg\n' + 'version = 1.0\n' + 'classifiers =\n' + ' Programming Language :: Python :: 3\n' + ' Programming Language :: Python :: 3 :: Only\n' + ' Programming Language :: Python :: 3.6\n' + ' Programming Language :: Python :: 3.7\n' + ' Programming Language :: Python :: 3.8\n' + '\n' + '[options]\n' + 'python_requires = >=3.6.1\n' + ) + + def test_classifiers_left_alone_for_odd_python_requires(tmpdir): setup_cfg = tmpdir.join('setup.cfg') setup_cfg.write(
python_requires>=3.6.1 should be detected as needing classifiers for 3.6+ currently I think `setup-cfg-fmt` ignores this?
0.0
dff9e90e8ee5d1eb883efab50137a45be666cca2
[ "tests/setup_cfg_fmt_test.py::test_python_requires_with_patch_version" ]
[ "tests/setup_cfg_fmt_test.py::test_ver_type_ok", "tests/setup_cfg_fmt_test.py::test_ver_type_error", "tests/setup_cfg_fmt_test.py::test_ver_type_not_a_version", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[foo-[Ff][Oo][Oo]]", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[FOO-[Ff][Oo][Oo]]", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[licen[sc]e-[Ll][Ii][Cc][Ee][Nn][SsCc][Ee]]", "tests/setup_cfg_fmt_test.py::test_noop", "tests/setup_cfg_fmt_test.py::test_rewrite_requires[install_requires-normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite_requires[setup_requires-normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite[orders", "tests/setup_cfg_fmt_test.py::test_rewrite[normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite[sorts", "tests/setup_cfg_fmt_test.py::test_rewrite[normalize", "tests/setup_cfg_fmt_test.py::test_normalize_lib[no", "tests/setup_cfg_fmt_test.py::test_normalize_lib[whitespace", "tests/setup_cfg_fmt_test.py::test_normalize_lib[<=", "tests/setup_cfg_fmt_test.py::test_normalize_lib[>=", "tests/setup_cfg_fmt_test.py::test_normalize_lib[b/w", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.rst-text/x-rst]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.markdown-text/markdown]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.md-text/markdown]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README-text/plain]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[readme.txt-text/plain]", "tests/setup_cfg_fmt_test.py::test_readme_discover_prefers_file_over_directory", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENSE]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENCE]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENSE.md]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[license.txt]", "tests/setup_cfg_fmt_test.py::test_license_does_not_match_directories", "tests/setup_cfg_fmt_test.py::test_rewrite_sets_license_type_and_classifier", "tests/setup_cfg_fmt_test.py::test_rewrite_identifies_license", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[already", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[weird", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[not", "tests/setup_cfg_fmt_test.py::test_strips_empty_options_and_sections[only", "tests/setup_cfg_fmt_test.py::test_strips_empty_options_and_sections[entire", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_python2_tox_ini", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_tox_ini_dashed_name", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_ignores_insufficient_version_envs", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_from_classifiers", "tests/setup_cfg_fmt_test.py::test_min_py3_version_updates_python_requires", "tests/setup_cfg_fmt_test.py::test_min_py3_version_greater_than_minimum", "tests/setup_cfg_fmt_test.py::test_min_version_removes_classifiers", "tests/setup_cfg_fmt_test.py::test_classifiers_left_alone_for_odd_python_requires", "tests/setup_cfg_fmt_test.py::test_min_py3_version_less_than_minimum", "tests/setup_cfg_fmt_test.py::test_rewrite_extras" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-10-05 22:38:03+00:00
mit
1,197
asottile__setup-cfg-fmt-52
diff --git a/setup_cfg_fmt.py b/setup_cfg_fmt.py index d12d92c..44d3cb3 100644 --- a/setup_cfg_fmt.py +++ b/setup_cfg_fmt.py @@ -4,7 +4,9 @@ import glob import io import os.path import re +import string from typing import Dict +from typing import Generator from typing import List from typing import Match from typing import Optional @@ -69,6 +71,11 @@ LICENSE_TO_CLASSIFIER = { 'Zlib': 'License :: OSI Approved :: zlib/libpng License', } +TOX_TO_CLASSIFIERS = { + 'py': 'Programming Language :: Python :: Implementation :: CPython', + 'pypy': 'Programming Language :: Python :: Implementation :: PyPy', +} + def _adjacent_filename(setup_cfg: str, filename: str) -> str: return os.path.join(os.path.dirname(setup_cfg), filename) @@ -145,6 +152,19 @@ def _parse_python_requires( return minimum, excluded +def _tox_envlist(setup_cfg: str) -> Generator[str, None, None]: + tox_ini = _adjacent_filename(setup_cfg, 'tox.ini') + if os.path.exists(tox_ini): + cfg = configparser.ConfigParser() + cfg.read(tox_ini) + + envlist = cfg.get('tox', 'envlist', fallback='') + if envlist: + for env in envlist.split(','): + env, _, _ = env.strip().partition('-') # py36-foo + yield env + + def _python_requires( setup_cfg: str, *, min_py3_version: Tuple[int, int], ) -> Optional[str]: @@ -158,24 +178,15 @@ def _python_requires( except UnknownVersionError: # assume they know what's up with weird things return current_value - tox_ini = _adjacent_filename(setup_cfg, 'tox.ini') - if os.path.exists(tox_ini): - cfg = configparser.ConfigParser() - cfg.read(tox_ini) - - envlist = cfg.get('tox', 'envlist', fallback='') - if envlist: - for env in envlist.split(','): - env = env.strip() - env, _, _ = env.partition('-') # py36-foo - if ( - env.startswith('py') and - len(env) == 4 and - env[2:].isdigit() - ): - version = _to_ver('.'.join(env[2:])) - if minimum is None or version < minimum[:2]: - minimum = version + for env in _tox_envlist(setup_cfg): + if ( + env.startswith('py') and + len(env) == 4 and + env[2:].isdigit() + ): + version = _to_ver('.'.join(env[2:])) + if minimum is None or version < minimum[:2]: + minimum = version for classifier in classifiers.strip().splitlines(): if classifier.startswith('Programming Language :: Python ::'): @@ -316,6 +327,18 @@ def _trim_py_classifiers( return [s for s in classifiers if _is_ok_classifier(s)] +def _imp_classifiers(setup_cfg: str) -> str: + classifiers = set() + + for env in _tox_envlist(setup_cfg): + # remove trailing digits: py39-django31 + classifier = TOX_TO_CLASSIFIERS.get(env.rstrip(string.digits)) + if classifier is not None: + classifiers.add(classifier) + + return '\n'.join(sorted(classifiers)) + + def format_file( filename: str, *, min_py3_version: Tuple[int, int], @@ -386,6 +409,13 @@ def format_file( f'\n{py_classifiers}' ) + imp_classifiers = _imp_classifiers(filename) + if imp_classifiers: + cfg['metadata']['classifiers'] = ( + cfg['metadata'].get('classifiers', '').rstrip() + + f'\n{imp_classifiers}' + ) + # sort the classifiers if present if 'classifiers' in cfg['metadata']: classifiers = sorted(set(cfg['metadata']['classifiers'].split('\n')))
asottile/setup-cfg-fmt
f53fc7144d52d8214b8129b4dc145193d9c8a3b6
diff --git a/tests/setup_cfg_fmt_test.py b/tests/setup_cfg_fmt_test.py index 9cfa690..097f081 100644 --- a/tests/setup_cfg_fmt_test.py +++ b/tests/setup_cfg_fmt_test.py @@ -482,6 +482,8 @@ def test_guess_python_requires_python2_tox_ini(tmpdir): ' Programming Language :: Python :: 3.5\n' ' Programming Language :: Python :: 3.6\n' ' Programming Language :: Python :: 3.7\n' + ' Programming Language :: Python :: Implementation :: CPython\n' + ' Programming Language :: Python :: Implementation :: PyPy\n' '\n' '[options]\n' 'python_requires = >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*\n' @@ -508,6 +510,7 @@ def test_guess_python_requires_tox_ini_dashed_name(tmpdir): ' Programming Language :: Python :: 3\n' ' Programming Language :: Python :: 3 :: Only\n' ' Programming Language :: Python :: 3.7\n' + ' Programming Language :: Python :: Implementation :: CPython\n' '\n' '[options]\n' 'python_requires = >=3.7\n' @@ -520,7 +523,9 @@ def test_guess_python_requires_ignores_insufficient_version_envs(tmpdir): setup_cfg.write( '[metadata]\n' 'name = pkg\n' - 'version = 1.0\n', + 'version = 1.0\n' + 'classifiers =\n' + ' Programming Language :: Python :: Implementation :: CPython\n', ) assert not main(( @@ -531,6 +536,8 @@ def test_guess_python_requires_ignores_insufficient_version_envs(tmpdir): '[metadata]\n' 'name = pkg\n' 'version = 1.0\n' + 'classifiers =\n' + ' Programming Language :: Python :: Implementation :: CPython\n' ) @@ -703,6 +710,7 @@ def test_python_requires_with_patch_version(tmpdir): ' Programming Language :: Python :: 3.6\n' ' Programming Language :: Python :: 3.7\n' ' Programming Language :: Python :: 3.8\n' + ' Programming Language :: Python :: Implementation :: CPython\n' '\n' '[options]\n' 'python_requires = >=3.6.1\n' @@ -772,6 +780,7 @@ def test_min_py3_version_less_than_minimum(tmpdir): ' Programming Language :: Python :: 3 :: Only\n' ' Programming Language :: Python :: 3.6\n' ' Programming Language :: Python :: 3.7\n' + ' Programming Language :: Python :: Implementation :: CPython\n' '\n' '[options]\n' 'python_requires = >=3.6\n' @@ -808,3 +817,106 @@ def test_rewrite_extras(tmpdir): ' hypothesis\n' ' pytest\n' ) + + +def test_imp_classifiers_from_tox_ini(tmpdir): + tmpdir.join('tox.ini').write('[tox]\nenvlist = py39-django31,pypy3,docs\n') + setup_cfg = tmpdir.join('setup.cfg') + setup_cfg.write( + '[metadata]\n' + 'name = test\n' + 'classifiers =\n' + ' License :: OSI Approved :: MIT License\n' + ' Programming Language :: Python :: 3\n' + ' Programming Language :: Python :: 3 :: Only\n' + ' Programming Language :: Python :: 3.9\n', + ) + + args = (str(setup_cfg), '--min-py3-version=3.9', '--max-py-version=3.9') + assert main(args) + + assert setup_cfg.read() == ( + '[metadata]\n' + 'name = test\n' + 'classifiers =\n' + ' License :: OSI Approved :: MIT License\n' + ' Programming Language :: Python :: 3\n' + ' Programming Language :: Python :: 3 :: Only\n' + ' Programming Language :: Python :: 3.9\n' + ' Programming Language :: Python :: Implementation :: CPython\n' + ' Programming Language :: Python :: Implementation :: PyPy\n' + '\n' + '[options]\n' + 'python_requires = >=3.9\n' + ) + + +def test_imp_classifiers_no_change(tmpdir): + tmpdir.join('tox.ini').write('[tox]\nenvlist = py39,pypy3-django31\n') + setup_cfg = tmpdir.join('setup.cfg') + setup_cfg.write( + '[metadata]\n' + 'name = test\n' + 'classifiers =\n' + ' License :: OSI Approved :: MIT License\n' + ' Programming Language :: Python :: 3\n' + ' Programming Language :: Python :: 3 :: Only\n' + ' Programming Language :: Python :: 3.9\n' + ' Programming Language :: Python :: Implementation :: CPython\n' + ' Programming Language :: Python :: Implementation :: PyPy\n' + '\n' + '[options]\n' + 'python_requires = >=3.9\n', + ) + + args = (str(setup_cfg), '--min-py3-version=3.9', '--max-py-version=3.9') + assert not main(args) + + assert setup_cfg.read() == ( + '[metadata]\n' + 'name = test\n' + 'classifiers =\n' + ' License :: OSI Approved :: MIT License\n' + ' Programming Language :: Python :: 3\n' + ' Programming Language :: Python :: 3 :: Only\n' + ' Programming Language :: Python :: 3.9\n' + ' Programming Language :: Python :: Implementation :: CPython\n' + ' Programming Language :: Python :: Implementation :: PyPy\n' + '\n' + '[options]\n' + 'python_requires = >=3.9\n' + ) + + +def test_imp_classifiers_pypy_only(tmpdir): + tmpdir.join('tox.ini').write('[tox]\nenvlist = pypy3\n') + setup_cfg = tmpdir.join('setup.cfg') + setup_cfg.write( + '[metadata]\n' + 'name = test\n' + 'classifiers =\n' + ' License :: OSI Approved :: MIT License\n' + ' Programming Language :: Python :: 3\n' + ' Programming Language :: Python :: 3 :: Only\n' + ' Programming Language :: Python :: 3.9\n' + '\n' + '[options]\n' + 'python_requires = >=3.9\n', + ) + + args = (str(setup_cfg), '--min-py3-version=3.9', '--max-py-version=3.9') + assert main(args) + + assert setup_cfg.read() == ( + '[metadata]\n' + 'name = test\n' + 'classifiers =\n' + ' License :: OSI Approved :: MIT License\n' + ' Programming Language :: Python :: 3\n' + ' Programming Language :: Python :: 3 :: Only\n' + ' Programming Language :: Python :: 3.9\n' + ' Programming Language :: Python :: Implementation :: PyPy\n' + '\n' + '[options]\n' + 'python_requires = >=3.9\n' + )
Add Implementation :: tags ``` Programming Language :: Python :: Implementation :: CPython Programming Language :: Python :: Implementation :: PyPy ``` can probably use `tox.ini` as a heuristic
0.0
f53fc7144d52d8214b8129b4dc145193d9c8a3b6
[ "tests/setup_cfg_fmt_test.py::test_guess_python_requires_python2_tox_ini", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_tox_ini_dashed_name", "tests/setup_cfg_fmt_test.py::test_python_requires_with_patch_version", "tests/setup_cfg_fmt_test.py::test_min_py3_version_less_than_minimum", "tests/setup_cfg_fmt_test.py::test_imp_classifiers_from_tox_ini", "tests/setup_cfg_fmt_test.py::test_imp_classifiers_pypy_only" ]
[ "tests/setup_cfg_fmt_test.py::test_ver_type_ok", "tests/setup_cfg_fmt_test.py::test_ver_type_error", "tests/setup_cfg_fmt_test.py::test_ver_type_not_a_version", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[foo-[Ff][Oo][Oo]]", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[FOO-[Ff][Oo][Oo]]", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[licen[sc]e-[Ll][Ii][Cc][Ee][Nn][SsCc][Ee]]", "tests/setup_cfg_fmt_test.py::test_noop", "tests/setup_cfg_fmt_test.py::test_rewrite_requires[install_requires-normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite_requires[setup_requires-normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite[orders", "tests/setup_cfg_fmt_test.py::test_rewrite[normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite[sorts", "tests/setup_cfg_fmt_test.py::test_rewrite[normalize", "tests/setup_cfg_fmt_test.py::test_normalize_lib[no", "tests/setup_cfg_fmt_test.py::test_normalize_lib[whitespace", "tests/setup_cfg_fmt_test.py::test_normalize_lib[<=", "tests/setup_cfg_fmt_test.py::test_normalize_lib[>=", "tests/setup_cfg_fmt_test.py::test_normalize_lib[b/w", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.rst-text/x-rst]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.markdown-text/markdown]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.md-text/markdown]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README-text/plain]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[readme.txt-text/plain]", "tests/setup_cfg_fmt_test.py::test_readme_discover_prefers_file_over_directory", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENSE]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENCE]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENSE.md]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[license.txt]", "tests/setup_cfg_fmt_test.py::test_license_does_not_match_directories", "tests/setup_cfg_fmt_test.py::test_rewrite_sets_license_type_and_classifier", "tests/setup_cfg_fmt_test.py::test_rewrite_identifies_license", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[already", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[weird", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[not", "tests/setup_cfg_fmt_test.py::test_strips_empty_options_and_sections[only", "tests/setup_cfg_fmt_test.py::test_strips_empty_options_and_sections[entire", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_ignores_insufficient_version_envs", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_from_classifiers", "tests/setup_cfg_fmt_test.py::test_min_py3_version_updates_python_requires", "tests/setup_cfg_fmt_test.py::test_min_py3_version_greater_than_minimum", "tests/setup_cfg_fmt_test.py::test_min_version_removes_classifiers", "tests/setup_cfg_fmt_test.py::test_classifiers_left_alone_for_odd_python_requires", "tests/setup_cfg_fmt_test.py::test_rewrite_extras", "tests/setup_cfg_fmt_test.py::test_imp_classifiers_no_change" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-10-10 16:31:31+00:00
mit
1,198
asottile__setup-cfg-fmt-54
diff --git a/setup_cfg_fmt.py b/setup_cfg_fmt.py index 44d3cb3..d9f84c8 100644 --- a/setup_cfg_fmt.py +++ b/setup_cfg_fmt.py @@ -236,7 +236,7 @@ def _normalize_req(req: str) -> str: return f'{normalized};{envs}' -BASE_NAME_REGEX = re.compile(r'[^!=><\s@]+') +BASE_NAME_REGEX = re.compile(r'[^!=><\s@~]+') REQ_REGEX = re.compile(r'(===|==|!=|~=|>=?|<=?|@)\s*([^,]+)')
asottile/setup-cfg-fmt
289b5f4aead119c0ebadbbcb092573e63509c019
diff --git a/tests/setup_cfg_fmt_test.py b/tests/setup_cfg_fmt_test.py index 097f081..ceba336 100644 --- a/tests/setup_cfg_fmt_test.py +++ b/tests/setup_cfg_fmt_test.py @@ -231,6 +231,7 @@ def test_rewrite(input_s, expected, tmpdir): pytest.param('req05 <= 2,!=1', 'req05!=1,<=2', id='<= cond at end'), pytest.param('req13 !=2, >= 7', 'req13!=2,>=7', id='>= cond at end'), pytest.param('req14 <=2, >= 1', 'req14>=1,<=2', id='b/w conds sorted'), + pytest.param('req15~=2', 'req15~=2', id='compatible release'), ), ) def test_normalize_lib(lib, expected):
Wrongly formating "compatible release" clause ```diff diff --git a/setup.cfg b/setup.cfg index efc3a0f..662e52c 100644 --- a/setup.cfg +++ b/setup.cfg @@ -43,15 +43,15 @@ console_scripts = [options.extras_require] doc = furo - sphinx~=3.0 - sphinx-autodoc-typehints~=1.10 - sphinxcontrib-autoprogram~=0.1.0 + sphinx-autodoc-typehints~~=1.10 + sphinxcontrib-autoprogram~~=0.1.0 + sphinx~~=3.0 test = - filelock~=3.0 + filelock~~=3.0 pytest>=5,<=6 - pytest-cov~=2.0 + pytest-cov~~=2.0 pytest-mock>=2,<=3 - pytest-xdist~=1.34 + pytest-xdist~~=1.34 typing = mypy==0.790 typing-extensions>=3.7.4.3 ``` https://www.python.org/dev/peps/pep-0440/#compatible-release
0.0
289b5f4aead119c0ebadbbcb092573e63509c019
[ "tests/setup_cfg_fmt_test.py::test_normalize_lib[compatible" ]
[ "tests/setup_cfg_fmt_test.py::test_ver_type_ok", "tests/setup_cfg_fmt_test.py::test_ver_type_error", "tests/setup_cfg_fmt_test.py::test_ver_type_not_a_version", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[foo-[Ff][Oo][Oo]]", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[FOO-[Ff][Oo][Oo]]", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[licen[sc]e-[Ll][Ii][Cc][Ee][Nn][SsCc][Ee]]", "tests/setup_cfg_fmt_test.py::test_noop", "tests/setup_cfg_fmt_test.py::test_rewrite_requires[install_requires-normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite_requires[setup_requires-normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite[orders", "tests/setup_cfg_fmt_test.py::test_rewrite[normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite[sorts", "tests/setup_cfg_fmt_test.py::test_rewrite[normalize", "tests/setup_cfg_fmt_test.py::test_normalize_lib[no", "tests/setup_cfg_fmt_test.py::test_normalize_lib[whitespace", "tests/setup_cfg_fmt_test.py::test_normalize_lib[<=", "tests/setup_cfg_fmt_test.py::test_normalize_lib[>=", "tests/setup_cfg_fmt_test.py::test_normalize_lib[b/w", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.rst-text/x-rst]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.markdown-text/markdown]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.md-text/markdown]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README-text/plain]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[readme.txt-text/plain]", "tests/setup_cfg_fmt_test.py::test_readme_discover_prefers_file_over_directory", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENSE]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENCE]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENSE.md]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[license.txt]", "tests/setup_cfg_fmt_test.py::test_license_does_not_match_directories", "tests/setup_cfg_fmt_test.py::test_rewrite_sets_license_type_and_classifier", "tests/setup_cfg_fmt_test.py::test_rewrite_identifies_license", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[already", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[weird", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[not", "tests/setup_cfg_fmt_test.py::test_strips_empty_options_and_sections[only", "tests/setup_cfg_fmt_test.py::test_strips_empty_options_and_sections[entire", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_python2_tox_ini", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_tox_ini_dashed_name", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_ignores_insufficient_version_envs", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_from_classifiers", "tests/setup_cfg_fmt_test.py::test_min_py3_version_updates_python_requires", "tests/setup_cfg_fmt_test.py::test_min_py3_version_greater_than_minimum", "tests/setup_cfg_fmt_test.py::test_min_version_removes_classifiers", "tests/setup_cfg_fmt_test.py::test_python_requires_with_patch_version", "tests/setup_cfg_fmt_test.py::test_classifiers_left_alone_for_odd_python_requires", "tests/setup_cfg_fmt_test.py::test_min_py3_version_less_than_minimum", "tests/setup_cfg_fmt_test.py::test_rewrite_extras", "tests/setup_cfg_fmt_test.py::test_imp_classifiers_from_tox_ini", "tests/setup_cfg_fmt_test.py::test_imp_classifiers_no_change", "tests/setup_cfg_fmt_test.py::test_imp_classifiers_pypy_only" ]
{ "failed_lite_validators": [ "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2020-10-26 16:29:52+00:00
mit
1,199
asottile__setup-cfg-fmt-59
diff --git a/setup_cfg_fmt.py b/setup_cfg_fmt.py index d9f84c8..1389aba 100644 --- a/setup_cfg_fmt.py +++ b/setup_cfg_fmt.py @@ -339,6 +339,16 @@ def _imp_classifiers(setup_cfg: str) -> str: return '\n'.join(sorted(classifiers)) +def _natural_sort(items: Sequence[str]) -> List[str]: + return sorted( + set(items), + key=lambda s: [ + int(part) if part.isdigit() else part.lower() + for part in re.split(r'(\d+)', s) + ], + ) + + def format_file( filename: str, *, min_py3_version: Tuple[int, int], @@ -418,7 +428,7 @@ def format_file( # sort the classifiers if present if 'classifiers' in cfg['metadata']: - classifiers = sorted(set(cfg['metadata']['classifiers'].split('\n'))) + classifiers = _natural_sort(cfg['metadata']['classifiers'].split('\n')) classifiers = _trim_py_classifiers( classifiers, requires, max_py_version=max_py_version, )
asottile/setup-cfg-fmt
af19bc2a229dd87817243ca2406dddde594d64a2
diff --git a/tests/setup_cfg_fmt_test.py b/tests/setup_cfg_fmt_test.py index ceba336..705b6e3 100644 --- a/tests/setup_cfg_fmt_test.py +++ b/tests/setup_cfg_fmt_test.py @@ -4,6 +4,7 @@ import os import pytest from setup_cfg_fmt import _case_insensitive_glob +from setup_cfg_fmt import _natural_sort from setup_cfg_fmt import _normalize_lib from setup_cfg_fmt import _ver_type from setup_cfg_fmt import main @@ -921,3 +922,25 @@ def test_imp_classifiers_pypy_only(tmpdir): '[options]\n' 'python_requires = >=3.9\n' ) + + +def test_natural_sort(): + classifiers = [ + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.10', + 'Programming Language :: Python :: 3.9', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3 :: Only', + ] + + sorted_classifiers = _natural_sort(classifiers) + + assert sorted_classifiers == [ + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3 :: Only', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Programming Language :: Python :: 3.10', + ]
classifiers should be version sorted notably they currently sort like this which seems bad: ``` Programming Language :: Python :: 3 Programming Language :: Python :: 3 :: Only Programming Language :: Python :: 3.10 Programming Language :: Python :: 3.7 Programming Language :: Python :: 3.8 Programming Language :: Python :: 3.9 ```
0.0
af19bc2a229dd87817243ca2406dddde594d64a2
[ "tests/setup_cfg_fmt_test.py::test_ver_type_ok", "tests/setup_cfg_fmt_test.py::test_ver_type_error", "tests/setup_cfg_fmt_test.py::test_ver_type_not_a_version", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[foo-[Ff][Oo][Oo]]", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[FOO-[Ff][Oo][Oo]]", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[licen[sc]e-[Ll][Ii][Cc][Ee][Nn][SsCc][Ee]]", "tests/setup_cfg_fmt_test.py::test_noop", "tests/setup_cfg_fmt_test.py::test_rewrite_requires[install_requires-normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite_requires[setup_requires-normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite[orders", "tests/setup_cfg_fmt_test.py::test_rewrite[normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite[sorts", "tests/setup_cfg_fmt_test.py::test_rewrite[normalize", "tests/setup_cfg_fmt_test.py::test_normalize_lib[no", "tests/setup_cfg_fmt_test.py::test_normalize_lib[whitespace", "tests/setup_cfg_fmt_test.py::test_normalize_lib[<=", "tests/setup_cfg_fmt_test.py::test_normalize_lib[>=", "tests/setup_cfg_fmt_test.py::test_normalize_lib[b/w", "tests/setup_cfg_fmt_test.py::test_normalize_lib[compatible", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.rst-text/x-rst]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.markdown-text/markdown]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.md-text/markdown]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README-text/plain]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[readme.txt-text/plain]", "tests/setup_cfg_fmt_test.py::test_readme_discover_prefers_file_over_directory", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENSE]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENCE]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENSE.md]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[license.txt]", "tests/setup_cfg_fmt_test.py::test_license_does_not_match_directories", "tests/setup_cfg_fmt_test.py::test_rewrite_sets_license_type_and_classifier", "tests/setup_cfg_fmt_test.py::test_rewrite_identifies_license", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[already", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[weird", "tests/setup_cfg_fmt_test.py::test_python_requires_left_alone[not", "tests/setup_cfg_fmt_test.py::test_strips_empty_options_and_sections[only", "tests/setup_cfg_fmt_test.py::test_strips_empty_options_and_sections[entire", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_python2_tox_ini", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_tox_ini_dashed_name", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_ignores_insufficient_version_envs", "tests/setup_cfg_fmt_test.py::test_guess_python_requires_from_classifiers", "tests/setup_cfg_fmt_test.py::test_min_py3_version_updates_python_requires", "tests/setup_cfg_fmt_test.py::test_min_py3_version_greater_than_minimum", "tests/setup_cfg_fmt_test.py::test_min_version_removes_classifiers", "tests/setup_cfg_fmt_test.py::test_python_requires_with_patch_version", "tests/setup_cfg_fmt_test.py::test_classifiers_left_alone_for_odd_python_requires", "tests/setup_cfg_fmt_test.py::test_min_py3_version_less_than_minimum", "tests/setup_cfg_fmt_test.py::test_rewrite_extras", "tests/setup_cfg_fmt_test.py::test_imp_classifiers_from_tox_ini", "tests/setup_cfg_fmt_test.py::test_imp_classifiers_no_change", "tests/setup_cfg_fmt_test.py::test_imp_classifiers_pypy_only", "tests/setup_cfg_fmt_test.py::test_natural_sort" ]
[]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-12-16 02:16:18+00:00
mit
1,200
asottile__setup-cfg-fmt-6
diff --git a/setup_cfg_fmt.py b/setup_cfg_fmt.py index ef7c2f7..2fb21cf 100644 --- a/setup_cfg_fmt.py +++ b/setup_cfg_fmt.py @@ -1,8 +1,11 @@ import argparse import configparser +import glob import io import os.path +import re from typing import Dict +from typing import Match from typing import Optional from typing import Sequence from typing import Tuple @@ -66,6 +69,30 @@ def _adjacent_filename(setup_cfg: str, filename: str) -> str: return os.path.join(os.path.dirname(setup_cfg), filename) +GLOB_PART = re.compile(r'(\[[^]]+\]|.)') + + +def _case_insensitive_glob(s: str) -> str: + def cb(match: Match[str]) -> str: + match_s = match.group() + if len(match_s) == 1: + return f'[{match_s.upper()}{match_s.lower()}]' + else: + inner = ''.join(f'{c.upper()}{c.lower()}' for c in match_s[1:-1]) + return f'[{inner}]' + + return GLOB_PART.sub(cb, s) + + +def _first_file(setup_cfg: str, prefix: str) -> Optional[str]: + prefix = _case_insensitive_glob(prefix) + path = _adjacent_filename(setup_cfg, prefix) + for filename in glob.iglob(f'{path}*'): + return filename + else: + return None + + def format_file(filename: str) -> bool: with open(filename) as f: contents = f.read() @@ -77,14 +104,23 @@ def format_file(filename: str) -> bool: cfg['metadata']['name'] = cfg['metadata']['name'].replace('-', '_') # if README.md exists, set `long_description` + content type - if os.path.exists(_adjacent_filename(filename, 'README.md')): - cfg['metadata']['long_description'] = 'file: README.md' - cfg['metadata']['long_description_content_type'] = 'text/markdown' + readme = _first_file(filename, 'readme') + if readme is not None: + long_description = f'file: {os.path.basename(readme)}' + cfg['metadata']['long_description'] = long_description + + tags = identify.tags_from_filename(readme) + if 'markdown' in tags: + cfg['metadata']['long_description_content_type'] = 'text/markdown' + elif 'rst' in tags: + cfg['metadata']['long_description_content_type'] = 'text/x-rst' + else: + cfg['metadata']['long_description_content_type'] = 'text/plain' # set license fields if a license exists - license_filename = _adjacent_filename(filename, 'LICENSE') - if os.path.exists(license_filename): - cfg['metadata']['license_file'] = 'LICENSE' + license_filename = _first_file(filename, 'licen[sc]e') + if license_filename is not None: + cfg['metadata']['license_file'] = os.path.basename(license_filename) license_id = identify.license_id(license_filename) if license_id is not None:
asottile/setup-cfg-fmt
75c9d4925ff2548a72eb6c686121484188b3389e
diff --git a/tests/setup_cfg_fmt_test.py b/tests/setup_cfg_fmt_test.py index cfda96a..c01262c 100644 --- a/tests/setup_cfg_fmt_test.py +++ b/tests/setup_cfg_fmt_test.py @@ -1,8 +1,21 @@ import pytest +from setup_cfg_fmt import _case_insensitive_glob from setup_cfg_fmt import main [email protected]( + ('s', 'expected'), + ( + ('foo', '[Ff][Oo][Oo]'), + ('FOO', '[Ff][Oo][Oo]'), + ('licen[sc]e', '[Ll][Ii][Cc][Ee][Nn][SsCc][Ee]'), + ), +) +def test_case_insensitive_glob(s, expected): + assert _case_insensitive_glob(s) == expected + + def test_noop(tmpdir): setup_cfg = tmpdir.join('setup.cfg') setup_cfg.write( @@ -87,8 +100,18 @@ def test_rewrite(input_s, expected, tmpdir): assert setup_cfg.read() == expected -def test_adds_long_description_with_readme(tmpdir): - tmpdir.join('README.md').write('my project!') [email protected]( + ('filename', 'content_type'), + ( + ('README.rst', 'text/x-rst'), + ('README.markdown', 'text/markdown'), + ('README.md', 'text/markdown'), + ('README', 'text/plain'), + ('readme.txt', 'text/plain'), + ), +) +def test_adds_long_description_with_readme(filename, content_type, tmpdir): + tmpdir.join(filename).write('my project!') setup_cfg = tmpdir.join('setup.cfg') setup_cfg.write( '[metadata]\n' @@ -99,16 +122,19 @@ def test_adds_long_description_with_readme(tmpdir): assert main((str(setup_cfg),)) assert setup_cfg.read() == ( - '[metadata]\n' - 'name = pkg\n' - 'version = 1.0\n' - 'long_description = file: README.md\n' - 'long_description_content_type = text/markdown\n' + f'[metadata]\n' + f'name = pkg\n' + f'version = 1.0\n' + f'long_description = file: {filename}\n' + f'long_description_content_type = {content_type}\n' ) -def test_sets_license_file_if_license_exists(tmpdir): - tmpdir.join('LICENSE').write('COPYRIGHT (C) 2019 ME') [email protected]( + 'filename', ('LICENSE', 'LICENCE', 'LICENSE.md', 'license.txt'), +) +def test_sets_license_file_if_license_exists(filename, tmpdir): + tmpdir.join(filename).write('COPYRIGHT (C) 2019 ME') setup_cfg = tmpdir.join('setup.cfg') setup_cfg.write( '[metadata]\n' @@ -119,10 +145,10 @@ def test_sets_license_file_if_license_exists(tmpdir): assert main((str(setup_cfg),)) assert setup_cfg.read() == ( - '[metadata]\n' - 'name = pkg\n' - 'version = 1.0\n' - 'license_file = LICENSE\n' + f'[metadata]\n' + f'name = pkg\n' + f'version = 1.0\n' + f'license_file = {filename}\n' )
Identify other types of READMEs https://github.com/asottile/setup-cfg-fmt/blob/3492c51eaa557e645c78a217de82f54ba6df75a3/setup_cfg_fmt.py#L46-L49 Might be able to leverage [`identify`](https://github.com/chriskuehl/identify) as well
0.0
75c9d4925ff2548a72eb6c686121484188b3389e
[ "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[foo-[Ff][Oo][Oo]]", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[FOO-[Ff][Oo][Oo]]", "tests/setup_cfg_fmt_test.py::test_case_insensitive_glob[licen[sc]e-[Ll][Ii][Cc][Ee][Nn][SsCc][Ee]]", "tests/setup_cfg_fmt_test.py::test_noop", "tests/setup_cfg_fmt_test.py::test_rewrite[orders", "tests/setup_cfg_fmt_test.py::test_rewrite[normalizes", "tests/setup_cfg_fmt_test.py::test_rewrite[sorts", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.rst-text/x-rst]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.markdown-text/markdown]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README.md-text/markdown]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[README-text/plain]", "tests/setup_cfg_fmt_test.py::test_adds_long_description_with_readme[readme.txt-text/plain]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENSE]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENCE]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[LICENSE.md]", "tests/setup_cfg_fmt_test.py::test_sets_license_file_if_license_exists[license.txt]", "tests/setup_cfg_fmt_test.py::test_rewrite_sets_license_type_and_classifier", "tests/setup_cfg_fmt_test.py::test_rewrite_identifies_license" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_hyperlinks" ], "has_test_patch": true, "is_lite": false }
2019-02-23 23:13:40+00:00
mit
1,201
asottile__tokenize-rt-3
diff --git a/README.md b/README.md index 3e9e23c..6fdf84d 100644 --- a/README.md +++ b/README.md @@ -5,8 +5,9 @@ tokenize-rt =========== The stdlib `tokenize` module does not properly roundtrip. This wrapper -around the stdlib provides an additional token `UNIMPORTANT_WS`, and a `Token` -data type. Use `src_to_tokens` and `tokens_to_src` to roundtrip. +around the stdlib provides two additional tokens `ESCAPED_NL` and +`UNIMPORTANT_WS`, and a `Token` data type. Use `src_to_tokens` and +`tokens_to_src` to roundtrip. This library is useful if you're writing a refactoring tool based on the python tokenization. @@ -21,6 +22,8 @@ python tokenization. ### `tokenize_rt.tokens_to_src(Sequence[Token]) -> text` +### `tokenize_rt.ECSAPED_NL` + ### `tokenize_rt.UNIMPORTANT_WS` ### `tokenize_rt.Token(name, src, line=None, utf8_byte_offset=None)` @@ -28,9 +31,9 @@ python tokenization. Construct a token - `name`: one of the token names listed in `token.tok_name` or - `UNIMPORTANT_WS` + `ESCAPED_NL` or `UNIMPORTANT_WS` - `src`: token's source as text - `line`: the line number that this token appears on. This will be `None` for - `UNIMPORTANT_WS` tokens. + `ESCAPED_NL` and `UNIMPORTANT_WS` tokens. - `utf8_byte_offset`: the utf8 byte offset that this token appears on in the - line. This will be `None` for `UNIMPORTANT_WS` tokens. + line. This will be `None` for `ESCAPED_NL` and `UNIMPORTANT_WS` tokens. diff --git a/tokenize_rt.py b/tokenize_rt.py index bc5ca7d..4513200 100644 --- a/tokenize_rt.py +++ b/tokenize_rt.py @@ -7,6 +7,7 @@ import io import tokenize +ESCAPED_NL = 'ESCAPED_NL' UNIMPORTANT_WS = 'UNIMPORTANT_WS' Token = collections.namedtuple( 'Token', ('name', 'src', 'line', 'utf8_byte_offset'), @@ -32,8 +33,16 @@ def src_to_tokens(src): newtok += lines[lineno] if scol > 0: newtok += lines[sline][:scol] + + # a multiline unimportant whitespace may contain escaped newlines + while '\\\n' in newtok: + ws, nl, newtok = newtok.partition('\\\n') + if ws: + tokens.append(Token(UNIMPORTANT_WS, ws)) + tokens.append(Token(ESCAPED_NL, nl)) if newtok: tokens.append(Token(UNIMPORTANT_WS, newtok)) + elif scol > last_col: tokens.append(Token(UNIMPORTANT_WS, line[last_col:scol]))
asottile/tokenize-rt
8054f9c9edcc217c5224772b1df87beffdbafd53
diff --git a/tests/tokenize_rt_test.py b/tests/tokenize_rt_test.py index d01f0fb..6977e5f 100644 --- a/tests/tokenize_rt_test.py +++ b/tests/tokenize_rt_test.py @@ -5,6 +5,7 @@ import io import pytest +from tokenize_rt import ESCAPED_NL from tokenize_rt import main from tokenize_rt import src_to_tokens from tokenize_rt import Token @@ -26,6 +27,41 @@ def test_src_to_tokens_simple(): ] +def test_src_to_tokens_escaped_nl(): + src = ( + 'x = \\\n' + ' 5' + ) + ret = src_to_tokens(src) + assert ret == [ + Token('NAME', 'x', line=1, utf8_byte_offset=0), + Token(UNIMPORTANT_WS, ' ', line=None, utf8_byte_offset=None), + Token('OP', '=', line=1, utf8_byte_offset=2), + Token(UNIMPORTANT_WS, ' ', line=None, utf8_byte_offset=None), + Token(ESCAPED_NL, '\\\n', line=None, utf8_byte_offset=None), + Token(UNIMPORTANT_WS, ' ', line=None, utf8_byte_offset=None), + Token('NUMBER', '5', line=2, utf8_byte_offset=4), + Token('ENDMARKER', '', line=3, utf8_byte_offset=0), + ] + + +def test_src_to_tokens_escaped_nl_no_left_ws(): + src = ( + 'x =\\\n' + ' 5' + ) + ret = src_to_tokens(src) + assert ret == [ + Token('NAME', 'x', line=1, utf8_byte_offset=0), + Token(UNIMPORTANT_WS, ' ', line=None, utf8_byte_offset=None), + Token('OP', '=', line=1, utf8_byte_offset=2), + Token(ESCAPED_NL, '\\\n', line=None, utf8_byte_offset=None), + Token(UNIMPORTANT_WS, ' ', line=None, utf8_byte_offset=None), + Token('NUMBER', '5', line=2, utf8_byte_offset=4), + Token('ENDMARKER', '', line=3, utf8_byte_offset=0), + ] + + @pytest.mark.parametrize( 'filename', (
Consider emitting an `ESCAPED_NL` token For example: ```python x = y.\ foo( bar, ) ``` The current tokenization is: ``` 1:0 NAME 'x' ?:? UNIMPORTANT_WS ' ' 1:2 OP '=' ?:? UNIMPORTANT_WS ' ' 1:4 NAME 'y' 1:5 OP '.' ?:? UNIMPORTANT_WS '\\\n ' 2:4 NAME 'foo' 2:7 OP '(' 2:8 NL '\n' ?:? UNIMPORTANT_WS ' ' 3:8 NAME 'bar' 3:11 OP ',' 3:12 NL '\n' ?:? UNIMPORTANT_WS ' ' 4:4 OP ')' 4:5 NEWLINE '\n' 5:0 ENDMARKER '' ``` It would be cool to split the UNIMPORTANT_WS token which contains the escaped newline
0.0
8054f9c9edcc217c5224772b1df87beffdbafd53
[ "tests/tokenize_rt_test.py::test_src_to_tokens_simple", "tests/tokenize_rt_test.py::test_roundtrip_tokenize[testing/resources/empty.py]", "tests/tokenize_rt_test.py::test_roundtrip_tokenize[testing/resources/unicode_snowman.py]", "tests/tokenize_rt_test.py::test_roundtrip_tokenize[testing/resources/backslash_continuation.py]", "tests/tokenize_rt_test.py::test_main" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2017-07-14 15:18:45+00:00
mit
1,202
asottile__yesqa-27
diff --git a/yesqa.py b/yesqa.py index 5beb9c7..919b7f5 100644 --- a/yesqa.py +++ b/yesqa.py @@ -39,13 +39,11 @@ def _remove_comment(tokens, i): def _remove_comments(tokens): tokens = list(tokens) for i, token in tokenize_rt.reversed_enumerate(tokens): - if ( - token.name == 'COMMENT' and ( - NOQA_RE.search(token.src) or - NOQA_FILE_RE.search(token.src) - ) - ): - _remove_comment(tokens, i) + if token.name == 'COMMENT': + if NOQA_RE.search(token.src): + _rewrite_noqa_comment(tokens, i, collections.defaultdict(set)) + elif NOQA_FILE_RE.search(token.src): + _remove_comment(tokens, i) return tokens
asottile/yesqa
ad85b55968036d30088048335194733ecaf06c13
diff --git a/tests/yesqa_test.py b/tests/yesqa_test.py index 25fd493..5563293 100644 --- a/tests/yesqa_test.py +++ b/tests/yesqa_test.py @@ -43,6 +43,11 @@ def test_non_utf8_bytes(tmpdir, capsys): '"""\n' + 'a' * 40 + ' ' + 'b' * 60 + '\n""" # noqa\n', # don't rewrite syntax errors 'import x # noqa\nx() = 5\n', + + 'A' * 65 + ' = int\n\n\n' + 'def f():\n' + ' # type: () -> ' + 'A' * 65 + ' # noqa\n' + ' pass\n', ), ) def test_ok(assert_rewrite, src): @@ -76,6 +81,10 @@ def test_ok(assert_rewrite, src): '# hello world\n' 'os\n', ), + ( + '# a # noqa: E501\n', + '# a\n', + ), # file comments ('# flake8: noqa\nx = 1\n', 'x = 1\n'), ('x = 1 # flake8: noqa\n', 'x = 1\n'),
Skip # noqa check on typing I have a usecase that pep8 `max-line-length` is set to `79` and at the same time I have a type annotation that exceeds `79` characters. For example: ``` # type: () -> Optional[List[Tuple[str, str, None, None, None, None, None]]] ``` I tried to search for multiline annotation but got nothing. I wonder whether we can remove end line noqa check on python typing comment?
0.0
ad85b55968036d30088048335194733ecaf06c13
[ "tests/yesqa_test.py::test_ok[AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "tests/yesqa_test.py::test_rewrite[#" ]
[ "tests/yesqa_test.py::test_non_utf8_bytes", "tests/yesqa_test.py::test_ok[]", "tests/yesqa_test.py::test_ok[#", "tests/yesqa_test.py::test_ok[import", "tests/yesqa_test.py::test_ok[\"\"\"\\naaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "tests/yesqa_test.py::test_rewrite[x", "tests/yesqa_test.py::test_rewrite[import", "tests/yesqa_test.py::test_rewrite[try:\\n", "tests/yesqa_test.py::test_main" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2019-05-08 23:46:17+00:00
mit
1,203
asottile__yesqa-4
diff --git a/yesqa.py b/yesqa.py index 008dc57..40cf153 100644 --- a/yesqa.py +++ b/yesqa.py @@ -43,14 +43,28 @@ def _remove_comments(tokens): def _rewrite_noqa_comment(tokens, i, flake8_results): + # find logical lines that this noqa comment may affect + lines = set() + j = i + while j >= 0 and tokens[j].name not in {'NL', 'NEWLINE'}: + t = tokens[j] + if t.line is not None: + lines.update(range(t.line, t.line + t.src.count('\n') + 1)) + j -= 1 + + lints = set() + for line in lines: + lints.update(flake8_results[line]) + token = tokens[i] match = NOQA_RE.match(token.src) + # exclude all lints on the line but no lints - if token.line not in flake8_results: + if not lints: _remove_comment(tokens, i) elif match.group().lower() != '# noqa': codes = set(SEP_RE.split(match.group(1)[2:])) - expected_codes = codes & flake8_results[token.line] + expected_codes = codes & lints if expected_codes != codes: comment = '# noqa: {}'.format(','.join(sorted(expected_codes))) tokens[i] = token._replace(src=NOQA_RE.sub(comment, token.src))
asottile/yesqa
52da14636029e7e8cc70c6a61912c14fa27ca50e
diff --git a/tests/yesqa_test.py b/tests/yesqa_test.py index e0225c8..9043a86 100644 --- a/tests/yesqa_test.py +++ b/tests/yesqa_test.py @@ -32,9 +32,11 @@ def test_non_utf8_bytes(tmpdir, capsys): ( '', # noop '# hello\n', # comment at beginning of file - 'import os # noqa\n', # still needed - 'import os # NOQA\n', # still needed - 'import os # noqa: F401\n', # still needed + # still needed + 'import os # noqa\n', + 'import os # NOQA\n', + 'import os # noqa: F401\n', + '"""\n' + 'a' * 40 + ' ' + 'b' * 60 + '\n""" # noqa\n', ), ) def test_ok(assert_rewrite, src):
False positive: removes `noqa` on multi-line string ```python """ aaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb """ # noqa ``` ```console $ flake8 test.py $ yesqa test.py Rewriting test.py $ flake8 test.py test.py:2:80: E501 line too long (82 > 79 characters) ```
0.0
52da14636029e7e8cc70c6a61912c14fa27ca50e
[ "tests/yesqa_test.py::test_ok[\"\"\"\\naaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" ]
[ "tests/yesqa_test.py::test_non_utf8_bytes", "tests/yesqa_test.py::test_ok[]", "tests/yesqa_test.py::test_ok[#", "tests/yesqa_test.py::test_ok[import", "tests/yesqa_test.py::test_rewrite[x", "tests/yesqa_test.py::test_rewrite[import", "tests/yesqa_test.py::test_rewrite[#", "tests/yesqa_test.py::test_main" ]
{ "failed_lite_validators": [ "has_short_problem_statement" ], "has_test_patch": true, "is_lite": false }
2017-12-31 16:32:27+00:00
mit
1,204
asottile__yesqa-41
diff --git a/yesqa.py b/yesqa.py index 478cbe3..431a8f8 100644 --- a/yesqa.py +++ b/yesqa.py @@ -72,18 +72,25 @@ def _rewrite_noqa_comment( match = NOQA_RE.search(token.src) assert match is not None + def _remove_noqa() -> None: + assert match is not None + if match.group() == token.src: + _remove_comment(tokens, i) + else: + src = NOQA_RE.sub('', token.src).strip() + if not src.startswith('#'): + src = f'# {src}' + tokens[i] = token._replace(src=src) + # exclude all lints on the line but no lints - if not lints and match.group() == token.src: - _remove_comment(tokens, i) - elif not lints: - src = NOQA_RE.sub('', token.src).strip() - if not src.startswith('#'): - src = f'# {src}' - tokens[i] = token._replace(src=src) + if not lints: + _remove_noqa() elif match.group().lower() != '# noqa': codes = set(SEP_RE.split(match.group(1)[1:])) expected_codes = codes & lints - if expected_codes != codes: + if not expected_codes: + _remove_noqa() + elif expected_codes != codes: comment = f'# noqa: {", ".join(sorted(expected_codes))}' tokens[i] = token._replace(src=NOQA_RE.sub(comment, token.src))
asottile/yesqa
45017e8d68c03701e03e0cf5c4054dfd14c0014f
diff --git a/tests/yesqa_test.py b/tests/yesqa_test.py index 84a604e..6e90ada 100644 --- a/tests/yesqa_test.py +++ b/tests/yesqa_test.py @@ -81,6 +81,13 @@ def test_ok(assert_rewrite, src): '# a # noqa: E501\n', '# a\n', ), + pytest.param( + 'if x==1: # noqa: F401\n' + ' pass\n', + 'if x==1:\n' + ' pass\n', + id='wrong noqa', + ), # file comments ('# flake8: noqa\nx = 1\n', 'x = 1\n'), ('x = 1 # flake8: noqa\n', 'x = 1\n'),
Can convert limited noqa's to generic noqa's If you have a line of code that has a flake8 error, but different from the one listed in a noqa comment, the tool will convert `# noqa: X000` to `# noqa:` which then masks the other error. Example: ``` if x==2: # noqa: E101 pass ``` becomes: ``` if x==2: # noqa: pass ``` which now suppresses E225
0.0
45017e8d68c03701e03e0cf5c4054dfd14c0014f
[ "tests/yesqa_test.py::test_rewrite[wrong" ]
[ "tests/yesqa_test.py::test_non_utf8_bytes", "tests/yesqa_test.py::test_ok[]", "tests/yesqa_test.py::test_ok[#", "tests/yesqa_test.py::test_ok[import", "tests/yesqa_test.py::test_ok[\"\"\"\\naaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "tests/yesqa_test.py::test_ok[AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "tests/yesqa_test.py::test_rewrite[x", "tests/yesqa_test.py::test_rewrite[import", "tests/yesqa_test.py::test_rewrite[#", "tests/yesqa_test.py::test_rewrite[try:\\n", "tests/yesqa_test.py::test_main" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-06-06 03:07:05+00:00
mit
1,205
asottile__yesqa-44
diff --git a/yesqa.py b/yesqa.py index 431a8f8..860cb44 100644 --- a/yesqa.py +++ b/yesqa.py @@ -27,8 +27,13 @@ def _run_flake8(filename: str) -> Dict[int, Set[str]]: out, _ = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate() ret: Dict[int, Set[str]] = collections.defaultdict(set) for line in out.decode().splitlines(): - lineno, code = line.split('\t') - ret[int(lineno)].add(code) + # TODO: use --no-show-source when that is released instead + try: + lineno, code = line.split('\t') + except ValueError: + pass # ignore additional output besides our --format + else: + ret[int(lineno)].add(code) return ret
asottile/yesqa
b13a51aa54142c59219c764e9f9362c049b439ed
diff --git a/tests/yesqa_test.py b/tests/yesqa_test.py index 0cf703c..75d1081 100644 --- a/tests/yesqa_test.py +++ b/tests/yesqa_test.py @@ -107,3 +107,13 @@ def test_main(tmpdir, capsys): assert g.read() == 'x = 1\n' out, _ = capsys.readouterr() assert out == f'Rewriting {g}\n' + + +def test_show_source_in_config(tmpdir, capsys): + f = tmpdir.join('f.py') + f.write('import os # noqa\n') + tmpdir.join('tox.ini').write('[flake8]\nshow_source = true\n') + with tmpdir.as_cwd(): + ret = yesqa.main((str(f),)) + assert ret == 0 + assert f.read() == 'import os # noqa\n'
yesqa fails with ValueError if show-source is enabled When the `flake8` option `show-source` is set to `True`, `yesqa` fails with `ValueError`. ``` Traceback (most recent call last): File ".../bin/yesqa", line 10, in <module> sys.exit(main()) File ".../lib/python3.7/site-packages/yesqa.py", line 158, in main retv |= fix_file(filename) File ".../lib/python3.7/site-packages/yesqa.py", line 123, in fix_file flake8_results = _run_flake8(tmpfile.name) File ".../lib/python3.7/site-packages/yesqa.py", line 30, in _run_flake8 lineno, code = line.split('\t') ValueError: not enough values to unpack (expected 2, got 1) ``` Setting `show-source` to `False` in the flake8 configuration (in my case, `setup.cfg`) fixes the issue.
0.0
b13a51aa54142c59219c764e9f9362c049b439ed
[ "tests/yesqa_test.py::test_show_source_in_config" ]
[ "tests/yesqa_test.py::test_non_utf8_bytes", "tests/yesqa_test.py::test_ok[]", "tests/yesqa_test.py::test_ok[#", "tests/yesqa_test.py::test_ok[import", "tests/yesqa_test.py::test_ok[\"\"\"\\naaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "tests/yesqa_test.py::test_ok[from", "tests/yesqa_test.py::test_ok[AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "tests/yesqa_test.py::test_rewrite[x", "tests/yesqa_test.py::test_rewrite[import", "tests/yesqa_test.py::test_rewrite[#", "tests/yesqa_test.py::test_rewrite[try:\\n", "tests/yesqa_test.py::test_rewrite[wrong", "tests/yesqa_test.py::test_main" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-06-19 17:09:38+00:00
mit
1,206
asottile__yesqa-69
diff --git a/yesqa.py b/yesqa.py index 18ad40f..a0a49eb 100644 --- a/yesqa.py +++ b/yesqa.py @@ -7,6 +7,7 @@ import sys import tempfile from typing import Dict from typing import List +from typing import Match from typing import Optional from typing import Sequence from typing import Set @@ -49,12 +50,24 @@ def _remove_comments(tokens: Tokens) -> Tokens: for i, token in tokenize_rt.reversed_enumerate(tokens): if token.name == 'COMMENT': if NOQA_RE.search(token.src): - _rewrite_noqa_comment(tokens, i, collections.defaultdict(set)) + _mask_noqa_comment(tokens, i) elif NOQA_FILE_RE.search(token.src): _remove_comment(tokens, i) return tokens +def _mask_noqa_comment(tokens: Tokens, i: int) -> None: + token = tokens[i] + match = NOQA_RE.search(token.src) + assert match is not None + + def _sub(match: Match[str]) -> str: + return f'# {"."*(len(match.group())-2)}' + + src = NOQA_RE.sub(_sub, token.src) + tokens[i] = token._replace(src=src) + + def _rewrite_noqa_comment( tokens: Tokens, i: int,
asottile/yesqa
5d8ec12119e236f2f8ed61e29902ed5242ec6126
diff --git a/tests/yesqa_test.py b/tests/yesqa_test.py index 75d1081..b1cb7ef 100644 --- a/tests/yesqa_test.py +++ b/tests/yesqa_test.py @@ -45,6 +45,8 @@ def test_non_utf8_bytes(tmpdir, capsys): 'def f():\n' ' # type: () -> ' + 'A' * 65 + ' # noqa\n' ' pass\n', + 'def foo(w: Sequence[int], x: Sequence[int], y: int, z: int) -> bar: ... # noqa: E501, F821\n', + 'def foo(w: Sequence[int]) -> bar: # foobarfoobarfoobarfoobarfoobarfoo # noqa: E501, F821\n', ), ) def test_ok(assert_rewrite, src):
yesqa turns `# noqa: F821,E501` into `# noqa: F821`, but then flake8 reports it Here's an example: ```console $ cat t.py def foo(w: Sequence[int], x: Sequence[int], y: int, z: int) -> bar: ... # noqa: F821,E501 $ yesqa t.py Rewriting t.py $ cat t.py def foo(w: Sequence[int], x: Sequence[int], y: int, z: int) -> bar: ... # noqa: F821 $ flake8 t.py t.py:1:80: E501 line too long (85 > 79 characters) ```
0.0
5d8ec12119e236f2f8ed61e29902ed5242ec6126
[ "tests/yesqa_test.py::test_ok[def" ]
[ "tests/yesqa_test.py::test_non_utf8_bytes", "tests/yesqa_test.py::test_ok[]", "tests/yesqa_test.py::test_ok[#", "tests/yesqa_test.py::test_ok[import", "tests/yesqa_test.py::test_ok[\"\"\"\\naaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "tests/yesqa_test.py::test_ok[from", "tests/yesqa_test.py::test_ok[AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "tests/yesqa_test.py::test_rewrite[x", "tests/yesqa_test.py::test_rewrite[import", "tests/yesqa_test.py::test_rewrite[#", "tests/yesqa_test.py::test_rewrite[try:\\n", "tests/yesqa_test.py::test_rewrite[wrong", "tests/yesqa_test.py::test_main", "tests/yesqa_test.py::test_show_source_in_config" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2021-04-24 18:53:07+00:00
mit
1,207
asphalt-framework__asphalt-119
diff --git a/docs/versionhistory.rst b/docs/versionhistory.rst index 3d5bdfd..1883fac 100644 --- a/docs/versionhistory.rst +++ b/docs/versionhistory.rst @@ -9,6 +9,8 @@ This library adheres to `Semantic Versioning 2.0 <https://semver.org/>`_. * Asphalt now runs via AnyIO, rather than asyncio, although the asyncio backend is used by default + * The runner now outputs an elaborate tree of component startup tasks if the + application fails to start within the allotted time * Dropped the ``--unsafe`` switch for ``asphalt run`` – configuration files are now always parsed in unsafe mode * Changed configuration parsing to no longer treat dotted keys in configuration diff --git a/src/asphalt/core/_component.py b/src/asphalt/core/_component.py index cdfdf48..8091fd7 100644 --- a/src/asphalt/core/_component.py +++ b/src/asphalt/core/_component.py @@ -6,7 +6,7 @@ from typing import Any from anyio import create_task_group -from ._utils import PluginContainer, merge_config +from ._utils import PluginContainer, merge_config, qualified_name class Component(metaclass=ABCMeta): @@ -105,7 +105,10 @@ class ContainerComponent(Component): async with create_task_group() as tg: for alias, component in self.child_components.items(): - tg.start_soon(component.start) + tg.start_soon( + component.start, + name=f"Starting {qualified_name(component)} ({alias})", + ) class CLIApplicationComponent(ContainerComponent): diff --git a/src/asphalt/core/_runner.py b/src/asphalt/core/_runner.py index d3d1318..008ad0b 100644 --- a/src/asphalt/core/_runner.py +++ b/src/asphalt/core/_runner.py @@ -1,20 +1,30 @@ from __future__ import annotations +import gc import platform +import re import signal import sys +import textwrap +from collections.abc import Coroutine from contextlib import AsyncExitStack +from dataclasses import dataclass, field from functools import partial from logging import INFO, Logger, basicConfig, getLogger from logging.config import dictConfig +from traceback import StackSummary +from types import FrameType from typing import Any, cast from warnings import warn import anyio from anyio import ( + CancelScope, Event, - fail_after, get_cancelled_exc_class, + get_current_task, + get_running_tasks, + sleep, to_thread, ) from anyio.abc import TaskStatus @@ -24,8 +34,12 @@ from ._concurrent import start_service_task from ._context import Context from ._utils import qualified_name +component_task_re = re.compile(r"^Starting (\S+) \((.+)\)$") -async def handle_signals(event: Event, *, task_status: TaskStatus[None]) -> None: + +async def handle_signals( + startup_scope: CancelScope, event: Event, *, task_status: TaskStatus[None] +) -> None: logger = getLogger(__name__) with anyio.open_signal_receiver(signal.SIGTERM, signal.SIGINT) as signals: task_status.started() @@ -35,9 +49,112 @@ async def handle_signals(event: Event, *, task_status: TaskStatus[None]) -> None "Received signal (%s) – terminating application", signal_name.split(":", 1)[0], # macOS has ": <signum>" after the name ) + startup_scope.cancel() event.set() +def get_coro_stack_summary(coro: Any) -> StackSummary: + frames: list[FrameType] = [] + while isinstance(coro, Coroutine): + while coro.__class__.__name__ == "async_generator_asend": + # Hack to get past asend() objects + coro = gc.get_referents(coro)[0].ag_await + + if frame := getattr(coro, "cr_frame", None): + frames.append(frame) + + coro = getattr(coro, "cr_await", None) + + frame_tuples = [(f, f.f_lineno) for f in frames] + return StackSummary.extract(frame_tuples) + + +async def startup_watcher( + startup_cancel_scope: CancelScope, + root_component: Component, + start_timeout: float, + logger: Logger, + *, + task_status: TaskStatus[CancelScope], +) -> None: + current_task = get_current_task() + parent_task = next( + task_info + for task_info in get_running_tasks() + if task_info.id == current_task.parent_id + ) + + with CancelScope() as cancel_scope: + task_status.started(cancel_scope) + await sleep(start_timeout) + + if cancel_scope.cancel_called: + return + + @dataclass + class ComponentStatus: + name: str + alias: str | None + parent_task_id: int | None + traceback: list[str] = field(init=False, default_factory=list) + children: list[ComponentStatus] = field(init=False, default_factory=list) + + component_statuses: dict[int, ComponentStatus] = {} + for task in get_running_tasks(): + if task.id == parent_task.id: + status = ComponentStatus(qualified_name(root_component), None, None) + elif task.name and (match := component_task_re.match(task.name)): + name: str + alias: str + name, alias = match.groups() + status = ComponentStatus(name, alias, task.parent_id) + else: + continue + + status.traceback = get_coro_stack_summary(task.coro).format() + component_statuses[task.id] = status + + root_status: ComponentStatus + for task_id, component_status in component_statuses.items(): + if component_status.parent_task_id is None: + root_status = component_status + elif parent_status := component_statuses.get(component_status.parent_task_id): + parent_status.children.append(component_status) + if parent_status.alias: + component_status.alias = ( + f"{parent_status.alias}.{component_status.alias}" + ) + + def format_status(status_: ComponentStatus, level: int) -> str: + title = f"{status_.alias or 'root'} ({status_.name})" + if status_.children: + children_output = "" + for i, child in enumerate(status_.children): + prefix = "| " if i < (len(status_.children) - 1) else " " + children_output += "+-" + textwrap.indent( + format_status(child, level + 1), + prefix, + lambda line: line[0] in " +|", + ) + + output = title + "\n" + children_output + else: + formatted_traceback = "".join(status_.traceback) + if level == 0: + formatted_traceback = textwrap.indent(formatted_traceback, "| ") + + output = title + "\n" + formatted_traceback + + return output + + logger.error( + "Timeout waiting for the root component to start\n" + "Components still waiting to finish startup:\n%s", + textwrap.indent(format_status(root_status, 0).rstrip(), " "), + ) + startup_cancel_scope.cancel() + + async def _run_application_async( component: Component, logger: Logger, @@ -54,24 +171,34 @@ async def _run_application_async( event = Event() await exit_stack.enter_async_context(Context()) - if platform.system() != "Windows": - await start_service_task( - partial(handle_signals, event), "Asphalt signal handler" - ) + with CancelScope() as startup_scope: + if platform.system() != "Windows": + await start_service_task( + partial(handle_signals, startup_scope, event), + "Asphalt signal handler", + ) + + try: + if start_timeout is not None: + startup_watcher_scope = await start_service_task( + lambda task_status: startup_watcher( + startup_scope, + component, + start_timeout, + logger, + task_status=task_status, + ), + "Asphalt startup watcher task", + ) - try: - with fail_after(start_timeout): await component.start() - except TimeoutError: - logger.error("Timeout waiting for the root component to start") - raise - except get_cancelled_exc_class(): - logger.error("Application startup interrupted") - return 1 - except BaseException: - logger.exception("Error during application startup") - raise + except get_cancelled_exc_class(): + return 1 + except BaseException: + logger.exception("Error during application startup") + return 1 + startup_watcher_scope.cancel() logger.info("Application started") if isinstance(component, CLIApplicationComponent):
asphalt-framework/asphalt
248348d57b604f3fd2a14edb99616c47688bbd1a
diff --git a/tests/test_runner.py b/tests/test_runner.py index ffb334d..11582c7 100644 --- a/tests/test_runner.py +++ b/tests/test_runner.py @@ -2,6 +2,7 @@ from __future__ import annotations import logging import platform +import re import signal from typing import Any, Literal from unittest.mock import patch @@ -11,11 +12,11 @@ import pytest from _pytest.logging import LogCaptureFixture from anyio import to_thread from anyio.lowlevel import checkpoint -from common import raises_in_exception_group from asphalt.core import ( CLIApplicationComponent, Component, + ContainerComponent, add_teardown_callback, get_resource, run_application, @@ -204,11 +205,10 @@ def test_start_exception(caplog: LogCaptureFixture, anyio_backend_name: str) -> """ caplog.set_level(logging.INFO) component = CrashComponent(method="exception") - with raises_in_exception_group( - RuntimeError, match="this should crash the application" - ): + with pytest.raises(SystemExit) as exc_info: run_application(component, backend=anyio_backend_name) + assert exc_info.value.code == 1 records = [ record for record in caplog.records if record.name.startswith("asphalt.core.") ] @@ -219,33 +219,78 @@ def test_start_exception(caplog: LogCaptureFixture, anyio_backend_name: str) -> assert records[3].message == "Application stopped" -def test_start_timeout(caplog: LogCaptureFixture, anyio_backend_name: str) -> None: - """ - Test that when the root component takes too long to start up, the runner exits and - logs the appropriate error message. - """ [email protected]("levels", [1, 2, 3]) +def test_start_timeout( + caplog: LogCaptureFixture, anyio_backend_name: str, levels: int +) -> None: + class StallingComponent(ContainerComponent): + def __init__(self, level: int): + super().__init__() + self.level = level - class StallingComponent(Component): async def start(self) -> None: - # Wait forever for a non-existent resource - await get_resource(float, wait=True) + if self.level == levels: + # Wait forever for a non-existent resource + await get_resource(float, wait=True) + else: + self.add_component("child1", StallingComponent, level=self.level + 1) + self.add_component("child2", StallingComponent, level=self.level + 1) + + await super().start() caplog.set_level(logging.INFO) - component = StallingComponent() - with raises_in_exception_group(TimeoutError): + component = StallingComponent(1) + with pytest.raises(SystemExit) as exc_info: run_application(component, start_timeout=0.1, backend=anyio_backend_name) - records = [ - record for record in caplog.records if record.name == "asphalt.core._runner" - ] - assert len(records) == 4 - assert records[0].message == "Running in development mode" - assert records[1].message == "Starting application" - assert records[2].message.startswith( - "Timeout waiting for the root component to start" + assert exc_info.value.code == 1 + assert len(caplog.messages) == 4 + assert caplog.messages[0] == "Running in development mode" + assert caplog.messages[1] == "Starting application" + assert caplog.messages[2].startswith( + "Timeout waiting for the root component to start\n" + "Components still waiting to finish startup:\n" ) - # assert "-> await ctx.get_resource(float)" in records[2].message - assert records[3].message == "Application stopped" + assert caplog.messages[3] == "Application stopped" + + child_component_re = re.compile(r"([ |]+)\+-([a-z.12]+) \((.+)\)") + lines = caplog.messages[2].splitlines() + expected_test_name = f"{__name__}.test_start_timeout" + assert lines[2] == f" root ({expected_test_name}.<locals>.StallingComponent)" + component_aliases: set[str] = set() + depths: list[int] = [0] * levels + expected_indent = " | " + for line in lines[3:]: + if match := child_component_re.match(line): + indent, alias, component_name = match.groups() + depth = len(alias.split(".")) + depths[depth - 1] += 1 + depths[depth:] = [0] * (len(depths) - depth) + assert len(depths) == levels + assert all(d < 3 for d in depths) + expected_indent = " " + "".join( + (" " if d > 1 else "| ") for d in depths[:depth] + ) + assert component_name == ( + f"{expected_test_name}.<locals>.StallingComponent" + ) + component_aliases.add(alias) + else: + assert line.startswith(expected_indent) + + if levels == 1: + assert not component_aliases + elif levels == 2: + assert component_aliases == {"child1", "child2"} + else: + assert component_aliases == { + "child1", + "child2", + "child1.child1", + "child1.child2", + "child2.child1", + "child2.child2", + } def test_dict_config(caplog: LogCaptureFixture, anyio_backend_name: str) -> None:
More information with timeout Currently, when a component requests a resource that never comes, the application times out without any information as to which component failed to get the resource: ``` ERROR:asphalt.core.runner:Timeout waiting for the root component to start ``` I'm not sure if it's currently possible to give more details. If not, it would be a great enhancement.
0.0
248348d57b604f3fd2a14edb99616c47688bbd1a
[ "tests/test_runner.py::test_start_exception[asyncio]", "tests/test_runner.py::test_start_timeout[asyncio-1]", "tests/test_runner.py::test_start_timeout[asyncio-2]", "tests/test_runner.py::test_start_timeout[asyncio-3]", "tests/test_runner.py::test_start_exception[trio]", "tests/test_runner.py::test_start_timeout[trio-1]", "tests/test_runner.py::test_start_timeout[trio-2]", "tests/test_runner.py::test_start_timeout[trio-3]" ]
[ "tests/test_runner.py::test_run_logging_config[asyncio-disabled]", "tests/test_runner.py::test_run_logging_config[asyncio-loglevel]", "tests/test_runner.py::test_run_logging_config[asyncio-dictconfig]", "tests/test_runner.py::test_run_max_threads[asyncio-None]", "tests/test_runner.py::test_run_max_threads[asyncio-3]", "tests/test_runner.py::test_run_callbacks[asyncio]", "tests/test_runner.py::test_clean_exit[asyncio-keyboard]", "tests/test_runner.py::test_clean_exit[asyncio-sigterm]", "tests/test_runner.py::test_dict_config[asyncio]", "tests/test_runner.py::test_run_cli_application[asyncio]", "tests/test_runner.py::test_run_logging_config[trio-disabled]", "tests/test_runner.py::test_run_logging_config[trio-loglevel]", "tests/test_runner.py::test_run_logging_config[trio-dictconfig]", "tests/test_runner.py::test_run_max_threads[trio-None]", "tests/test_runner.py::test_run_max_threads[trio-3]", "tests/test_runner.py::test_run_callbacks[trio]", "tests/test_runner.py::test_clean_exit[trio-keyboard]", "tests/test_runner.py::test_clean_exit[trio-sigterm]", "tests/test_runner.py::test_dict_config[trio]", "tests/test_runner.py::test_run_cli_application[trio]" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks", "has_pytest_match_arg" ], "has_test_patch": true, "is_lite": false }
2024-04-29 21:46:19+00:00
apache-2.0
1,208
asphalt-framework__asphalt-50
diff --git a/docs/userguide/deployment.rst b/docs/userguide/deployment.rst index 6736615..7f9fd45 100644 --- a/docs/userguide/deployment.rst +++ b/docs/userguide/deployment.rst @@ -17,17 +17,18 @@ Running the launcher is very straightfoward: .. code-block:: bash - asphalt run yourconfig.yaml [your-overrides.yml...] + asphalt run yourconfig.yaml [your-overrides.yml...] [--set path.to.key=val] Or alternatively: - python -m asphalt run yourconfig.yaml [your-overrides.yml...] + python -m asphalt run yourconfig.yaml [your-overrides.yml...] [--set path.to.key=val] What this will do is: #. read all the given configuration files, starting from ``yourconfig.yaml`` -#. merge the configuration files' contents into a single configuration dictionary using - :func:`~asphalt.core.utils.merge_config` +#. read the command line configuration options passed with ``--set``, if any +#. merge the configuration files' contents and the command line configuration options into a single configuration dictionary using + :func:`~asphalt.core.utils.merge_config`. #. call :func:`~asphalt.core.runner.run_application` using the configuration dictionary as keyword arguments @@ -147,8 +148,10 @@ Component configuration can be specified on several levels: * First configuration file argument to ``asphalt run`` * Second configuration file argument to ``asphalt run`` * ... +* Command line configuration options to ``asphalt run --set`` Any options you specify on each level override or augment any options given on previous levels. +The command line configuration options have precedence over the configuration files. To minimize the effort required to build a working configuration file for your application, it is suggested that you pass as many of the options directly in the component initialization code and leave only deployment specific options like API keys, access credentials and such to the @@ -162,12 +165,29 @@ gets passed three keyword arguments: * ``ssl=True`` The first one is provided in the root component code while the other two options come from the YAML -file. You could also override the mailer backend in the configuration file if you wanted. The same -effect can be achieved programmatically by supplying the override configuration to the container -component via its ``components`` constructor argument. This is very useful when writing tests -against your application. For example, you might want to use the ``mock`` mailer in your test suite -configuration to test that the application correctly sends out emails (and to prevent them from -actually being sent to recipients!). +file. You could also override the mailer backend in the configuration file if you wanted, or at the +command line (with the configuration file saved as ``config.yaml``): + +.. code-block:: bash + + asphalt run config.yaml --set component.components.mailer.backend=sendmail + +.. note:: + Note that if you want a ``.`` to be treated as part of an identifier, and not as a separator, + you need to escape it at the command line with ``\``. For instance, in both commands: + + .. code-block:: bash + + asphalt run config.yaml --set "logging.loggers.asphalt\.templating.level=DEBUG" + asphalt run config.yaml --set logging.loggers.asphalt\\.templating.level=DEBUG + + The logging level for the ``asphalt.templating`` logger will be set to ``DEBUG``. + +The same effect can be achieved programmatically by supplying the override configuration to the +container component via its ``components`` constructor argument. This is very useful when writing +tests against your application. For example, you might want to use the ``mock`` mailer in your test +suite configuration to test that the application correctly sends out emails (and to prevent them +from actually being sent to recipients!). There is another neat trick that lets you easily modify a specific key in the configuration. By using dotted notation in a configuration key, you can target a specific key arbitrarily deep in diff --git a/src/asphalt/core/cli.py b/src/asphalt/core/cli.py index 3f4c02d..b1823e5 100644 --- a/src/asphalt/core/cli.py +++ b/src/asphalt/core/cli.py @@ -1,8 +1,10 @@ from __future__ import annotations import os +import re +from collections.abc import Mapping from pathlib import Path -from typing import Any, Dict, Optional +from typing import Any, Dict, List, Optional import click from ruamel.yaml import YAML, ScalarNode @@ -52,7 +54,20 @@ def main() -> None: type=str, help="service to run (if the configuration file contains multiple services)", ) -def run(configfile, unsafe: bool, loop: Optional[str], service: Optional[str]) -> None: [email protected]( + "--set", + "set_", + multiple=True, + type=str, + help="set configuration", +) +def run( + configfile, + unsafe: bool, + loop: Optional[str], + service: Optional[str], + set_: List[str], +) -> None: yaml = YAML(typ="unsafe" if unsafe else "safe") yaml.constructor.add_constructor("!Env", env_constructor) yaml.constructor.add_constructor("!TextFile", text_file_constructor) @@ -67,6 +82,28 @@ def run(configfile, unsafe: bool, loop: Optional[str], service: Optional[str]) - ), "the document root element must be a dictionary" config = merge_config(config, config_data) + # Override config options + for override in set_: + if "=" not in override: + raise click.ClickException( + f"Configuration must be set with '=', got: {override}" + ) + + key, value = override.split("=", 1) + parsed_value = yaml.load(value) + keys = [k.replace(r"\.", ".") for k in re.split(r"(?<!\\)\.", key)] + section = config + for i, part_key in enumerate(keys[:-1]): + section = section.setdefault(part_key, {}) + if not isinstance(section, Mapping): + path = " ⟶ ".join(x for x in keys[: i + 1]) + raise click.ClickException( + f"Cannot apply override for {key!r}: value at {path} is not " + f"a mapping, but {qualified_name(section)}" + ) + + section[keys[-1]] = parsed_value + # Override the event loop policy if specified if loop: config["event_loop_policy"] = loop
asphalt-framework/asphalt
39ff21a7aa0785f7cdb28eebabd011277080f108
diff --git a/tests/test_cli.py b/tests/test_cli.py index c8c22f6..02247a9 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -88,6 +88,38 @@ logging: } +def test_run_bad_override(runner: CliRunner) -> None: + config = """\ + component: + type: does.not.exist:Component +""" + with runner.isolated_filesystem(): + Path("test.yml").write_text(config) + result = runner.invoke(cli.run, ["test.yml", "--set", "foobar"]) + assert result.exit_code == 1 + assert result.stdout == ( + "Error: Configuration must be set with '=', got: foobar\n" + ) + + +def test_run_bad_path(runner: CliRunner) -> None: + config = """\ + component: + type: does.not.exist:Component + listvalue: [] +""" + with runner.isolated_filesystem(): + Path("test.yml").write_text(config) + result = runner.invoke( + cli.run, ["test.yml", "--set", "component.listvalue.foo=1"] + ) + assert result.exit_code == 1 + assert result.stdout == ( + "Error: Cannot apply override for 'component.listvalue.foo': value at " + "component ⟶ listvalue is not a mapping, but list\n" + ) + + def test_run_multiple_configs(runner: CliRunner) -> None: component_class = "{0.__module__}:{0.__name__}".format(DummyComponent) config1 = """\ @@ -106,6 +138,7 @@ logging: component: dummyval1: alternate dummyval2: 10 + dummyval3: foo """ with runner.isolated_filesystem(), patch( @@ -113,7 +146,17 @@ component: ) as run_app: Path("conf1.yml").write_text(config1) Path("conf2.yml").write_text(config2) - result = runner.invoke(cli.run, ["conf1.yml", "conf2.yml"]) + result = runner.invoke( + cli.run, + [ + "conf1.yml", + "conf2.yml", + "--set", + "component.dummyval3=bar", + "--set", + "component.dummyval4=baz", + ], + ) assert result.exit_code == 0 assert run_app.call_count == 1 @@ -124,6 +167,8 @@ component: "type": component_class, "dummyval1": "alternate", "dummyval2": 10, + "dummyval3": "bar", + "dummyval4": "baz", }, "logging": {"version": 1, "disable_existing_loggers": False}, }
Configuration through the command line Asphalt can currently be configured through YAML files, but it would be great to also support configuration through CLI arguments and options, that would take precedence over YAML files.
0.0
39ff21a7aa0785f7cdb28eebabd011277080f108
[ "tests/test_cli.py::test_run_bad_override", "tests/test_cli.py::test_run_bad_path", "tests/test_cli.py::test_run_multiple_configs" ]
[ "tests/test_cli.py::test_run[safe-default]", "tests/test_cli.py::test_run[safe-override]", "tests/test_cli.py::test_run[unsafe-default]", "tests/test_cli.py::test_run[unsafe-override]", "tests/test_cli.py::TestServices::test_run_service[server]", "tests/test_cli.py::TestServices::test_run_service[client]", "tests/test_cli.py::TestServices::test_service_not_found", "tests/test_cli.py::TestServices::test_no_service_selected", "tests/test_cli.py::TestServices::test_bad_services_type", "tests/test_cli.py::TestServices::test_no_services_defined", "tests/test_cli.py::TestServices::test_run_only_service", "tests/test_cli.py::TestServices::test_run_default_service", "tests/test_cli.py::TestServices::test_service_env_variable", "tests/test_cli.py::TestServices::test_service_env_variable_override" ]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-11-21 13:35:39+00:00
apache-2.0
1,209
astamminger__zotero-bibtize-19
diff --git a/zotero_bibtize/zotero_bibtize.py b/zotero_bibtize/zotero_bibtize.py index 2acf9e5..7c98628 100644 --- a/zotero_bibtize/zotero_bibtize.py +++ b/zotero_bibtize/zotero_bibtize.py @@ -57,11 +57,24 @@ class BibEntry(object): unescaped = self.unescape_bibtex_entry_string(raw_entry_string) unescaped = re.sub(r'^(\s*)|(\s*)$', '', unescaped) entry_match = re.match(r'^\@([\s\S]*?)\{([\s\S]*?)\}$', unescaped) - entry_type = entry_match.group(1) - entry_content = re.split(',\n', entry_match.group(2)) - # if the last field entry is followed by a comma the last entry - # in the list will be '' which will lead to issued further - # upstream, thus we check here and remove an emtpy entry + entry_type, entry_content = entry_match.group(1, 2) + # check if the unescaped bibtex entry is valid + if not self._is_balanced(entry_content): + raise Exception("Found braces unbalanced after unescaping of " + "BibTeX entry. The offending entry was\n\n" + "{}".format(raw_entry_string)) + entry_content = [] + tmp_entry = '' + for part in re.split(r",", entry_match.group(2)): + tmp_entry += re.sub(r'\n', '', part) + # since _is_balanced also returns True for strings containing + # no braces at this also works for the initial bibentry key + if self._is_balanced(tmp_entry): + entry_content.append(re.sub(r'\n', '', tmp_entry)) + tmp_entry = '' + else: # re-introduce comma if unbalanced + tmp_entry += ',' + # remove possible emtpy entry at the end of the array if not entry_content[-1]: entry_content = entry_content[:-1] # return type, original zotero key and the actual content list @@ -114,6 +127,16 @@ class BibEntry(object): entry = entry.replace(word, word.lstrip("{").rstrip("}")) return entry + def _is_balanced(self, string): + """ + Check if opening and closing curly braces are balanced in string. + + :param str string: string to be checked for balanced braces + """ + n_open = len(re.findall(r"\{", string)) + n_close = len(re.findall(r"\}", string)) + return n_open == n_close + def __str__(self): # return bibtex entry as string content = ['@{}{{{}'.format(self.type, self.key)]
astamminger/zotero-bibtize
8433104b8ad5b61726996951e342e3cc354fd427
diff --git a/tests/zotero_bibtize/test_bibtex_entry.py b/tests/zotero_bibtize/test_bibtex_entry.py index b9e4ecc..d67b9ee 100644 --- a/tests/zotero_bibtize/test_bibtex_entry.py +++ b/tests/zotero_bibtize/test_bibtex_entry.py @@ -81,9 +81,7 @@ bibtex_entry_types = [ @pytest.mark.parametrize(('bibtex_entry_type'), bibtex_entry_types) def test_entry_type_is_recognized(bibtex_entry_type): from zotero_bibtize.zotero_bibtize import BibEntry - #entry_string = (r"@{:}{{key,{{field = {{}}}}" - # .format(bibtex_entry_type)) - entry_string = r"@{:}{{key,{{}}".format(bibtex_entry_type) + entry_string = r"@{:}{{key,}}".format(bibtex_entry_type) bibentry = BibEntry(entry_string) # check parsed type matches wanted type assert bibentry.type == bibtex_entry_type @@ -238,8 +236,8 @@ def test_multiple_replacement_of_capitalized(): # words (i.e. embraced by curly braces) input_entry = ( "@bibtextype{bibkey,", - " field1 = {Has \\ce{{Command}}},", - " field2 = {Has same word {Command}}", + " field1 = {Has \\ce{{Command}}},", + " field2 = {Has same word {Command}}", "}", "", ) @@ -247,3 +245,29 @@ def test_multiple_replacement_of_capitalized(): bibentry = BibEntry(input_entry) assert bibentry.fields['field1'] == "Has \\ce{Command}" assert bibentry.fields['field2'] == "Has same word Command" + + +def test_splitting_for_containing_termination_sequence(): + """ + Regression test for Issue #18 + https://github.com/astamminger/zotero-bibtize/issues/18 + """ + from zotero_bibtize.zotero_bibtize import BibEntry + input_entry = ( + "@bibtextype{bibkey,", + " field1 = {Regular Field Without Newlines},", + " field2 = {Field containing,\n termination sequence}", + "}", + "", + ) + input_entry = "\n".join(input_entry) + bibentry = BibEntry(input_entry) + input_entry = ( + "@bibtextype{bibkey,", + " field1 = {Regular Field Without Newlines},", + " field2 = {Field {containing},\n termination sequence}", + "}", + "", + ) + input_entry = "\n".join(input_entry) + bibentry = BibEntry(input_entry)
Assumed BibTex termination sequence for entry fields is incomplete Currently every entry field of a BibTex entry is assumed to be terminated by the sequence `,\n` and the entries are split accordingly. This leads to issues, especially for abstract fields which likely may contain this sequence, leading to a erroneous splitting of entries. The termination sequence should thus be extended to check if `,\n` is preceded by `}` which closes the BibText entry field, i.e. the origin regex `,\n` should be replaced with `(?<=\}),\n`.
0.0
8433104b8ad5b61726996951e342e3cc354fd427
[ "tests/zotero_bibtize/test_bibtex_entry.py::test_splitting_for_containing_termination_sequence" ]
[ "tests/zotero_bibtize/test_bibtex_entry.py::test_remove_zotero_custom_escapes[{\\\\textbar}-|]", "tests/zotero_bibtize/test_bibtex_entry.py::test_remove_zotero_custom_escapes[{\\\\textless}-<]", "tests/zotero_bibtize/test_bibtex_entry.py::test_remove_zotero_custom_escapes[{\\\\textgreater}->]", "tests/zotero_bibtize/test_bibtex_entry.py::test_remove_zotero_custom_escapes[{\\\\textasciitilde}-~]", "tests/zotero_bibtize/test_bibtex_entry.py::test_remove_zotero_custom_escapes[{\\\\textasciicircum}-^]", "tests/zotero_bibtize/test_bibtex_entry.py::test_remove_zotero_custom_escapes[{\\\\textbackslash}-\\\\]", "tests/zotero_bibtize/test_bibtex_entry.py::test_remove_zotero_custom_escapes[\\\\{\\\\vphantom{\\\\}}-{]", "tests/zotero_bibtize/test_bibtex_entry.py::test_remove_zotero_custom_escapes[\\\\vphantom{\\\\{}\\\\}-}]", "tests/zotero_bibtize/test_bibtex_entry.py::test_remove_zotero_special_chars_escapes[\\\\#-#]", "tests/zotero_bibtize/test_bibtex_entry.py::test_remove_zotero_special_chars_escapes[\\\\%-%]", "tests/zotero_bibtize/test_bibtex_entry.py::test_remove_zotero_special_chars_escapes[\\\\&-&]", "tests/zotero_bibtize/test_bibtex_entry.py::test_remove_zotero_special_chars_escapes[\\\\$-$]", "tests/zotero_bibtize/test_bibtex_entry.py::test_remove_zotero_special_chars_escapes[\\\\_-_]", "tests/zotero_bibtize/test_bibtex_entry.py::test_remove_zotero_special_chars_escapes[\\\\{-{]", "tests/zotero_bibtize/test_bibtex_entry.py::test_remove_zotero_special_chars_escapes[\\\\}-}]", "tests/zotero_bibtize/test_bibtex_entry.py::test_remove_curly_braces_from_capitalized", "tests/zotero_bibtize/test_bibtex_entry.py::test_entry_type_is_recognized[article]", "tests/zotero_bibtize/test_bibtex_entry.py::test_entry_type_is_recognized[book]", "tests/zotero_bibtize/test_bibtex_entry.py::test_entry_type_is_recognized[booklet]", "tests/zotero_bibtize/test_bibtex_entry.py::test_entry_type_is_recognized[conference]", "tests/zotero_bibtize/test_bibtex_entry.py::test_entry_type_is_recognized[incollection]", "tests/zotero_bibtize/test_bibtex_entry.py::test_entry_type_is_recognized[inproceedings]", "tests/zotero_bibtize/test_bibtex_entry.py::test_entry_type_is_recognized[manual]", "tests/zotero_bibtize/test_bibtex_entry.py::test_entry_type_is_recognized[mastersthesis]", "tests/zotero_bibtize/test_bibtex_entry.py::test_entry_type_is_recognized[misc]", "tests/zotero_bibtize/test_bibtex_entry.py::test_entry_type_is_recognized[phdthesis]", "tests/zotero_bibtize/test_bibtex_entry.py::test_entry_type_is_recognized[proceedings]", "tests/zotero_bibtize/test_bibtex_entry.py::test_entry_type_is_recognized[techreport]", "tests/zotero_bibtize/test_bibtex_entry.py::test_entry_type_is_recognized[unpublished]", "tests/zotero_bibtize/test_bibtex_entry.py::test_bibtex_fields_are_recognized", "tests/zotero_bibtize/test_bibtex_entry.py::test_output_string_assembly", "tests/zotero_bibtize/test_bibtex_entry.py::test_field_label_and_contents", "tests/zotero_bibtize/test_bibtex_entry.py::test_ignore_custom_fields", "tests/zotero_bibtize/test_bibtex_entry.py::test_fields_containing_equal_signs", "tests/zotero_bibtize/test_bibtex_entry.py::test_multiple_replacement_of_capitalized" ]
{ "failed_lite_validators": [], "has_test_patch": true, "is_lite": true }
2020-04-23 20:22:39+00:00
mit
1,210
astanin__python-tabulate-152
diff --git a/setup.py b/setup.py index 1cb6a84..00be096 100644 --- a/setup.py +++ b/setup.py @@ -46,6 +46,7 @@ setup( author_email="[email protected]", url="https://github.com/astanin/python-tabulate", license="MIT", + python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*", classifiers=[ "Development Status :: 4 - Beta", "License :: OSI Approved :: MIT License", @@ -58,6 +59,7 @@ setup( "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", "Topic :: Software Development :: Libraries", ], py_modules=["tabulate"], diff --git a/tabulate.py b/tabulate.py index 0579fb3..4afcd0d 100644 --- a/tabulate.py +++ b/tabulate.py @@ -572,6 +572,10 @@ _invisible_codes_link = re.compile( _ansi_color_reset_code = "\033[0m" +_float_with_thousands_separators = re.compile( + r"^(([+-]?[0-9]{1,3})(?:,([0-9]{3}))*)?(?(1)\.[0-9]*|\.[0-9]+)?$" +) + def simple_separated_format(separator): """Construct a simple TableFormat with columns separated by a separator. @@ -593,6 +597,39 @@ def simple_separated_format(separator): ) +def _isnumber_with_thousands_separator(string): + """ + >>> _isnumber_with_thousands_separator(".") + False + >>> _isnumber_with_thousands_separator("1") + True + >>> _isnumber_with_thousands_separator("1.") + True + >>> _isnumber_with_thousands_separator(".1") + True + >>> _isnumber_with_thousands_separator("1000") + False + >>> _isnumber_with_thousands_separator("1,000") + True + >>> _isnumber_with_thousands_separator("1,0000") + False + >>> _isnumber_with_thousands_separator("1,000.1234") + True + >>> _isnumber_with_thousands_separator(b"1,000.1234") + True + >>> _isnumber_with_thousands_separator("+1,000.1234") + True + >>> _isnumber_with_thousands_separator("-1,000.1234") + True + """ + try: + string = string.decode() + except (UnicodeDecodeError, AttributeError): + pass + + return bool(re.match(_float_with_thousands_separators, string)) + + def _isconvertible(conv, string): try: conv(string) @@ -701,9 +738,11 @@ def _afterpoint(string): -1 >>> _afterpoint("123e45") 2 + >>> _afterpoint("123,456.78") + 2 """ - if _isnumber(string): + if _isnumber(string) or _isnumber_with_thousands_separator(string): if _isint(string): return -1 else:
astanin/python-tabulate
b2c26bcb70e497f674b38aa7e29de12c0123708a
diff --git a/test/test_internal.py b/test/test_internal.py index 44765cf..681ee7b 100644 --- a/test/test_internal.py +++ b/test/test_internal.py @@ -31,6 +31,36 @@ def test_align_column_decimal(): assert_equal(output, expected) +def test_align_column_decimal_with_thousand_separators(): + "Internal: _align_column(..., 'decimal')" + column = ["12.345", "-1234.5", "1.23", "1,234.5", "1e+234", "1.0e234"] + output = T._align_column(column, "decimal") + expected = [ + " 12.345 ", + "-1234.5 ", + " 1.23 ", + "1,234.5 ", + " 1e+234 ", + " 1.0e234", + ] + assert_equal(output, expected) + + +def test_align_column_decimal_with_incorrect_thousand_separators(): + "Internal: _align_column(..., 'decimal')" + column = ["12.345", "-1234.5", "1.23", "12,34.5", "1e+234", "1.0e234"] + output = T._align_column(column, "decimal") + expected = [ + " 12.345 ", + " -1234.5 ", + " 1.23 ", + "12,34.5 ", + " 1e+234 ", + " 1.0e234", + ] + assert_equal(output, expected) + + def test_align_column_none(): "Internal: _align_column(..., None)" column = ["123.4", "56.7890"]
Float with comma formatting are mis-aligned When using commas in `floatfmt`, like `,.2f`, alignment is off: ``` In [32]: print(tabulate([("a", 3456.321), ("b", 982.6513)], floatfmt=".2f")) - ------- a 3456.32 b 982.65 - ------- In [33]: print(tabulate([("a", 3456.321), ("b", 982.6513)], floatfmt=",.2f")) - ----------- a 3,456.32 b 982.65 - ----------- ```
0.0
b2c26bcb70e497f674b38aa7e29de12c0123708a
[ "test/test_internal.py::test_align_column_decimal_with_thousand_separators" ]
[ "test/test_internal.py::test_multiline_width", "test/test_internal.py::test_align_column_decimal", "test/test_internal.py::test_align_column_decimal_with_incorrect_thousand_separators", "test/test_internal.py::test_align_column_none", "test/test_internal.py::test_align_column_multiline", "test/test_internal.py::test_wrap_text_to_colwidths", "test/test_internal.py::test_wrap_text_to_numbers", "test/test_internal.py::test_wrap_text_to_colwidths_single_ansi_colors_full_cell", "test/test_internal.py::test_wrap_text_to_colwidths_multi_ansi_colors_full_cell", "test/test_internal.py::test_wrap_text_to_colwidths_multi_ansi_colors_in_subset" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2021-10-14 18:06:45+00:00
mit
1,211
astanin__python-tabulate-21
diff --git a/tabulate.py b/tabulate.py index 92164fb..99b6118 100755 --- a/tabulate.py +++ b/tabulate.py @@ -1423,7 +1423,11 @@ def tabulate( has_invisible = re.search(_invisible_codes, plain_text) enable_widechars = wcwidth is not None and WIDE_CHARS_MODE - if tablefmt in multiline_formats and _is_multiline(plain_text): + if ( + not isinstance(tablefmt, TableFormat) + and tablefmt in multiline_formats + and _is_multiline(plain_text) + ): tablefmt = multiline_formats.get(tablefmt, tablefmt) is_multiline = True else:
astanin/python-tabulate
e7daa576ff444f95c560b18ef0bb22b3b1b67b57
diff --git a/test/test_regression.py b/test/test_regression.py index 8cdfcb2..e79aad8 100644 --- a/test/test_regression.py +++ b/test/test_regression.py @@ -4,7 +4,7 @@ from __future__ import print_function from __future__ import unicode_literals -from tabulate import tabulate, _text_type, _long_type +from tabulate import tabulate, _text_type, _long_type, TableFormat, Line, DataRow from common import assert_equal, assert_in, SkipTest @@ -365,3 +365,21 @@ def test_empty_pipe_table_with_columns(): expected = "\n".join(["| Col1 | Col2 |", "|--------|--------|"]) result = tabulate(table, headers, tablefmt="pipe") assert_equal(result, expected) + + +def test_custom_tablefmt(): + "Regression: allow custom TableFormat that specifies with_header_hide (github issue #20)" + tablefmt = TableFormat( + lineabove=Line("", "-", " ", ""), + linebelowheader=Line("", "-", " ", ""), + linebetweenrows=None, + linebelow=Line("", "-", " ", ""), + headerrow=DataRow("", " ", ""), + datarow=DataRow("", " ", ""), + padding=0, + with_header_hide=["lineabove", "linebelow"], + ) + rows = [["foo", "bar"], ["baz", "qux"]] + expected = "\n".join(["A B", "--- ---", "foo bar", "baz qux"]) + result = tabulate(rows, headers=["A", "B"], tablefmt=tablefmt) + assert_equal(result, expected)
Custom TableFormat gives: TypeError: unhashable type: 'list' Cloned tabulate from master (433dfc69f2abba1c463763d33e1fb3bcdd3afe37) and tried to use custom TableFormat: Script: ``` from tabulate import tabulate, TableFormat, Line, DataRow tablefmt = TableFormat( lineabove = Line("", "-", " ", ""), linebelowheader = Line("", "-", " ", ""), linebetweenrows = None, linebelow = Line("", "-", " ", ""), headerrow = DataRow("", " ", ""), datarow = DataRow("", " ", ""), padding = 0, with_header_hide = ["lineabove", "linebelow"]) rows = [ ['foo', 'bar'], ['baz', 'qux'] ] print(tabulate(rows, headers=['A', 'B'], tablefmt=tablefmt)) ``` Output: ``` Traceback (most recent call last): File "<stdin>", line 17, in <module> File "/home/woky/work/test/venv/lib/python3.7/site-packages/tabulate.py", line 1268, in tabulate if tablefmt in multiline_formats and _is_multiline(plain_text): TypeError: unhashable type: 'list' ``` (I'm not the original issue submitter - this is copied from https://bitbucket.org/astanin/python-tabulate/issues/156/custom-tableformat-gives-typeerror)
0.0
e7daa576ff444f95c560b18ef0bb22b3b1b67b57
[ "test/test_regression.py::test_custom_tablefmt" ]
[ "test/test_regression.py::test_ansi_color_in_table_cells", "test/test_regression.py::test_alignment_of_colored_cells", "test/test_regression.py::test_iter_of_iters_with_headers", "test/test_regression.py::test_datetime_values", "test/test_regression.py::test_simple_separated_format", "test/test_regression.py::test_simple_separated_format_with_headers", "test/test_regression.py::test_column_type_of_bytestring_columns", "test/test_regression.py::test_numeric_column_headers", "test/test_regression.py::test_88_256_ANSI_color_codes", "test/test_regression.py::test_column_with_mixed_value_types", "test/test_regression.py::test_latex_escape_special_chars", "test/test_regression.py::test_isconvertible_on_set_values", "test/test_regression.py::test_ansi_color_for_decimal_numbers", "test/test_regression.py::test_alignment_of_decimal_numbers_with_ansi_color", "test/test_regression.py::test_long_integers", "test/test_regression.py::test_colorclass_colors", "test/test_regression.py::test_align_long_integers", "test/test_regression.py::test_boolean_columns", "test/test_regression.py::test_ansi_color_bold_and_fgcolor", "test/test_regression.py::test_empty_table_with_keys_as_header", "test/test_regression.py::test_escape_empty_cell_in_first_column_in_rst", "test/test_regression.py::test_ragged_rows", "test/test_regression.py::test_empty_pipe_table_with_columns" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_git_commit_hash" ], "has_test_patch": true, "is_lite": false }
2019-11-26 02:53:34+00:00
mit
1,212
astanin__python-tabulate-221
diff --git a/README.md b/README.md index d64b99a..07ab28c 100644 --- a/README.md +++ b/README.md @@ -666,18 +666,31 @@ Ver2 19.2 ### Custom column alignment -`tabulate` allows a custom column alignment to override the above. The -`colalign` argument can be a list or a tuple of `stralign` named -arguments. Possible column alignments are: `right`, `center`, `left`, -`decimal` (only for numbers), and `None` (to disable alignment). -Omitting an alignment uses the default. For example: +`tabulate` allows a custom column alignment to override the smart alignment described above. +Use `colglobalalign` to define a global setting. Possible alignments are: `right`, `center`, `left`, `decimal` (only for numbers). +Furthermore, you can define `colalign` for column-specific alignment as a list or a tuple. Possible values are `global` (keeps global setting), `right`, `center`, `left`, `decimal` (only for numbers), `None` (to disable alignment). Missing alignments are treated as `global`. ```pycon ->>> print(tabulate([["one", "two"], ["three", "four"]], colalign=("right",)) ------ ---- - one two -three four ------ ---- +>>> print(tabulate([[1,2,3,4],[111,222,333,444]], colglobalalign='center', colalign = ('global','left','right'))) +--- --- --- --- + 1 2 3 4 +111 222 333 444 +--- --- --- --- +``` + +### Custom header alignment + +Headers' alignment can be defined separately from columns'. Like for columns, you can use: +- `headersglobalalign` to define a header-specific global alignment setting. Possible values are `right`, `center`, `left`, `None` (to follow column alignment), +- `headersalign` list or tuple to further specify header-wise alignment. Possible values are `global` (keeps global setting), `same` (follow column alignment), `right`, `center`, `left`, `None` (to disable alignment). Missing alignments are treated as `global`. + +```pycon +>>> print(tabulate([[1,2,3,4,5,6],[111,222,333,444,555,666]], colglobalalign = 'center', colalign = ('left',), headers = ['h','e','a','d','e','r'], headersglobalalign = 'right', headersalign = ('same','same','left','global','center'))) + +h e a d e r +--- --- --- --- --- --- +1 2 3 4 5 6 +111 222 333 444 555 666 ``` ### Number formatting @@ -1123,5 +1136,5 @@ Bart Broere, Vilhelm Prytz, Alexander Gažo, Hugo van Kemenade, jamescooke, Matt Warner, Jérôme Provensal, Kevin Deldycke, Kian-Meng Ang, Kevin Patterson, Shodhan Save, cleoold, KOLANICH, Vijaya Krishna Kasula, Furcy Pin, Christian Fibich, Shaun Duncan, -Dimitri Papadopoulos. +Dimitri Papadopoulos, Élie Goudout. diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 3b1a1e1..11bb865 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1,5 +1,6 @@ """Pretty-print tabular data.""" +import warnings from collections import namedtuple from collections.abc import Iterable, Sized from html import escape as htmlescape @@ -1318,7 +1319,7 @@ def _bool(val): def _normalize_tabular_data(tabular_data, headers, showindex="default"): - """Transform a supported data type to a list of lists, and a list of headers. + """Transform a supported data type to a list of lists, and a list of headers, with headers padding. Supported tabular data types: @@ -1498,13 +1499,12 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): pass # pad with empty headers for initial columns if necessary + headers_pad = 0 if headers and len(rows) > 0: - nhs = len(headers) - ncols = len(rows[0]) - if nhs < ncols: - headers = [""] * (ncols - nhs) + headers + headers_pad = max(0, len(rows[0]) - len(headers)) + headers = [""] * headers_pad + headers - return rows, headers + return rows, headers, headers_pad def _wrap_text_to_colwidths(list_of_lists, colwidths, numparses=True): @@ -1580,8 +1580,11 @@ def tabulate( missingval=_DEFAULT_MISSINGVAL, showindex="default", disable_numparse=False, + colglobalalign=None, colalign=None, maxcolwidths=None, + headersglobalalign=None, + headersalign=None, rowalign=None, maxheadercolwidths=None, ): @@ -1636,8 +1639,8 @@ def tabulate( - - -- - Column alignment - ---------------- + Column and Headers alignment + ---------------------------- `tabulate` tries to detect column types automatically, and aligns the values properly. By default it aligns decimal points of the @@ -1646,6 +1649,23 @@ def tabulate( (`numalign`, `stralign`) are: "right", "center", "left", "decimal" (only for `numalign`), and None (to disable alignment). + `colglobalalign` allows for global alignment of columns, before any + specific override from `colalign`. Possible values are: None + (defaults according to coltype), "right", "center", "decimal", + "left". + `colalign` allows for column-wise override starting from left-most + column. Possible values are: "global" (no override), "right", + "center", "decimal", "left". + `headersglobalalign` allows for global headers alignment, before any + specific override from `headersalign`. Possible values are: None + (follow columns alignment), "right", "center", "left". + `headersalign` allows for header-wise override starting from left-most + given header. Possible values are: "global" (no override), "same" + (follow column alignment), "right", "center", "left". + + Note on intended behaviour: If there is no `tabular_data`, any column + alignment argument is ignored. Hence, in this case, header + alignment cannot be inferred from column alignment. Table formats ------------- @@ -2065,7 +2085,7 @@ def tabulate( if tabular_data is None: tabular_data = [] - list_of_lists, headers = _normalize_tabular_data( + list_of_lists, headers, headers_pad = _normalize_tabular_data( tabular_data, headers, showindex=showindex ) list_of_lists, separating_lines = _remove_separating_lines(list_of_lists) @@ -2181,11 +2201,21 @@ def tabulate( ] # align columns - aligns = [numalign if ct in [int, float] else stralign for ct in coltypes] + # first set global alignment + if colglobalalign is not None: # if global alignment provided + aligns = [colglobalalign] * len(cols) + else: # default + aligns = [numalign if ct in [int, float] else stralign for ct in coltypes] + # then specific alignements if colalign is not None: assert isinstance(colalign, Iterable) + if isinstance(colalign, str): + warnings.warn(f"As a string, `colalign` is interpreted as {[c for c in colalign]}. Did you mean `colglobalalign = \"{colalign}\"` or `colalign = (\"{colalign}\",)`?", stacklevel=2) for idx, align in enumerate(colalign): - aligns[idx] = align + if not idx < len(aligns): + break + elif align != "global": + aligns[idx] = align minwidths = ( [width_fn(h) + min_padding for h in headers] if headers else [0] * len(cols) ) @@ -2194,17 +2224,35 @@ def tabulate( for c, a, minw in zip(cols, aligns, minwidths) ] + aligns_headers = None if headers: # align headers and add headers t_cols = cols or [[""]] * len(headers) - t_aligns = aligns or [stralign] * len(headers) + # first set global alignment + if headersglobalalign is not None: # if global alignment provided + aligns_headers = [headersglobalalign] * len(t_cols) + else: # default + aligns_headers = aligns or [stralign] * len(headers) + # then specific header alignements + if headersalign is not None: + assert isinstance(headersalign, Iterable) + if isinstance(headersalign, str): + warnings.warn(f"As a string, `headersalign` is interpreted as {[c for c in headersalign]}. Did you mean `headersglobalalign = \"{headersalign}\"` or `headersalign = (\"{headersalign}\",)`?", stacklevel=2) + for idx, align in enumerate(headersalign): + hidx = headers_pad + idx + if not hidx < len(aligns_headers): + break + elif align == "same" and hidx < len(aligns): # same as column align + aligns_headers[hidx] = aligns[hidx] + elif align != "global": + aligns_headers[hidx] = align minwidths = [ max(minw, max(width_fn(cl) for cl in c)) for minw, c in zip(minwidths, t_cols) ] headers = [ _align_header(h, a, minw, width_fn(h), is_multiline, width_fn) - for h, a, minw in zip(headers, t_aligns, minwidths) + for h, a, minw in zip(headers, aligns_headers, minwidths) ] rows = list(zip(*cols)) else: @@ -2219,7 +2267,7 @@ def tabulate( _reinsert_separating_lines(rows, separating_lines) return _format_table( - tablefmt, headers, rows, minwidths, aligns, is_multiline, rowaligns=rowaligns + tablefmt, headers, aligns_headers, rows, minwidths, aligns, is_multiline, rowaligns=rowaligns ) @@ -2350,7 +2398,7 @@ class JupyterHTMLStr(str): return self -def _format_table(fmt, headers, rows, colwidths, colaligns, is_multiline, rowaligns): +def _format_table(fmt, headers, headersaligns, rows, colwidths, colaligns, is_multiline, rowaligns): """Produce a plain-text representation of the table.""" lines = [] hidden = fmt.with_header_hide if (headers and fmt.with_header_hide) else [] @@ -2372,7 +2420,7 @@ def _format_table(fmt, headers, rows, colwidths, colaligns, is_multiline, rowali _append_line(lines, padded_widths, colaligns, fmt.lineabove) if padded_headers: - append_row(lines, padded_headers, padded_widths, colaligns, headerrow) + append_row(lines, padded_headers, padded_widths, headersaligns, headerrow) if fmt.linebelowheader and "linebelowheader" not in hidden: _append_line(lines, padded_widths, colaligns, fmt.linebelowheader)
astanin/python-tabulate
83fd4fb98926c8a6fdf45caa1b91ee8913b64dcb
diff --git a/test/common.py b/test/common.py index d95e84f..4cd3709 100644 --- a/test/common.py +++ b/test/common.py @@ -1,6 +1,6 @@ import pytest # noqa from pytest import skip, raises # noqa - +import warnings def assert_equal(expected, result): print("Expected:\n%s\n" % expected) @@ -27,3 +27,18 @@ def rows_to_pipe_table_str(rows): lines.append(line) return "\n".join(lines) + +def check_warnings(func_args_kwargs, *, num=None, category=None, contain=None): + func, args, kwargs = func_args_kwargs + with warnings.catch_warnings(record=True) as W: + # Causes all warnings to always be triggered inside here. + warnings.simplefilter("always") + func(*args, **kwargs) + # Checks + if num is not None: + assert len(W) == num + if category is not None: + assert all([issubclass(w.category, category) for w in W]) + if contain is not None: + assert all([contain in str(w.message) for w in W]) + diff --git a/test/test_api.py b/test/test_api.py index 046d752..e658e82 100644 --- a/test/test_api.py +++ b/test/test_api.py @@ -48,8 +48,11 @@ def test_tabulate_signature(): ("missingval", ""), ("showindex", "default"), ("disable_numparse", False), + ("colglobalalign", None), ("colalign", None), ("maxcolwidths", None), + ("headersglobalalign", None), + ("headersalign", None), ("rowalign", None), ("maxheadercolwidths", None), ] diff --git a/test/test_output.py b/test/test_output.py index 9043aed..d572498 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -1,7 +1,7 @@ """Test output of the various forms of tabular data.""" import tabulate as tabulate_module -from common import assert_equal, raises, skip +from common import assert_equal, raises, skip, check_warnings from tabulate import tabulate, simple_separated_format, SEPARATING_LINE # _test_table shows @@ -2680,6 +2680,60 @@ def test_colalign_multi_with_sep_line(): expected = " one two\n\nthree four" assert_equal(expected, result) +def test_column_global_and_specific_alignment(): + """ Test `colglobalalign` and `"global"` parameter for `colalign`. """ + table = [[1,2,3,4],[111,222,333,444]] + colglobalalign = 'center' + colalign = ('global','left', 'right') + result = tabulate(table, colglobalalign=colglobalalign, colalign=colalign) + expected = '\n'.join([ + "--- --- --- ---", + " 1 2 3 4", + "111 222 333 444", + "--- --- --- ---"]) + assert_equal(expected, result) + +def test_headers_global_and_specific_alignment(): + """ Test `headersglobalalign` and `headersalign`. """ + table = [[1,2,3,4,5,6],[111,222,333,444,555,666]] + colglobalalign = 'center' + colalign = ('left',) + headers = ['h', 'e', 'a', 'd', 'e', 'r'] + headersglobalalign = 'right' + headersalign = ('same', 'same', 'left', 'global', 'center') + result = tabulate(table, headers=headers, colglobalalign=colglobalalign, colalign=colalign, headersglobalalign=headersglobalalign, headersalign=headersalign) + expected = '\n'.join([ + "h e a d e r", + "--- --- --- --- --- ---", + "1 2 3 4 5 6", + "111 222 333 444 555 666"]) + assert_equal(expected, result) + +def test_colalign_or_headersalign_too_long(): + """ Test `colalign` and `headersalign` too long. """ + table = [[1,2],[111,222]] + colalign = ('global', 'left', 'center') + headers = ['h'] + headersalign = ('center', 'right', 'same') + result = tabulate(table, headers=headers, colalign=colalign, headersalign=headersalign) + expected = '\n'.join([ + " h", + "--- ---", + " 1 2", + "111 222"]) + assert_equal(expected, result) + +def test_warning_when_colalign_or_headersalign_is_string(): + """ Test user warnings when `colalign` or `headersalign` is a string. """ + table = [[1,"bar"]] + opt = { + 'colalign': "center", + 'headers': ['foo', '2'], + 'headersalign': "center"} + check_warnings((tabulate, [table], opt), + num = 2, + category = UserWarning, + contain = "As a string") def test_float_conversions(): "Output: float format parsed"
Feature Request: Enable alignment for header Existing code supports numalign and stralign for aligning numbers and strings. It would be helpful if the header is allowed to have a alignment. Example: ``` +---------------------+-------------+ | message id | occur | +---------------------+-------------+ | trailing-whitespace |. 1 | +---------------------+-------------+ | too-many-statemen |. 1 | +---------------------+-------------+ |too-many-locals |. 1 | +---------------------+-------------+ ``` If the headers are aligned (ex. center) ``` +---------------------+-------------+ | message id | occur | +---------------------+-------------+ | trailing-whitespace |. 1 | +---------------------+-------------+ | too-many-statemen |. 1 | +---------------------+-------------+ |too-many-locals |. 1 | +---------------------+-------------+ ```
0.0
83fd4fb98926c8a6fdf45caa1b91ee8913b64dcb
[ "test/test_api.py::test_tabulate_signature", "test/test_output.py::test_column_global_and_specific_alignment", "test/test_output.py::test_headers_global_and_specific_alignment", "test/test_output.py::test_colalign_or_headersalign_too_long", "test/test_output.py::test_warning_when_colalign_or_headersalign_is_string" ]
[ "test/test_api.py::test_tabulate_formats", "test/test_api.py::test_simple_separated_format_signature", "test/test_output.py::test_plain", "test/test_output.py::test_plain_headerless", "test/test_output.py::test_plain_multiline_headerless", "test/test_output.py::test_plain_multiline", "test/test_output.py::test_plain_multiline_with_links", "test/test_output.py::test_plain_multiline_with_empty_cells", "test/test_output.py::test_plain_multiline_with_empty_cells_headerless", "test/test_output.py::test_plain_maxcolwidth_autowraps", "test/test_output.py::test_plain_maxcolwidth_autowraps_with_sep", "test/test_output.py::test_maxcolwidth_single_value", "test/test_output.py::test_maxcolwidth_pad_tailing_widths", "test/test_output.py::test_maxcolwidth_honor_disable_parsenum", "test/test_output.py::test_plain_maxheadercolwidths_autowraps", "test/test_output.py::test_simple", "test/test_output.py::test_simple_with_sep_line", "test/test_output.py::test_readme_example_with_sep", "test/test_output.py::test_simple_multiline_2", "test/test_output.py::test_simple_multiline_2_with_sep_line", "test/test_output.py::test_simple_headerless", "test/test_output.py::test_simple_headerless_with_sep_line", "test/test_output.py::test_simple_multiline_headerless", "test/test_output.py::test_simple_multiline", "test/test_output.py::test_simple_multiline_with_links", "test/test_output.py::test_simple_multiline_with_empty_cells", "test/test_output.py::test_simple_multiline_with_empty_cells_headerless", "test/test_output.py::test_github", "test/test_output.py::test_grid", "test/test_output.py::test_grid_headerless", "test/test_output.py::test_grid_multiline_headerless", "test/test_output.py::test_grid_multiline", "test/test_output.py::test_grid_multiline_with_empty_cells", "test/test_output.py::test_grid_multiline_with_empty_cells_headerless", "test/test_output.py::test_simple_grid", "test/test_output.py::test_simple_grid_headerless", "test/test_output.py::test_simple_grid_multiline_headerless", "test/test_output.py::test_simple_grid_multiline", "test/test_output.py::test_simple_grid_multiline_with_empty_cells", "test/test_output.py::test_simple_grid_multiline_with_empty_cells_headerless", "test/test_output.py::test_rounded_grid", "test/test_output.py::test_rounded_grid_headerless", "test/test_output.py::test_rounded_grid_multiline_headerless", "test/test_output.py::test_rounded_grid_multiline", "test/test_output.py::test_rounded_grid_multiline_with_empty_cells", "test/test_output.py::test_rounded_grid_multiline_with_empty_cells_headerless", "test/test_output.py::test_heavy_grid", "test/test_output.py::test_heavy_grid_headerless", "test/test_output.py::test_heavy_grid_multiline_headerless", "test/test_output.py::test_heavy_grid_multiline", "test/test_output.py::test_heavy_grid_multiline_with_empty_cells", "test/test_output.py::test_heavy_grid_multiline_with_empty_cells_headerless", "test/test_output.py::test_mixed_grid", "test/test_output.py::test_mixed_grid_headerless", "test/test_output.py::test_mixed_grid_multiline_headerless", "test/test_output.py::test_mixed_grid_multiline", "test/test_output.py::test_mixed_grid_multiline_with_empty_cells", "test/test_output.py::test_mixed_grid_multiline_with_empty_cells_headerless", "test/test_output.py::test_double_grid", "test/test_output.py::test_double_grid_headerless", "test/test_output.py::test_double_grid_multiline_headerless", "test/test_output.py::test_double_grid_multiline", "test/test_output.py::test_double_grid_multiline_with_empty_cells", "test/test_output.py::test_double_grid_multiline_with_empty_cells_headerless", "test/test_output.py::test_fancy_grid", "test/test_output.py::test_fancy_grid_headerless", "test/test_output.py::test_fancy_grid_multiline_headerless", "test/test_output.py::test_fancy_grid_multiline", "test/test_output.py::test_fancy_grid_multiline_with_empty_cells", "test/test_output.py::test_fancy_grid_multiline_with_empty_cells_headerless", "test/test_output.py::test_fancy_grid_multiline_row_align", "test/test_output.py::test_outline", "test/test_output.py::test_outline_headerless", "test/test_output.py::test_simple_outline", "test/test_output.py::test_simple_outline_headerless", "test/test_output.py::test_rounded_outline", "test/test_output.py::test_rounded_outline_headerless", "test/test_output.py::test_heavy_outline", "test/test_output.py::test_heavy_outline_headerless", "test/test_output.py::test_mixed_outline", "test/test_output.py::test_mixed_outline_headerless", "test/test_output.py::test_double_outline", "test/test_output.py::test_double_outline_headerless", "test/test_output.py::test_fancy_outline", "test/test_output.py::test_fancy_outline_headerless", "test/test_output.py::test_pipe", "test/test_output.py::test_pipe_headerless", "test/test_output.py::test_presto", "test/test_output.py::test_presto_headerless", "test/test_output.py::test_presto_multiline_headerless", "test/test_output.py::test_presto_multiline", "test/test_output.py::test_presto_multiline_with_empty_cells", "test/test_output.py::test_presto_multiline_with_empty_cells_headerless", "test/test_output.py::test_orgtbl", "test/test_output.py::test_orgtbl_headerless", "test/test_output.py::test_asciidoc", "test/test_output.py::test_asciidoc_headerless", "test/test_output.py::test_psql", "test/test_output.py::test_psql_headerless", "test/test_output.py::test_psql_multiline_headerless", "test/test_output.py::test_psql_multiline", "test/test_output.py::test_psql_multiline_with_empty_cells", "test/test_output.py::test_psql_multiline_with_empty_cells_headerless", "test/test_output.py::test_pretty", "test/test_output.py::test_pretty_headerless", "test/test_output.py::test_pretty_multiline_headerless", "test/test_output.py::test_pretty_multiline", "test/test_output.py::test_pretty_multiline_with_links", "test/test_output.py::test_pretty_multiline_with_empty_cells", "test/test_output.py::test_pretty_multiline_with_empty_cells_headerless", "test/test_output.py::test_jira", "test/test_output.py::test_jira_headerless", "test/test_output.py::test_rst", "test/test_output.py::test_rst_with_empty_values_in_first_column", "test/test_output.py::test_rst_headerless", "test/test_output.py::test_rst_multiline", "test/test_output.py::test_rst_multiline_with_links", "test/test_output.py::test_rst_multiline_with_empty_cells", "test/test_output.py::test_rst_multiline_with_empty_cells_headerless", "test/test_output.py::test_mediawiki", "test/test_output.py::test_mediawiki_headerless", "test/test_output.py::test_moinmoin", "test/test_output.py::test_youtrack", "test/test_output.py::test_moinmoin_headerless", "test/test_output.py::test_html", "test/test_output.py::test_unsafehtml", "test/test_output.py::test_html_headerless", "test/test_output.py::test_unsafehtml_headerless", "test/test_output.py::test_latex", "test/test_output.py::test_latex_raw", "test/test_output.py::test_latex_headerless", "test/test_output.py::test_latex_booktabs", "test/test_output.py::test_latex_booktabs_headerless", "test/test_output.py::test_textile", "test/test_output.py::test_textile_with_header", "test/test_output.py::test_textile_with_center_align", "test/test_output.py::test_no_data", "test/test_output.py::test_empty_data", "test/test_output.py::test_no_data_without_headers", "test/test_output.py::test_empty_data_without_headers", "test/test_output.py::test_intfmt", "test/test_output.py::test_empty_data_with_headers", "test/test_output.py::test_floatfmt", "test/test_output.py::test_floatfmt_multi", "test/test_output.py::test_colalign_multi", "test/test_output.py::test_colalign_multi_with_sep_line", "test/test_output.py::test_float_conversions", "test/test_output.py::test_missingval", "test/test_output.py::test_missingval_multi", "test/test_output.py::test_column_alignment", "test/test_output.py::test_unaligned_separated", "test/test_output.py::test_dict_like_with_index", "test/test_output.py::test_list_of_lists_with_index", "test/test_output.py::test_list_of_lists_with_index_with_sep_line", "test/test_output.py::test_list_of_lists_with_supplied_index", "test/test_output.py::test_list_of_lists_with_index_firstrow", "test/test_output.py::test_disable_numparse_default", "test/test_output.py::test_disable_numparse_true", "test/test_output.py::test_disable_numparse_list", "test/test_output.py::test_preserve_whitespace" ]
{ "failed_lite_validators": [ "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-11-25 13:54:21+00:00
mit
1,213
astanin__python-tabulate-76
diff --git a/.gitignore b/.gitignore index 1579287..460933e 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,16 @@ dist *~ *.pyc /tabulate.egg-info/ +*.egg* +*.pyc +.* +build/ +.coverage +coverage.xml +dist/ +doc/changelog.rst +venv* +website-build/ +## Unit test / coverage reports +.coverage +.tox diff --git a/README.md b/README.md index ce06dad..7125559 100644 --- a/README.md +++ b/README.md @@ -176,7 +176,7 @@ extensions](http://johnmacfarlane.net/pandoc/README.html#tables): eggs 451 bacon 0 -`github` follows the conventions of Github flavored Markdown. It +`github` follows the conventions of GitHub flavored Markdown. It corresponds to the `pipe` format without alignment colons: >>> print(tabulate(table, headers, tablefmt="github")) @@ -668,9 +668,9 @@ as a number imply that `tabulate`: It may not be suitable for serializing really big tables (but who's going to do that, anyway?) or printing tables in performance sensitive applications. `tabulate` is about two orders of magnitude slower than -simply joining lists of values with a tab, coma or other separator. +simply joining lists of values with a tab, comma, or other separator. -In the same time `tabulate` is comparable to other table +At the same time, `tabulate` is comparable to other table pretty-printers. Given a 10x10 table (a list of lists) of mixed text and numeric data, `tabulate` appears to be slower than `asciitable`, and faster than `PrettyTable` and `texttable` The following mini-benchmark @@ -714,7 +714,7 @@ On Linux `tox` expects to find executables like `python2.6`, `C:\Python26\python.exe`, `C:\Python27\python.exe` and `C:\Python34\python.exe` respectively. -To test only some Python environements, use `-e` option. For example, to +To test only some Python environments, use `-e` option. For example, to test only against Python 2.7 and Python 3.6, run: tox -e py27,py36 diff --git a/tabulate.py b/tabulate.py index 5d57167..65abfd6 100755 --- a/tabulate.py +++ b/tabulate.py @@ -5,17 +5,17 @@ from __future__ import print_function from __future__ import unicode_literals from collections import namedtuple -from platform import python_version_tuple +import sys import re import math -if python_version_tuple() >= ("3", "3", "0"): +if sys.version_info >= (3, 3): from collections.abc import Iterable else: from collections import Iterable -if python_version_tuple()[0] < "3": +if sys.version_info[0] < 3: from itertools import izip_longest from functools import partial @@ -91,9 +91,9 @@ DataRow = namedtuple("DataRow", ["begin", "sep", "end"]) # headerrow # --- linebelowheader --- # datarow -# --- linebewteenrows --- +# --- linebetweenrows --- # ... (more datarows) ... -# --- linebewteenrows --- +# --- linebetweenrows --- # last datarow # --- linebelow --------- # @@ -535,11 +535,14 @@ multiline_formats = { _multiline_codes = re.compile(r"\r|\n|\r\n") _multiline_codes_bytes = re.compile(b"\r|\n|\r\n") _invisible_codes = re.compile( - r"\x1b\[\d+[;\d]*m|\x1b\[\d*\;\d*\;\d*m" + r"\x1b\[\d+[;\d]*m|\x1b\[\d*\;\d*\;\d*m|\x1b\]8;;(.*?)\x1b\\" ) # ANSI color codes _invisible_codes_bytes = re.compile( - b"\x1b\\[\\d+\\[;\\d]*m|\x1b\\[\\d*;\\d*;\\d*m" + b"\x1b\\[\\d+\\[;\\d]*m|\x1b\\[\\d*;\\d*;\\d*m|\\x1b\\]8;;(.*?)\\x1b\\\\" ) # ANSI color codes +_invisible_codes_link = re.compile( + r"\x1B]8;[a-zA-Z0-9:]*;[^\x1B]+\x1B\\([^\x1b]+)\x1B]8;;\x1B\\" +) # Terminal hyperlinks def simple_separated_format(separator): @@ -724,9 +727,15 @@ def _padnone(ignore_width, s): def _strip_invisible(s): - "Remove invisible ANSI color codes." + r"""Remove invisible ANSI color codes. + + >>> str(_strip_invisible('\x1B]8;;https://example.com\x1B\\This is a link\x1B]8;;\x1B\\')) + 'This is a link' + + """ if isinstance(s, _text_type): - return re.sub(_invisible_codes, "", s) + links_removed = re.sub(_invisible_codes_link, "\\1", s) + return re.sub(_invisible_codes, "", links_removed) else: # a bytestring return re.sub(_invisible_codes_bytes, "", s) @@ -894,7 +903,7 @@ def _column_type(strings, has_invisible=True, numparse=True): def _format(val, valtype, floatfmt, missingval="", has_invisible=True): - """Format a value accoding to its type. + """Format a value according to its type. Unicode is supported: @@ -1022,7 +1031,10 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): elif hasattr(tabular_data, "index"): # values is a property, has .index => it's likely a pandas.DataFrame (pandas 0.11.0) keys = list(tabular_data) - if tabular_data.index.name is not None: + if ( + showindex in ["default", "always", True] + and tabular_data.index.name is not None + ): if isinstance(tabular_data.index.name, list): keys[:0] = tabular_data.index.name else: @@ -1469,6 +1481,8 @@ def tabulate( ) has_invisible = re.search(_invisible_codes, plain_text) + if not has_invisible: + has_invisible = re.search(_invisible_codes_link, plain_text) enable_widechars = wcwidth is not None and WIDE_CHARS_MODE if ( not isinstance(tablefmt, TableFormat) diff --git a/tox.ini b/tox.ini index c9f4e98..a20b325 100644 --- a/tox.ini +++ b/tox.ini @@ -8,7 +8,7 @@ # for testing and it is disabled by default. [tox] -envlist = lint, py27, py35, py36, py37, py38 +envlist = lint, py27, py35, py36, py37, py38, py39, py310 [testenv] commands = pytest -v --doctest-modules --ignore benchmark.py @@ -97,6 +97,40 @@ deps = pandas wcwidth + +[testenv:py39] +basepython = python3.9 +commands = pytest -v --doctest-modules --ignore benchmark.py +deps = + pytest + +[testenv:py39-extra] +basepython = python3.9 +commands = pytest -v --doctest-modules --ignore benchmark.py +deps = + pytest + numpy + pandas + wcwidth + + +[testenv:py310] +basepython = python3.10 +commands = pytest -v --doctest-modules --ignore benchmark.py +deps = + pytest + +[testenv:py310-extra] +basepython = python3.10 +setenv = PYTHONDEVMODE = 1 +commands = pytest -v --doctest-modules --ignore benchmark.py +deps = + pytest + numpy + pandas + wcwidth + + [flake8] max-complexity = 22 max-line-length = 99
astanin/python-tabulate
2552e6dfb23cac990aeabb27b86745878d62247e
diff --git a/test/test_output.py b/test/test_output.py index 0e72c71..abab439 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -59,6 +59,22 @@ def test_plain_multiline(): assert_equal(expected, result) +def test_plain_multiline_with_links(): + "Output: plain with multiline cells with links and headers" + table = [[2, "foo\nbar"]] + headers = ("more\nspam \x1b]8;;target\x1b\\eggs\x1b]8;;\x1b\\", "more spam\n& eggs") + expected = "\n".join( + [ + " more more spam", + " spam \x1b]8;;target\x1b\\eggs\x1b]8;;\x1b\\ & eggs", + " 2 foo", + " bar", + ] + ) + result = tabulate(table, headers, tablefmt="plain") + assert_equal(expected, result) + + def test_plain_multiline_with_empty_cells(): "Output: plain with multiline cells and empty cells with headers" table = [ @@ -162,6 +178,23 @@ def test_simple_multiline(): assert_equal(expected, result) +def test_simple_multiline_with_links(): + "Output: simple with multiline cells with links and headers" + table = [[2, "foo\nbar"]] + headers = ("more\nspam \x1b]8;;target\x1b\\eggs\x1b]8;;\x1b\\", "more spam\n& eggs") + expected = "\n".join( + [ + " more more spam", + " spam \x1b]8;;target\x1b\\eggs\x1b]8;;\x1b\\ & eggs", + "----------- -----------", + " 2 foo", + " bar", + ] + ) + result = tabulate(table, headers, tablefmt="simple") + assert_equal(expected, result) + + def test_simple_multiline_with_empty_cells(): "Output: simple with multiline cells and empty cells with headers" table = [ @@ -766,6 +799,25 @@ def test_pretty_multiline(): assert_equal(expected, result) +def test_pretty_multiline_with_links(): + "Output: pretty with multiline cells with headers" + table = [[2, "foo\nbar"]] + headers = ("more\nspam \x1b]8;;target\x1b\\eggs\x1b]8;;\x1b\\", "more spam\n& eggs") + expected = "\n".join( + [ + "+-----------+-----------+", + "| more | more spam |", + "| spam \x1b]8;;target\x1b\\eggs\x1b]8;;\x1b\\ | & eggs |", + "+-----------+-----------+", + "| 2 | foo |", + "| | bar |", + "+-----------+-----------+", + ] + ) + result = tabulate(table, headers, tablefmt="pretty") + assert_equal(expected, result) + + def test_pretty_multiline_with_empty_cells(): "Output: pretty with multiline cells and empty cells with headers" table = [ @@ -889,6 +941,25 @@ def test_rst_multiline(): assert_equal(expected, result) +def test_rst_multiline_with_links(): + "Output: rst with multiline cells with headers" + table = [[2, "foo\nbar"]] + headers = ("more\nspam \x1b]8;;target\x1b\\eggs\x1b]8;;\x1b\\", "more spam\n& eggs") + expected = "\n".join( + [ + "=========== ===========", + " more more spam", + " spam \x1b]8;;target\x1b\\eggs\x1b]8;;\x1b\\ & eggs", + "=========== ===========", + " 2 foo", + " bar", + "=========== ===========", + ] + ) + result = tabulate(table, headers, tablefmt="rst") + assert_equal(expected, result) + + def test_rst_multiline_with_empty_cells(): "Output: rst with multiline cells and empty cells with headers" table = [ @@ -1363,7 +1434,9 @@ def test_pandas_without_index(): import pandas df = pandas.DataFrame( - [["one", 1], ["two", None]], columns=["string", "number"], index=["a", "b"] + [["one", 1], ["two", None]], + columns=["string", "number"], + index=pandas.Index(["a", "b"], name="index"), ) expected = "\n".join( [ diff --git a/test/test_regression.py b/test/test_regression.py index 2324c06..955e11f 100644 --- a/test/test_regression.py +++ b/test/test_regression.py @@ -47,6 +47,52 @@ def test_alignment_of_colored_cells(): assert_equal(expected, formatted) +def test_alignment_of_link_cells(): + "Regression: Align links as if they were colorless." + linktable = [ + ("test", 42, "\x1b]8;;target\x1b\\test\x1b]8;;\x1b\\"), + ("test", 101, "\x1b]8;;target\x1b\\test\x1b]8;;\x1b\\"), + ] + linkheaders = ("test", "\x1b]8;;target\x1b\\test\x1b]8;;\x1b\\", "test") + formatted = tabulate(linktable, linkheaders, "grid") + expected = "\n".join( + [ + "+--------+--------+--------+", + "| test | \x1b]8;;target\x1b\\test\x1b]8;;\x1b\\ | test |", + "+========+========+========+", + "| test | 42 | \x1b]8;;target\x1b\\test\x1b]8;;\x1b\\ |", + "+--------+--------+--------+", + "| test | 101 | \x1b]8;;target\x1b\\test\x1b]8;;\x1b\\ |", + "+--------+--------+--------+", + ] + ) + print("expected: %r\n\ngot: %r\n" % (expected, formatted)) + assert_equal(expected, formatted) + + +def test_alignment_of_link_text_cells(): + "Regression: Align links as if they were colorless." + linktable = [ + ("test", 42, "1\x1b]8;;target\x1b\\test\x1b]8;;\x1b\\2"), + ("test", 101, "3\x1b]8;;target\x1b\\test\x1b]8;;\x1b\\4"), + ] + linkheaders = ("test", "5\x1b]8;;target\x1b\\test\x1b]8;;\x1b\\6", "test") + formatted = tabulate(linktable, linkheaders, "grid") + expected = "\n".join( + [ + "+--------+----------+--------+", + "| test | 5\x1b]8;;target\x1b\\test\x1b]8;;\x1b\\6 | test |", + "+========+==========+========+", + "| test | 42 | 1\x1b]8;;target\x1b\\test\x1b]8;;\x1b\\2 |", + "+--------+----------+--------+", + "| test | 101 | 3\x1b]8;;target\x1b\\test\x1b]8;;\x1b\\4 |", + "+--------+----------+--------+", + ] + ) + print("expected: %r\n\ngot: %r\n" % (expected, formatted)) + assert_equal(expected, formatted) + + def test_iter_of_iters_with_headers(): "Regression: Generator of generators with a gen. of headers (issue #9)."
Support hyperlinks encoded as terminal escape sequences Some terminals support [clickable text](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda) via escape sequences. If we use the escape sequence ```python >>> import tabulate >>> >>> def encode_url(text: str, target:str): ... return f"\u001b]8;;{target}\u001b\\{text}\u001b]8;;\u001b\\" ... >>> table = tabulate.tabulate([[encode_url("test", "http://example.org")]], headers=["test"], tablefmt="grid") >>> print(table) +--------+ | test | +========+ | test | +--------+ ``` tabulate does not calculate the width correctly.
0.0
2552e6dfb23cac990aeabb27b86745878d62247e
[ "test/test_output.py::test_plain_multiline_with_links", "test/test_output.py::test_simple_multiline_with_links", "test/test_output.py::test_pretty_multiline_with_links", "test/test_output.py::test_rst_multiline_with_links", "test/test_regression.py::test_alignment_of_link_cells", "test/test_regression.py::test_alignment_of_link_text_cells" ]
[ "test/test_output.py::test_plain", "test/test_output.py::test_plain_headerless", "test/test_output.py::test_plain_multiline_headerless", "test/test_output.py::test_plain_multiline", "test/test_output.py::test_plain_multiline_with_empty_cells", "test/test_output.py::test_plain_multiline_with_empty_cells_headerless", "test/test_output.py::test_simple", "test/test_output.py::test_simple_multiline_2", "test/test_output.py::test_simple_headerless", "test/test_output.py::test_simple_multiline_headerless", "test/test_output.py::test_simple_multiline", "test/test_output.py::test_simple_multiline_with_empty_cells", "test/test_output.py::test_simple_multiline_with_empty_cells_headerless", "test/test_output.py::test_github", "test/test_output.py::test_grid", "test/test_output.py::test_grid_headerless", "test/test_output.py::test_grid_multiline_headerless", "test/test_output.py::test_grid_multiline", "test/test_output.py::test_grid_multiline_with_empty_cells", "test/test_output.py::test_grid_multiline_with_empty_cells_headerless", "test/test_output.py::test_fancy_grid", "test/test_output.py::test_fancy_grid_headerless", "test/test_output.py::test_fancy_grid_multiline_headerless", "test/test_output.py::test_fancy_grid_multiline", "test/test_output.py::test_fancy_grid_multiline_with_empty_cells", "test/test_output.py::test_fancy_grid_multiline_with_empty_cells_headerless", "test/test_output.py::test_pipe", "test/test_output.py::test_pipe_headerless", "test/test_output.py::test_presto", "test/test_output.py::test_presto_headerless", "test/test_output.py::test_presto_multiline_headerless", "test/test_output.py::test_presto_multiline", "test/test_output.py::test_presto_multiline_with_empty_cells", "test/test_output.py::test_presto_multiline_with_empty_cells_headerless", "test/test_output.py::test_orgtbl", "test/test_output.py::test_orgtbl_headerless", "test/test_output.py::test_psql", "test/test_output.py::test_psql_headerless", "test/test_output.py::test_psql_multiline_headerless", "test/test_output.py::test_psql_multiline", "test/test_output.py::test_psql_multiline_with_empty_cells", "test/test_output.py::test_psql_multiline_with_empty_cells_headerless", "test/test_output.py::test_pretty", "test/test_output.py::test_pretty_headerless", "test/test_output.py::test_pretty_multiline_headerless", "test/test_output.py::test_pretty_multiline", "test/test_output.py::test_pretty_multiline_with_empty_cells", "test/test_output.py::test_pretty_multiline_with_empty_cells_headerless", "test/test_output.py::test_jira", "test/test_output.py::test_jira_headerless", "test/test_output.py::test_rst", "test/test_output.py::test_rst_with_empty_values_in_first_column", "test/test_output.py::test_rst_headerless", "test/test_output.py::test_rst_multiline", "test/test_output.py::test_rst_multiline_with_empty_cells", "test/test_output.py::test_rst_multiline_with_empty_cells_headerless", "test/test_output.py::test_mediawiki", "test/test_output.py::test_mediawiki_headerless", "test/test_output.py::test_moinmoin", "test/test_output.py::test_youtrack", "test/test_output.py::test_moinmoin_headerless", "test/test_output.py::test_html", "test/test_output.py::test_unsafehtml", "test/test_output.py::test_html_headerless", "test/test_output.py::test_unsafehtml_headerless", "test/test_output.py::test_latex", "test/test_output.py::test_latex_raw", "test/test_output.py::test_latex_headerless", "test/test_output.py::test_latex_booktabs", "test/test_output.py::test_latex_booktabs_headerless", "test/test_output.py::test_textile", "test/test_output.py::test_textile_with_header", "test/test_output.py::test_textile_with_center_align", "test/test_output.py::test_no_data", "test/test_output.py::test_empty_data", "test/test_output.py::test_no_data_without_headers", "test/test_output.py::test_empty_data_without_headers", "test/test_output.py::test_floatfmt", "test/test_output.py::test_floatfmt_multi", "test/test_output.py::test_colalign_multi", "test/test_output.py::test_float_conversions", "test/test_output.py::test_missingval", "test/test_output.py::test_missingval_multi", "test/test_output.py::test_column_alignment", "test/test_output.py::test_unaligned_separated", "test/test_output.py::test_dict_like_with_index", "test/test_output.py::test_list_of_lists_with_index", "test/test_output.py::test_list_of_lists_with_supplied_index", "test/test_output.py::test_list_of_lists_with_index_firstrow", "test/test_output.py::test_disable_numparse_default", "test/test_output.py::test_disable_numparse_true", "test/test_output.py::test_disable_numparse_list", "test/test_output.py::test_preserve_whitespace", "test/test_regression.py::test_ansi_color_in_table_cells", "test/test_regression.py::test_alignment_of_colored_cells", "test/test_regression.py::test_iter_of_iters_with_headers", "test/test_regression.py::test_datetime_values", "test/test_regression.py::test_simple_separated_format", "test/test_regression.py::test_simple_separated_format_with_headers", "test/test_regression.py::test_column_type_of_bytestring_columns", "test/test_regression.py::test_numeric_column_headers", "test/test_regression.py::test_88_256_ANSI_color_codes", "test/test_regression.py::test_column_with_mixed_value_types", "test/test_regression.py::test_latex_escape_special_chars", "test/test_regression.py::test_isconvertible_on_set_values", "test/test_regression.py::test_ansi_color_for_decimal_numbers", "test/test_regression.py::test_alignment_of_decimal_numbers_with_ansi_color", "test/test_regression.py::test_long_integers", "test/test_regression.py::test_colorclass_colors", "test/test_regression.py::test_align_long_integers", "test/test_regression.py::test_boolean_columns", "test/test_regression.py::test_ansi_color_bold_and_fgcolor", "test/test_regression.py::test_empty_table_with_keys_as_header", "test/test_regression.py::test_escape_empty_cell_in_first_column_in_rst", "test/test_regression.py::test_ragged_rows", "test/test_regression.py::test_empty_pipe_table_with_columns", "test/test_regression.py::test_custom_tablefmt" ]
{ "failed_lite_validators": [ "has_hyperlinks", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-08-03 21:32:37+00:00
mit
1,214
astarte-platform__astarte-device-sdk-python-98
diff --git a/CHANGELOG.md b/CHANGELOG.md index d2d9f3a..5aae20f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.12.0] - Unreleased +### Fixed +- Sending zero payloads for endpoints in property interfaces was unsetting the property. + ## [0.11.0] - 2023-03-16 ### Added - Initial Astarte Device SDK release diff --git a/astarte/device/device.py b/astarte/device/device.py index 01ccb7b..868d6f5 100644 --- a/astarte/device/device.py +++ b/astarte/device/device.py @@ -498,7 +498,7 @@ class Device: # pylint: disable=too-many-instance-attributes """ bson_payload = b"" - if payload: + if payload is not None: validation_result = self.__validate_data( interface_name, interface_path, payload, timestamp )
astarte-platform/astarte-device-sdk-python
eafef00aab916233f575042231c6ade3cc6720d6
diff --git a/tests/test_device.py b/tests/test_device.py index 07c7713..471e317 100644 --- a/tests/test_device.py +++ b/tests/test_device.py @@ -500,6 +500,45 @@ class UnitTests(unittest.TestCase): qos="reliability value", ) + @mock.patch.object(Client, "publish") + @mock.patch("astarte.device.device.bson.dumps") + @mock.patch.object(Introspection, "get_interface") + def test_send_zero(self, mock_get_interface, mock_bson_dumps, mock_mqtt_publish): + device = self.helper_initialize_device(loop=None) + + mock_mapping = mock.MagicMock() + mock_mapping.reliability = "reliability value" + mock_interface = mock.MagicMock() + mock_interface.validate.return_value = None + mock_interface.get_mapping.return_value = mock_mapping + mock_interface.is_aggregation_object.return_value = False + mock_get_interface.return_value = mock_interface + + mock_bson_dumps.return_value = bytes("bson content", "utf-8") + + interface_name = "interface name" + interface_path = "interface path" + payload = 0 + timestamp = datetime.now() + device.send(interface_name, interface_path, payload, timestamp) + + calls = [ + mock.call(interface_name), + mock.call(interface_name), + mock.call(interface_name), + ] + mock_get_interface.assert_has_calls(calls, any_order=True) + self.assertEqual(mock_get_interface.call_count, 3) + mock_interface.is_aggregation_object.assert_called_once() + mock_interface.validate.assert_called_once_with(interface_path, payload, timestamp) + mock_interface.get_mapping.assert_called_once_with(interface_path) + mock_bson_dumps.assert_called_once_with({"v": payload, "t": timestamp}) + mock_mqtt_publish.assert_called_once_with( + "realm_name/device_id/" + interface_name + interface_path, + bytes("bson content", "utf-8"), + qos="reliability value", + ) + @mock.patch.object(Client, "publish") @mock.patch("astarte.device.device.bson.dumps") @mock.patch.object(Introspection, "get_interface")
Sending empty payloads unsets properties Sending an empty payload through the `send` function for interfaces of type property sends an unset command. The bug originates here: https://github.com/astarte-platform/astarte-device-sdk-python/blob/60a3f88e7ca5089aedc91e29f87a2cc463929a10/astarte/device/device.py#L500-L504 A simple fix can be to change `if payload:` to `if payload is not None:`.
0.0
eafef00aab916233f575042231c6ade3cc6720d6
[ "tests/test_device.py::UnitTests::test_send_zero" ]
[ "tests/test_device.py::UnitTests::test__on_connect", "tests/test_device.py::UnitTests::test__on_connect_connection_result_no_connection", "tests/test_device.py::UnitTests::test__on_connect_with_threading", "tests/test_device.py::UnitTests::test__on_disconnect_good_shutdown", "tests/test_device.py::UnitTests::test__on_disconnect_good_shutdown_with_threading", "tests/test_device.py::UnitTests::test__on_disconnect_invalid_certificate", "tests/test_device.py::UnitTests::test__on_disconnect_other_reason", "tests/test_device.py::UnitTests::test__on_message", "tests/test_device.py::UnitTests::test__on_message_control_message", "tests/test_device.py::UnitTests::test__on_message_incorrect_base_topic", "tests/test_device.py::UnitTests::test__on_message_incorrect_interface", "tests/test_device.py::UnitTests::test__on_message_incorrect_payload", "tests/test_device.py::UnitTests::test__on_message_no_callback", "tests/test_device.py::UnitTests::test__on_message_with_threading", "tests/test_device.py::UnitTests::test_add_interface", "tests/test_device.py::UnitTests::test_add_interface_from_dir", "tests/test_device.py::UnitTests::test_add_interface_from_dir_non_existing_dir_err", "tests/test_device.py::UnitTests::test_add_interface_from_dir_not_a_dir_err", "tests/test_device.py::UnitTests::test_add_interface_from_file", "tests/test_device.py::UnitTests::test_add_interface_from_file_incorrect_json_err", "tests/test_device.py::UnitTests::test_add_interface_from_file_missing_file_err", "tests/test_device.py::UnitTests::test_connect", "tests/test_device.py::UnitTests::test_connect_already_connected", "tests/test_device.py::UnitTests::test_connect_crypto_already_configured", "tests/test_device.py::UnitTests::test_connect_crypto_already_has_certificate", "tests/test_device.py::UnitTests::test_connect_crypto_ignore_ssl_errors", "tests/test_device.py::UnitTests::test_disconnect", "tests/test_device.py::UnitTests::test_get_device_id", "tests/test_device.py::UnitTests::test_initialization_ok", "tests/test_device.py::UnitTests::test_initialization_raises", "tests/test_device.py::UnitTests::test_is_connected", "tests/test_device.py::UnitTests::test_remove_interface", "tests/test_device.py::UnitTests::test_send", "tests/test_device.py::UnitTests::test_send_aggregate", "tests/test_device.py::UnitTests::test_send_aggregate_is_an_aggregate_raises_validation_err", "tests/test_device.py::UnitTests::test_send_aggregate_wrong_payload_type_raises", "tests/test_device.py::UnitTests::test_send_get_qos_no_interface_raises", "tests/test_device.py::UnitTests::test_send_get_qos_no_mapping_raises", "tests/test_device.py::UnitTests::test_send_interface_validate_raises_not_found_err", "tests/test_device.py::UnitTests::test_send_interface_validate_raises_other_err", "tests/test_device.py::UnitTests::test_send_is_an_aggregate_raises_interface_not_found", "tests/test_device.py::UnitTests::test_send_is_an_aggregate_raises_validation_err", "tests/test_device.py::UnitTests::test_send_wrong_payload_type_raises", "tests/test_device.py::UnitTests::test_unset_property", "tests/test_device.py::UnitTests::test_unset_property_interface_not_a_property_raises", "tests/test_device.py::UnitTests::test_unset_property_interface_not_found_raises" ]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2023-07-05 10:04:17+00:00
apache-2.0
1,215
astroML__astroML-237
diff --git a/CHANGES.rst b/CHANGES.rst index 9399114..0418d9d 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,3 +1,9 @@ +1.0.2 (unreleased) +================== + +- Fix bug in ``lumfunc.Cminus`` that lead to return NaN values. [#237] + + 1.0.1 (2020-09-09) ================== diff --git a/astroML/lumfunc.py b/astroML/lumfunc.py index 18a363e..537a385 100644 --- a/astroML/lumfunc.py +++ b/astroML/lumfunc.py @@ -71,10 +71,17 @@ def Cminus(x, y, xmax, ymax): ymax = ymax[i_sort] for j in range(1, Nall): - Ny[j] = np.sum(x[:j] < xmax[j]) + # Making sure we don't divide with 0 later + objects = np.sum(x[:j] < xmax[j]) + if objects: + Ny[j] = objects + else: + Ny[j] = np.inf + Ny[0] = np.inf cuml_y = np.cumprod(1. + 1. / Ny) - Ny[0] = 0 + + Ny[np.isinf(Ny)] = 0 # renormalize cuml_y *= Nall / cuml_y[-1] @@ -87,10 +94,17 @@ def Cminus(x, y, xmax, ymax): ymax = ymax[i_sort] for i in range(1, Nall): - Nx[i] = np.sum(y[:i] < ymax[i]) + # Making sure we don't divide with 0 later + objects = np.sum(y[:i] < ymax[i]) + if objects: + Nx[i] = objects + else: + Nx[i] = np.inf + Nx[0] = np.inf cuml_x = np.cumprod(1. + 1. / Nx) - Nx[0] = 0 + + Nx[np.isinf(Nx)] = 0 # renormalize cuml_x *= Nall / cuml_x[-1]
astroML/astroML
335d040cd5c9cbf2adaa9e16f6c64e2e73d282de
diff --git a/astroML/tests/test_lumfunc.py b/astroML/tests/test_lumfunc.py new file mode 100644 index 0000000..62ab666 --- /dev/null +++ b/astroML/tests/test_lumfunc.py @@ -0,0 +1,13 @@ +import numpy as np +from astroML.lumfunc import Cminus + + +def test_cminus_nans(): + # Regression test for https://github.com/astroML/astroML/issues/234 + + x = [10.02, 10.00] + y = [14.97, 14.99] + xmax = [10.03, 10.01] + ymax = [14.98, 15.00] + + assert np.isfinite(np.sum(Cminus(x, y, xmax, ymax)))
Minor edge case in Cminus leads to nans in output Encountered a situation where cuml_x and cuml_y calculated by astroML.lumfunc.Cminus returns nans. This might only happen with bad luck. Code to reproduce: ``` from astroML.lumfunc import Cminus x, y, xmax, ymax = [10.02, 10.00], [14.97, 14.99], [10.03, 10.01], [14.98, 15.00] Cminus(x, y, xmax, ymax) ``` Output: `(array([0., 0.]), array([0., 0.]), array([ 0., nan]), array([ 0., nan]))` Astrophysical context for the above input: I would like to use the CMinus method to recover the true distributions of distance modulus (DM) and absolute magnitude (Mr), since I am limited by a flux limit of r < 25. Letting x<-DM and y<-Mr, I can calculate xmax and ymax (xmax = r_lim - y and vice versa). Since this example is at a peculiar case where the` x[0] > xmax[1]` this means `Nx[1] = np.sum(x[:1] < xmax[1])` to be 0, which causes `cuml_x = np.cumprod(1. + 1. / Nx)` evaluate to nan (see [source](https://github.com/astroML/astroML/blob/dbc4311fcd144cbd62dd1e32803e2b7738627f6b/astroML/lumfunc.py#L74)). I think this only happens when, after [sorting ](https://github.com/astroML/astroML/blob/dbc4311fcd144cbd62dd1e32803e2b7738627f6b/astroML/lumfunc.py#L67), this unique case comes up where `np.sum(x[:j] < xmax[j]) == 0`, usually for very small j. Saw this while using simulated LSST data. I'm not familiar enough with Cminus to come up with a fix for this edge case, and seemed to show up most often when using astroML.lumfuc.bootstrap_Cminus.
0.0
335d040cd5c9cbf2adaa9e16f6c64e2e73d282de
[ "astroML/tests/test_lumfunc.py::test_cminus_nans" ]
[]
{ "failed_lite_validators": [ "has_many_modified_files" ], "has_test_patch": true, "is_lite": false }
2021-03-03 01:05:17+00:00
bsd-2-clause
1,216
astrochun__chun_codes-11
diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000..38985f9 --- /dev/null +++ b/.coveragerc @@ -0,0 +1,1 @@ +[run] diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml new file mode 100644 index 0000000..c726337 --- /dev/null +++ b/.github/workflows/python-package.yml @@ -0,0 +1,42 @@ +# This workflow will install Python dependencies, run tests and lint with a variety of Python versions +# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions + +name: Python package + +on: + push: + paths-ignore: + - '**.md' + - 'LICENSE' + pull_request: + paths-ignore: + - '**.md' + - 'LICENSE' + +jobs: + build: + + runs-on: ubuntu-latest + # See: https://github.com/marketplace/actions/skip-based-on-commit-message + if: "!contains(github.event.head_commit.message, 'ci skip') || !contains(github.event.head_commit.message, 'skip ci')" + strategy: + matrix: + python-version: ['3.7', '3.8'] + + steps: + - name: Checkout chun_codes + uses: actions/checkout@v2 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install pytest pytest-cov + - name: Install chun_codes + run: | + python setup.py install + - name: Test with pytest + run: | + pytest --cov-report term-missing --cov-config=.coveragerc --cov=chun_codes tests diff --git a/README.md b/README.md index 10cb2fa..c153fdc 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # chun_codes Set of Python 2.7 and 3.xx codes used in astrochun's codes -[![Build Status](https://travis-ci.com/astrochun/chun_codes.svg?branch=master)](https://travis-ci.com/astrochun/chun_codes) +[![GitHub build](https://github.com/astrochun/chun_codes/workflows/Python%20package/badge.svg?branch=master)](https://github.com/astrochun/chun_codes/actions?query=workflow%3A%22Python+package%22) ![GitHub top language](https://img.shields.io/github/languages/top/astrochun/chun_codes) ![GitHub release (latest by date)](https://img.shields.io/github/v/release/astrochun/chun_codes) [![Open Source Love](https://badges.frapsoft.com/os/mit/mit.svg?v=102)](https://github.com/ellerbrock/open-source-badge/) diff --git a/chun_codes/__init__.py b/chun_codes/__init__.py index f059530..56ba287 100644 --- a/chun_codes/__init__.py +++ b/chun_codes/__init__.py @@ -15,7 +15,7 @@ py_vers = sys.version_info.major if py_vers == 2: import pdfmerge -__version__ = "0.6.0" +__version__ = "0.7.0" def systime(): diff --git a/chun_codes/cardelli.py b/chun_codes/cardelli.py index c13503a..18a5509 100644 --- a/chun_codes/cardelli.py +++ b/chun_codes/cardelli.py @@ -2,6 +2,7 @@ import numpy as np from astropy import units as u + def uv_func_mw(x, R): Fa = -0.04473*(x-5.9)**2 - 0.009779*(x-5.9)**3 @@ -16,21 +17,21 @@ def uv_func_mw(x, R): b = -3.090 + 1.825 * x + 1.206/((x-4.62)**2+0.263) + Fb return a + b/R -#enddef + def fuv_func_mw(x, R): a = -1.073 - 0.628 * (x-8) + 0.137*(x-8)**2 - 0.070*(x-8)**3 b = 13.670 + 4.257*(x-8) - 0.420*(x-8)**2 + 0.374*(x-8)**3 return a + b/R -#enddef + def ir_func_mw(x, R): a = 0.574 * x**1.61 b = -0.527 * x**1.61 return a + b/R -#enddef + def opt_func_mw(x, R): y = x - 1.82 @@ -40,10 +41,10 @@ def opt_func_mw(x, R): b = 1.41338 * y + 2.28305 * y**2 + 1.07233 * y**3 - 5.38434 * y**4 - \ 0.62251 * y**5 + 5.30260 * y**6 - 2.09002 * y**7 return a + b/R -#enddef -def cardelli(lambda0, R=3.1): #, extrapolate=False): - ''' + +def cardelli(lambda0, R=3.1): + """ NAME: cardelli @@ -83,36 +84,41 @@ def cardelli(lambda0, R=3.1): #, extrapolate=False): REVISON HISTORY: Created by Chun Ly, 28 June 2016 - ''' + """ # Specify units of lambda0 so that code can convert # Default is R=3.1 t_lam = lambda0.to(u.nm).value - ## Handles individual values, x - if type(t_lam) == 'list': + # Handles individual values, x + if isinstance(t_lam, float): + t_lam = np.array([t_lam]) + if isinstance(t_lam, list): t_lam = np.array(t_lam) - else: - if isinstance(t_lam, (np.ndarray, np.generic)) == False: - t_lam = np.array([t_lam]) + if not isinstance(t_lam, (np.ndarray, np.generic)): + t_lam = np.array([t_lam]) - x = 1.0/(t_lam/1000.0) #in micron^-1 + x = 1.0/(t_lam/1000.0) # in micron^-1 k = np.zeros(np.size(t_lam), dtype=np.float64) mark = np.where((x <= 1.10) & (x >= 0.30))[0] - if len(mark) > 0: k[mark] = ir_func_mw(x[mark], R) + if len(mark) > 0: + k[mark] = ir_func_mw(x[mark], R) mark = np.where((x <= 3.30) & (x > 1.10))[0] - if len(mark) > 0: k[mark] = opt_func_mw(x[mark], R) + if len(mark) > 0: + k[mark] = opt_func_mw(x[mark], R) mark = np.where((x <= 8.00) & (x > 3.3))[0] - if len(mark) > 0: k[mark] = uv_func_mw(x[mark], R) + if len(mark) > 0: + k[mark] = uv_func_mw(x[mark], R) mark = np.where((x <= 10.00) & (x > 8.0))[0] - if len(mark) > 0: k[mark] = fuv_func_mw(x[mark], R) + if len(mark) > 0: + k[mark] = fuv_func_mw(x[mark], R) k = k * R - if np.size(x) == 1: k = k[0] + if np.size(x) == 1: + k = k[0] return k -#enddef diff --git a/setup.py b/setup.py index ffed3ee..4ef46ae 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ with open("README.md", "r") as fh: setup( name='chun_codes', - version='0.6.0', + version='0.7.0', packages=['chun_codes'], url='https://github.com/astrochun/chun_codes', license='MIT License',
astrochun/chun_codes
e1b467b5dc59c571b5e5d5868b02fb1fc919fbf7
diff --git a/tests/test_cardelli.py b/tests/test_cardelli.py new file mode 100644 index 0000000..89f4cb7 --- /dev/null +++ b/tests/test_cardelli.py @@ -0,0 +1,20 @@ +import astropy.units as u +import numpy as np + +from chun_codes import cardelli + + +def test_cardelli(): + + line_Ha = 6562.8 + lambda0 = line_Ha * u.Angstrom + result1 = cardelli.cardelli(lambda0) + assert isinstance(result1, float) + + result2 = cardelli.cardelli([line_Ha] * u.Angstrom) + assert isinstance(result2, float) + + lambda0 = [500, 900, 1100, 1500, 2500, 5500, 15000] * u.Angstrom + result3 = cardelli.cardelli(lambda0) + assert isinstance(result3, (np.ndarray, np.generic)) + assert len(result3) == len(lambda0)
Use GitHub Actions for CI Because of the change in pricing model by Travis CI for open-source software, it becomes cost prohibitive to use Travis CI moving forward. Thus, we should migrate to using GitHub actions for CI and build tests. This doc page and the GitHub Action YAML is a starting point: https://docs.github.com/en/free-pro-team@latest/actions/guides/building-and-testing-python We can start with this but not include python 2.7. Will need to include other dependencies such as chun_codes and pytest-cov. This might be useful for testing purposes before committing the github actions: https://github.com/nektos/act We should require a skip if "ci skip" or "skip ci"  Action items: - [x] Create a `python-package` GitHub Actions workflow - [x] Add option to prevent skip CI with "ci skip" or "skip ci. See [this](https://github.com/ualibraries/ReQUIAM/runs/1487466435?check_suite_focus=true) - [x] Disable certain files - [x] GitHub Actions badge in README.md - [x] Include tests for `cardelli` module <!--Branch info--> **Implemented in**: `feature/gh_actions_build_test`
0.0
e1b467b5dc59c571b5e5d5868b02fb1fc919fbf7
[ "tests/test_cardelli.py::test_cardelli" ]
[]
{ "failed_lite_validators": [ "has_hyperlinks", "has_added_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2020-12-08 05:08:02+00:00
mit
1,217
astropenguin__azely-61
diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index c1fe2d2..0d103e2 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -5,6 +5,9 @@ "dockerfile": "Dockerfile" }, "postCreateCommand": "poetry install", + "containerEnv": { + "AZELY_DIR": "${containerWorkspaceFolder}/.azely/" + }, "customizations": { "vscode": { "extensions": [ diff --git a/.gitignore b/.gitignore index f899d85..5d99a78 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,7 @@ -# User-defined +### Azely ### .azely/ -.vscode/ -.envrc -.env +### Python ### # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] @@ -26,9 +24,11 @@ parts/ sdist/ var/ wheels/ +share/python-wheels/ *.egg-info/ .installed.cfg *.egg +MANIFEST # PyInstaller # Usually these files are written by a python script from a template @@ -43,13 +43,17 @@ pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ +.nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover +*.py,cover .hypothesis/ +.pytest_cache/ +cover/ # Translations *.mo @@ -58,6 +62,8 @@ coverage.xml # Django stuff: *.log local_settings.py +db.sqlite3 +db.sqlite3-journal # Flask stuff: instance/ @@ -72,16 +78,49 @@ docs/_apidoc docs/_build/ # PyBuilder +.pybuilder/ target/ # Jupyter Notebook .ipynb_checkpoints -# pyenv -.python-version +# IPython +profile_default/ +ipython_config.py -# celery beat schedule file +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff celerybeat-schedule +celerybeat.pid # SageMath parsed files *.sage.py @@ -92,6 +131,8 @@ celerybeat-schedule env/ venv/ ENV/ +env.bak/ +venv.bak/ # Spyder project settings .spyderproject @@ -105,3 +146,31 @@ ENV/ # mypy .mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +### Python Patch ### +# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration +poetry.toml + +# ruff +.ruff_cache/ + +# LSP config files +pyrightconfig.json diff --git a/azely/__init__.py b/azely/__init__.py index d397bbd..583e6a7 100644 --- a/azely/__init__.py +++ b/azely/__init__.py @@ -8,7 +8,6 @@ __all__ = [ "get_time", "location", "object", - "query", "time", "utils", ] @@ -18,7 +17,6 @@ __version__ = "0.7.0" # submodules from . import consts from . import cache -from . import query from . import utils from . import location from . import object diff --git a/azely/consts.py b/azely/consts.py index 3beab4f..2545a31 100644 --- a/azely/consts.py +++ b/azely/consts.py @@ -8,8 +8,8 @@ determined by some environment variables of client. __all__ = [ "AZELY_DIR", "AZELY_CONFIG", - "AZELY_OBJECT", - "AZELY_LOCATION", + "AZELY_OBJECTS", + "AZELY_LOCATIONS", "SOLAR_FRAME", "SOLAR_OBJECTS", "HERE", @@ -73,8 +73,8 @@ else: AZELY_CONFIG = ensure(AZELY_DIR / "config.toml") -AZELY_OBJECT = ensure(AZELY_DIR / "objects.toml") -AZELY_LOCATION = ensure(AZELY_DIR / "locations.toml") +AZELY_OBJECTS = ensure(AZELY_DIR / "objects.toml") +AZELY_LOCATIONS = ensure(AZELY_DIR / "locations.toml") # special values for the solar system ephemeris diff --git a/azely/location.py b/azely/location.py index d9bd5d9..563626a 100644 --- a/azely/location.py +++ b/azely/location.py @@ -4,7 +4,7 @@ __all__ = ["Location", "get_location"] # standard library from dataclasses import dataclass from datetime import tzinfo -from typing import ClassVar +from typing import ClassVar, Optional # dependencies @@ -15,8 +15,7 @@ from ipinfo import getHandler from pytz import timezone from timezonefinder import TimezoneFinder from .cache import PathLike, cache -from .consts import AZELY_LOCATION, GOOGLE_API, HERE, IPINFO_API, TIMEOUT -from .query import parse +from .consts import AZELY_LOCATIONS, GOOGLE_API, HERE, IPINFO_API, TIMEOUT @dataclass @@ -65,39 +64,45 @@ class Location: def get_location( query: str, + /, *, google_api: str = GOOGLE_API, ipinfo_api: str = IPINFO_API, + name: Optional[str] = None, + source: PathLike = AZELY_LOCATIONS, timeout: int = TIMEOUT, + update: bool = False, ) -> Location: """Get location information.""" - parsed = parse(query) - - if parsed.query.lower() == HERE: + if query.lower() == HERE: return get_location_by_ip( - query=parsed.query, + query, ipinfo_api=ipinfo_api, + name=name, timeout=timeout, - source=parsed.source or AZELY_LOCATION, - update=parsed.update, + source=source, + update=update, ) else: return get_location_by_name( - query=parsed.query, + query, google_api=google_api, + name=name, timeout=timeout, - source=parsed.source or AZELY_LOCATION, - update=parsed.update, + source=source, + update=update, ) @cache def get_location_by_ip( query: str, + /, *, ipinfo_api: str, - timeout: int, + name: Optional[str], source: PathLike, # consumed by @cache + timeout: int, update: bool, # consumed by @cache ) -> Location: """Get location information by current IP address.""" @@ -114,10 +119,12 @@ def get_location_by_ip( @cache def get_location_by_name( query: str, + /, *, google_api: str, - timeout: int, + name: Optional[str], source: PathLike, # consumed by @cache + timeout: int, update: bool, # consumed by @cache ) -> Location: """Get location information by a location name.""" @@ -129,7 +136,7 @@ def get_location_by_name( ) return Location( - name=query, + name=name or query, longitude=str(response.lon), latitude=str(response.lat), ) diff --git a/azely/object.py b/azely/object.py index 02ecc55..1f57ef3 100644 --- a/azely/object.py +++ b/azely/object.py @@ -3,7 +3,7 @@ __all__ = ["Object", "get_object"] # standard library from dataclasses import dataclass -from typing import List +from typing import Optional # dependent packages @@ -11,8 +11,7 @@ from astropy.coordinates import Longitude, Latitude, SkyCoord, get_body from astropy.time import Time as ObsTime from astropy.utils.data import conf from .cache import PathLike, cache -from .consts import AZELY_OBJECT, FRAME, SOLAR_FRAME, SOLAR_OBJECTS, TIMEOUT -from .query import parse +from .consts import AZELY_OBJECTS, FRAME, SOLAR_FRAME, SOLAR_OBJECTS, TIMEOUT @dataclass @@ -64,39 +63,45 @@ class Object: def get_object( query: str, + /, *, frame: str = FRAME, + name: Optional[str] = None, + source: PathLike = AZELY_OBJECTS, timeout: int = TIMEOUT, + update: bool = False, ) -> Object: """Get object information.""" - parsed = parse(query) - - if parsed.query.lower() in SOLAR_OBJECTS: + if query.lower() in SOLAR_OBJECTS: return get_object_solar( - query=parsed.query, - source=parsed.source or AZELY_OBJECT, - update=parsed.update, + query, + name=name, + source=source, + update=update, ) else: return get_object_by_name( - query=parsed.query, + query, frame=frame, + name=name, timeout=timeout, - source=parsed.source or AZELY_OBJECT, - update=parsed.update, + source=source, + update=update, ) @cache def get_object_solar( query: str, + /, *, + name: Optional[str], source: PathLike, # consumed by @cache update: bool, # consumed by @cache ) -> Object: """Get object information in the solar system.""" return Object( - name=query, + name=name or query, longitude="NA", latitude="NA", frame=SOLAR_FRAME, @@ -106,10 +111,12 @@ def get_object_solar( @cache def get_object_by_name( query: str, + /, *, frame: str, - timeout: int, + name: Optional[str], source: PathLike, # consumed by @cache + timeout: int, update: bool, # consumed by @cache ) -> Object: """Get object information by an object name.""" @@ -122,7 +129,7 @@ def get_object_by_name( ) return Object( - name=query, + name=name or query, longitude=str(response.data.lon), # type: ignore latitude=str(response.data.lat), # type: ignore frame=frame, diff --git a/azely/query.py b/azely/query.py deleted file mode 100644 index 5dcd3e7..0000000 --- a/azely/query.py +++ /dev/null @@ -1,35 +0,0 @@ -__all__ = ["parse"] - - -# standard library -from dataclasses import dataclass -from re import compile -from typing import Optional - - -# constants -QUERY = compile(r"^\s*((.+):)?([^!]+)(!)?\s*$") - - -@dataclass(frozen=True) -class Parsed: - query: str - """Final query to be passed.""" - - source: Optional[str] = None - """Path of the query source.""" - - update: bool = False - """Whether to update the query source.""" - - -def parse(string: str) -> Parsed: - """Parse a string and return a parsed object.""" - if (match := QUERY.search(string)) is None: - raise ValueError(f"{string} is not valid.") - - return Parsed( - query=match.group(3), - source=match.group(2), - update=bool(match.group(4)), - )
astropenguin/azely
81628f0686c07ea88117fdc4963628d0a0ec1ee3
diff --git a/tests/test_location.py b/tests/test_location.py index e255d8c..08a7356 100644 --- a/tests/test_location.py +++ b/tests/test_location.py @@ -8,7 +8,7 @@ from azely.location import Location, get_location from tomlkit import dump -# constants +# test data expected = Location( name="Array Operations Site", longitude="292d14m45.85512974s", @@ -19,15 +19,12 @@ expected = Location( # test functions def test_location_by_query(): - assert get_location(f"{expected.name}!") == expected + assert get_location(expected.name, update=True) == expected def test_location_by_user(): with NamedTemporaryFile("w", suffix=".toml") as f: - name = "AOS" - query = f"{f.name}:{name}" - - dump({name: asdict(expected)}, f) + dump({expected.name: asdict(expected)}, f) f.seek(0) - assert get_location(query) == expected + assert get_location(expected.name, source=f.name) == expected diff --git a/tests/test_object.py b/tests/test_object.py index 6286bee..eceffee 100644 --- a/tests/test_object.py +++ b/tests/test_object.py @@ -8,7 +8,7 @@ from azely.object import Object, get_object from tomlkit import dump -# constants +# test data expected_solar = Object( name="Sun", longitude="NA", @@ -17,28 +17,25 @@ expected_solar = Object( ) expected_icrs = Object( - name="M87", - longitude="12h30m49.42338414s", - latitude="+12d23m28.0436859s", + name="3C 273", + longitude="12h29m06.69982572s", + latitude="2d03m08.59762998s", frame="icrs", ) # test functions def test_object_of_solar(): - assert get_object(f"{expected_solar.name}!") == expected_solar + assert get_object(expected_solar.name, update=True) == expected_solar def test_object_by_query(): - assert get_object(f"{expected_icrs.name}!") == expected_icrs + assert get_object(expected_icrs.name, update=True) == expected_icrs def test_object_by_user(): with NamedTemporaryFile("w", suffix=".toml") as f: - name = "M87" - query = f"{f.name}:{name}" - - dump({name: asdict(expected_icrs)}, f) + dump({expected_icrs.name: asdict(expected_icrs)}, f) f.seek(0) - assert get_object(query) == expected_icrs + assert get_object(expected_icrs.name, source=f.name) == expected_icrs
Update query format of location and object modules
0.0
81628f0686c07ea88117fdc4963628d0a0ec1ee3
[ "tests/test_location.py::test_location_by_query", "tests/test_location.py::test_location_by_user", "tests/test_object.py::test_object_of_solar", "tests/test_object.py::test_object_by_query", "tests/test_object.py::test_object_by_user" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_removed_files", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2023-07-28 10:36:22+00:00
mit
1,218
astropenguin__pandas-dataclasses-102
diff --git a/pandas_dataclasses/core/asdata.py b/pandas_dataclasses/core/asdata.py index 6e0fb59..29265a5 100644 --- a/pandas_dataclasses/core/asdata.py +++ b/pandas_dataclasses/core/asdata.py @@ -2,7 +2,7 @@ __all__ = ["asdataframe", "asseries"] # standard library -from typing import Any, Dict, Hashable, List, Optional, Type, overload +from typing import Any, Callable, Dict, Hashable, List, Optional, overload # dependencies @@ -17,12 +17,12 @@ from .typing import P, DataClass, PandasClass, TDataFrame, TSeries # runtime functions @overload -def asdataframe(obj: Any, *, factory: Type[TDataFrame]) -> TDataFrame: +def asdataframe(obj: PandasClass[P, TDataFrame], *, factory: None = None) -> TDataFrame: ... @overload -def asdataframe(obj: PandasClass[P, TDataFrame], *, factory: None = None) -> TDataFrame: +def asdataframe(obj: DataClass[P], *, factory: Callable[..., TDataFrame]) -> TDataFrame: ... @@ -38,9 +38,6 @@ def asdataframe(obj: Any, *, factory: Any = None) -> Any: if factory is None: factory = spec.factory or pd.DataFrame - if not issubclass(factory, pd.DataFrame): - raise TypeError("Factory must be a subclass of DataFrame.") - dataframe = factory( data=get_data(spec), index=get_index(spec), @@ -52,12 +49,12 @@ def asdataframe(obj: Any, *, factory: Any = None) -> Any: @overload -def asseries(obj: Any, *, factory: Type[TSeries]) -> TSeries: +def asseries(obj: PandasClass[P, TSeries], *, factory: None = None) -> TSeries: ... @overload -def asseries(obj: PandasClass[P, TSeries], *, factory: None = None) -> TSeries: +def asseries(obj: DataClass[P], *, factory: Callable[..., TSeries]) -> TSeries: ... @@ -73,9 +70,6 @@ def asseries(obj: Any, *, factory: Any = None) -> Any: if factory is None: factory = spec.factory or pd.Series - if not issubclass(factory, pd.Series): - raise TypeError("Factory must be a subclass of Series.") - data = get_data(spec) index = get_index(spec) diff --git a/pandas_dataclasses/core/mixins.py b/pandas_dataclasses/core/mixins.py index f900957..0e21fe2 100644 --- a/pandas_dataclasses/core/mixins.py +++ b/pandas_dataclasses/core/mixins.py @@ -5,7 +5,7 @@ __all__ = ["As", "AsDataFrame", "AsSeries"] from copy import copy from functools import wraps as wraps_ from types import FunctionType, MethodType -from typing import Any, Callable, ForwardRef, Generic, Type, cast +from typing import Any, Callable, ForwardRef, Generic, Type # dependencies @@ -15,13 +15,13 @@ from typing_extensions import get_args, get_origin # submodules from .asdata import asdataframe, asseries -from .typing import P, T, PandasClass, TPandas +from .typing import P, T, Pandas, PandasClass, TPandas class classproperty: - """Class property dedicated to ``As.new``.""" + """Class property decorator dedicated to ``As.new``.""" - def __init__(self, func: Any) -> None: + def __init__(self, func: Callable[..., Any]) -> None: self.__doc__ = func.__doc__ self.func = func @@ -33,20 +33,82 @@ class classproperty: return self.func(cls) # type: ignore -def wraps(func: Any, return_: Any) -> Callable[[T], T]: - """Function decorator dedicated to ``As.new``.""" +class As(Generic[TPandas]): + """Mix-in class for runtime pandas data creator.""" + + __pandas_factory__: Callable[..., TPandas] + """Factory for pandas data creation.""" + + def __init_subclass__(cls, **kwargs: Any) -> None: + """Add a pandas factory to an inheriting class.""" + factory = kwargs.pop("factory", None) + cls.__pandas_factory__ = factory or get_factory(cls) + super().__init_subclass__(**kwargs) + + @classproperty + def new(cls) -> MethodType: + """Runtime pandas data creator as a classmethod.""" + return MethodType(get_new(cls), cls) + + +AsDataFrame = As[pd.DataFrame] +"""Alias of ``As[pandas.DataFrame]``.""" + + +AsSeries = As["pd.Series[Any]"] +"""Alias of ``As[pandas.Series[Any]]``.""" + + +def get_factory(cls: Any) -> Callable[..., Any]: + """Extract a pandas factory from a class.""" + for base in getattr(cls, "__orig_bases__", ()): + if get_origin(base) is not As: + continue + + factory = get_args(base)[0] + + # special handling for AsSeries + if factory == ForwardRef("pd.Series[Any]"): + return pd.Series + + return factory # type: ignore + + raise TypeError("Could not find any factory.") + + +def get_new(cls: Any) -> Callable[..., Pandas]: + """Create a runtime new function from a class.""" + factory = cls.__pandas_factory__ + origin = get_origin(factory) or factory + + if issubclass(origin, pd.DataFrame): + converter: Any = asdataframe + elif issubclass(origin, pd.Series): + converter = asseries + else: + raise TypeError("Could not choose a converter.") + + @wraps(cls.__init__, "new", factory) + def new(cls: Any, *args: Any, **kwargs: Any) -> Any: + return converter(cls(*args, **kwargs)) + + return new + + +def wraps(func: Any, name: str, return_: Any) -> Callable[[T], T]: + """functools.wraps with modifiable name and return type.""" if not isinstance(func, FunctionType): return wraps_(func) copied = type(func)( func.__code__, func.__globals__, - "new", + name, func.__defaults__, func.__closure__, ) - for name in ( + for attr in ( "__annotations__", "__dict__", "__doc__", @@ -55,55 +117,7 @@ def wraps(func: Any, return_: Any) -> Callable[[T], T]: "__name__", "__qualname__", ): - setattr(copied, name, copy(getattr(func, name))) + setattr(copied, attr, copy(getattr(func, attr))) copied.__annotations__["return"] = return_ return wraps_(copied) - - -class As(Generic[TPandas]): - """Mix-in class that provides shorthand methods.""" - - __pandas_factory__: Type[TPandas] - """Factory for pandas data creation.""" - - def __init_subclass__(cls, **kwargs: Any) -> None: - """Add a pandas factory to an inheriting class.""" - super().__init_subclass__(**kwargs) - - for base in cls.__orig_bases__: # type: ignore - if get_origin(base) is not As: - continue - - factory = get_args(base)[0] - - if factory == ForwardRef("pd.Series[Any]"): - cls.__pandas_factory__ = cast(Any, pd.Series) - else: - cls.__pandas_factory__ = factory - - @classproperty - def new(cls) -> Any: - """Create a pandas object from dataclass parameters.""" - factory = cls.__pandas_factory__ - - if issubclass(factory, pd.DataFrame): - aspandas: Any = asdataframe - elif issubclass(factory, pd.Series): - aspandas = asseries - else: - raise TypeError("Not a valid pandas factory.") - - @wraps(cls.__init__, factory) # type: ignore - def new(cls: Any, *args: Any, **kwargs: Any) -> Any: - return aspandas(cls(*args, **kwargs)) - - return MethodType(new, cls) - - -AsDataFrame = As[pd.DataFrame] -"""Alias of ``As[pandas.DataFrame]``.""" - - -AsSeries = As["pd.Series[Any]"] -"""Alias of ``As[pandas.Series[Any]]``.""" diff --git a/pandas_dataclasses/core/specs.py b/pandas_dataclasses/core/specs.py index f33b5f5..009a1a3 100644 --- a/pandas_dataclasses/core/specs.py +++ b/pandas_dataclasses/core/specs.py @@ -5,7 +5,7 @@ __all__ = ["Spec"] from dataclasses import dataclass, replace from dataclasses import Field as Field_, fields as fields_ from functools import lru_cache -from typing import Any, Hashable, List, Optional, Type, Union +from typing import Any, Callable, Hashable, List, Optional, Type # dependencies @@ -13,8 +13,7 @@ from typing_extensions import Literal, get_type_hints # submodules -import pandas as pd -from .typing import P, DataClass, Role, get_dtype, get_name, get_role +from .typing import P, DataClass, Pandas, Role, get_dtype, get_name, get_role # runtime classes @@ -84,7 +83,7 @@ class Spec: fields: Fields """List of field specifications.""" - factory: Optional[Type[Union[pd.DataFrame, "pd.Series[Any]"]]] = None + factory: Optional[Callable[..., Pandas]] = None """Factory for pandas data creation.""" @classmethod diff --git a/pandas_dataclasses/core/typing.py b/pandas_dataclasses/core/typing.py index 8d3a1e2..dc0704a 100644 --- a/pandas_dataclasses/core/typing.py +++ b/pandas_dataclasses/core/typing.py @@ -7,13 +7,13 @@ from enum import Enum, auto from itertools import chain from typing import ( Any, + Callable, Collection, Dict, Hashable, Iterable, Optional, Tuple, - Type, TypeVar, Union, ) @@ -34,9 +34,10 @@ from typing_extensions import ( # type hints (private) +Pandas = Union[pd.DataFrame, "pd.Series[Any]"] P = ParamSpec("P") T = TypeVar("T") -TPandas = TypeVar("TPandas", bound=Union[pd.DataFrame, "pd.Series[Any]"]) +TPandas = TypeVar("TPandas", bound=Pandas) TDataFrame = TypeVar("TDataFrame", bound=pd.DataFrame) TSeries = TypeVar("TSeries", bound="pd.Series[Any]") @@ -54,7 +55,7 @@ class PandasClass(Protocol[P, TPandas]): """Type hint for dataclass objects with a pandas factory.""" __dataclass_fields__: Dict[str, "Field[Any]"] - __pandas_factory__: Type[TPandas] + __pandas_factory__: Callable[..., TPandas] def __init__(self, *args: P.args, **kwargs: P.kwargs) -> None: ...
astropenguin/pandas-dataclasses
a9e85948a4ee1e3213e6b62e6e0a0cce3be0c0b0
diff --git a/tests/test_mixins.py b/tests/test_mixins.py index 13cffc5..3abcaf2 100644 --- a/tests/test_mixins.py +++ b/tests/test_mixins.py @@ -24,12 +24,12 @@ class DataFrameWeather(Weather, AsDataFrame): @dataclass -class SeriesWeather(Weather, AsSeries): +class CustomDataFrameWeather(Weather, As[CustomDataFrame]): pass @dataclass -class CustomDataFrameWeather(Weather, As[CustomDataFrame]): +class SeriesWeather(Weather, AsSeries): pass @@ -38,6 +38,11 @@ class CustomSeriesWeather(Weather, As[CustomSeries]): pass +@dataclass +class FloatSeriesWeather(Weather, As["pd.Series[float]"], factory=pd.Series): + pass + + # test functions def test_dataframe_weather() -> None: df_weather = DataFrameWeather.new( @@ -93,3 +98,17 @@ def test_custom_series_weather() -> None: assert isinstance(ser_weather, CustomSeries) assert_series_equal(ser_weather, ser_weather_true, check_series_type=False) + + +def test_float_series_weather() -> None: + ser_weather = FloatSeriesWeather.new( + year=weather.year, + month=weather.month, + temp_avg=weather.temp_avg, + temp_max=weather.temp_max, + wind_avg=weather.wind_avg, + wind_max=weather.wind_max, + ) + + assert isinstance(ser_weather, pd.Series) + assert_series_equal(ser_weather, ser_weather_true, check_series_type=False)
Extend pandas factory Update type hints for pandas factory (`__pandas_factory__`) to accept a function whose return type is a subclass of `pandas.DataFrame` or `pandas.Series`.
0.0
a9e85948a4ee1e3213e6b62e6e0a0cce3be0c0b0
[ "tests/test_mixins.py::test_dataframe_weather", "tests/test_mixins.py::test_custom_dataframe_weather", "tests/test_mixins.py::test_series_weather", "tests/test_mixins.py::test_custom_series_weather", "tests/test_mixins.py::test_float_series_weather" ]
[]
{ "failed_lite_validators": [ "has_short_problem_statement", "has_many_modified_files", "has_many_hunks" ], "has_test_patch": true, "is_lite": false }
2022-10-22 18:24:35+00:00
mit
1,219