Skip to content
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

Prefer preserving WithItem parentheses #7694

Merged
merged 1 commit into from
Sep 28, 2023
Merged

Conversation

MichaReiser
Copy link
Member

@MichaReiser MichaReiser commented Sep 28, 2023

Summary

This PR fixes a deviation to Black when formatting WithItems.

if True:
    with anyio.CancelScope(shield=True) if get_running_loop() else contextlib.nullcontext() as b:
        pass
    
    with (anyio.CancelScope(shield=True) if get_running_loop() else contextlib.nullcontext()):
        pass

Black formats this as:

if True:
    with anyio.CancelScope(
        shield=True
    ) if get_running_loop() else contextlib.nullcontext() as b:
        pass

    with (
        anyio.CancelScope(shield=True)
        if get_running_loop()
        else contextlib.nullcontext()
    ):
        pass

Notice that the two examples are identical except that the second example has parentheses around the with context expression.

Ruff formats both examples as if the context expression is not parenthesized:

if True:
    with anyio.CancelScope(
        shield=True
    ) if get_running_loop() else contextlib.nullcontext() as b:
        pass

This PR uses the IfBreaks layout that prefers parenthesizing the context manager when it is already parenthesized in source, aligning the behavior with black.

Closes #7441

Test Plan

Added tests. I reviewed the changes and they now match black's formatting.

The similarity index remains unchanged.

@MichaReiser
Copy link
Member Author

Current dependencies on/for this PR:

This comment was auto-generated by Graphite.

@MichaReiser MichaReiser added the formatter Related to the formatter label Sep 28, 2023
@MichaReiser MichaReiser marked this pull request as ready for review September 28, 2023 11:47
@charliermarsh charliermarsh changed the title Prefer preserving WithItem parenthese Prefer preserving WithItem parentheses Sep 28, 2023
@MichaReiser MichaReiser merged commit f53c410 into main Sep 28, 2023
@MichaReiser MichaReiser deleted the with-item-parentheses branch September 28, 2023 13:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
formatter Related to the formatter
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Formatter incompatibility: breaking multiple context managers
2 participants