-
-
Notifications
You must be signed in to change notification settings - Fork 206
Fold nested context managers. #1012
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
shaleh
wants to merge
4
commits into
asottile:main
Choose a base branch
from
shaleh:fold-nested-context-managers
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import ast | ||
| import functools | ||
| import itertools | ||
| from collections.abc import Iterable | ||
| from typing import Any | ||
|
|
||
| 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 Block | ||
|
|
||
|
|
||
| def _expand_item(indent: int, item: ast.AST) -> str: | ||
| return '{}{}'.format(' ' * indent, ast.unparse(item)) | ||
|
|
||
|
|
||
| def _replace_context_managers( | ||
| i: int, | ||
| tokens: list[Token], | ||
| *, | ||
| with_items: list[ast.withitem], | ||
| body: Iterable[ast.AST], | ||
| ) -> None: | ||
| block = Block.find(tokens, i, trim_end=True) | ||
| block_indent = block._minimum_indent(tokens) | ||
| replacement = '{}with ({}):\n{}\n'.format( | ||
| ' ' * block._initial_indent(tokens), | ||
| ', '.join(ast.unparse(item) for item in with_items), | ||
| '\n'.join(_expand_item(block_indent, item) for item in body), | ||
| ) | ||
| tokens[block.start:block.end] = [Token('CODE', replacement)] | ||
|
|
||
|
|
||
| def flatten(xs: Iterable[Any]) -> list[Any]: | ||
| return list(itertools.chain.from_iterable(xs)) | ||
|
Comment on lines
+40
to
+41
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this is not at all acceptable or typesafe |
||
|
|
||
|
|
||
| @register(ast.With) | ||
| def visit_With_fold_nested( | ||
| state: State, | ||
| node: ast.With, | ||
| parent: ast.AST, | ||
| ) -> Iterable[tuple[Offset, TokenFunc]]: | ||
| """ | ||
| Fold nested with statements into one statement. | ||
|
|
||
| with foo: | ||
| with bar: | ||
| body | ||
|
|
||
| becomes | ||
|
|
||
| with (foo, bar): | ||
| body | ||
| """ | ||
| if state.settings.min_version < (3, 10): | ||
| return | ||
| if isinstance(parent, ast.With): | ||
| # The top most with statement will handle all of the children. | ||
| return | ||
|
|
||
| with_stmts = [] | ||
| current: ast.AST = node | ||
| while isinstance(current, ast.With): | ||
| with_stmts.append(current) | ||
| if len(current.body) == 1: | ||
| current = current.body[0] | ||
| else: | ||
| break | ||
|
|
||
| if len(with_stmts) > 1: | ||
| with_items = flatten(n.items for n in with_stmts) | ||
| yield ast_to_offset(node), functools.partial( | ||
| _replace_context_managers, | ||
| body=with_stmts[-1].body, | ||
| with_items=with_items, | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import pytest | ||
|
|
||
| from pyupgrade._data import Settings | ||
| from pyupgrade._main import _fix_plugins | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| ('s', 'version'), | ||
| ( | ||
| pytest.param( | ||
| 'with foo:\n' | ||
| " print('something')\n" | ||
| '\n', | ||
| (3, 10), | ||
| id='simple with expression', | ||
| ), | ||
| pytest.param( | ||
| 'with foo as bar:\n' | ||
| " print('something')\n" | ||
| '\n', | ||
| (3, 10), | ||
| id='simple with expression and captured name', | ||
| ), | ||
| pytest.param( | ||
| 'with foo as thing1, bar as thing2:\n' | ||
| " print('something')\n" | ||
| '\n', | ||
| (3, 9), | ||
| id='nested with expression and captured names', | ||
| ), | ||
| pytest.param( | ||
| 'with foo:\n' | ||
| ' with bar:\n' | ||
| " print('something')\n" | ||
| " print('another')\n" | ||
| '\n', | ||
| (3, 9), | ||
| id='nested with expression with empty name capture workaround', | ||
| ), | ||
| ), | ||
| ) | ||
| def test_fold_nested_context_managers_noop(s, version): | ||
| assert _fix_plugins(s, settings=Settings(min_version=version)) == s | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| ('s', 'expected', 'version'), | ||
| ( | ||
| pytest.param( | ||
| 'with foo:\n' | ||
| ' with bar:\n' | ||
| " print('something')\n" | ||
| " print('another')\n" | ||
| '\n', | ||
| 'with (foo, bar):\n' | ||
| " print('something')\n" | ||
| " print('another')\n" | ||
| '\n', | ||
| (3, 10), | ||
| id='nested with expression', | ||
| ), | ||
| pytest.param( | ||
| 'if value:\n' | ||
| ' with foo:\n' | ||
| ' with bar:\n' | ||
| ' with baz:\n' | ||
| " print('something')\n" | ||
| " print('another')\n" | ||
| '\n', | ||
| 'if value:\n' | ||
| ' with (foo, bar, baz):\n' | ||
| " print('something')\n" | ||
| " print('another')\n" | ||
| '\n', | ||
| (3, 10), | ||
| id='nested with expression inside of an if', | ||
| ), | ||
| pytest.param( | ||
| 'with foo as thing1:\n' | ||
| ' with bar as thing2:\n' | ||
| " print('something')\n" | ||
| " print('another')\n" | ||
| '\n', | ||
| 'with (foo as thing1, bar as thing2):\n' | ||
| " print('something')\n" | ||
| " print('another')\n" | ||
| '\n', | ||
| (3, 10), | ||
| id='nested with expression with named capture', | ||
| ), | ||
| pytest.param( | ||
| 'with foo as thing1:\n' | ||
| ' with bar:\n' | ||
| " print('something')\n" | ||
| " print('another')\n" | ||
| '\n', | ||
| 'with (foo as thing1, bar):\n' | ||
| " print('something')\n" | ||
| " print('another')\n" | ||
| '\n', | ||
| (3, 10), | ||
| id='nested with expression with only one named capture', | ||
| ), | ||
| pytest.param( | ||
| 'with foo as thing1:\n' | ||
| ' with bar:\n' | ||
| " print('something')\n" | ||
| " print('another')\n" | ||
| ' with other:\n' | ||
| " print('yet enother')\n" | ||
| '\n', | ||
| 'with foo as thing1:\n' | ||
| ' with bar:\n' | ||
| " print('something')\n" | ||
| " print('another')\n" | ||
| ' with other:\n' | ||
| " print('yet enother')\n" | ||
| '\n', | ||
| (3, 10), | ||
| id='nested with expression that is semantically meaningful', | ||
| ), | ||
| ), | ||
| ) | ||
| def test_fold_nested_context_managers(s, expected, version): | ||
| ret = _fix_plugins(s, settings=Settings(min_version=version)) | ||
| assert ret == expected |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ast.unparse does not roundtrip so it is not usable or acceptable
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
https://github.com/Instagram/LibCST is finally being maintained again so I guess @shaleh could use this. Alternatively, and likely recommended by @asottile, use his https://github.com/asottile/tokenize-rt