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
lib2to3 generates invalid code with filter and ternary operator #83052
Comments
This code snippet exposes a small edge case in lib2to3, where syntactically invalid code is generated: data = [1, 2, 3, 4, 5]
x = filter(lambda x: True if x > 2 else False, data)
print(x) lib2to3 transforms 2nd line above to: which is invalid (would be OK with parentheses after 1st 'if') Admittedly, the original code here is more complex that it should be ('True if foo else False' being equivalent to just 'foo'), but walked into this in "the real world" and wanted to report it. |
I can reproduce on the latest master branch. ./python Tools/scripts/2to3 2.py
RefactoringTool: Skipping optional fixer: buffer
RefactoringTool: Skipping optional fixer: idioms
RefactoringTool: Skipping optional fixer: set_literal
RefactoringTool: Skipping optional fixer: ws_comma
RefactoringTool: Refactored 2.py
--- 2.py (original)
+++ 2.py (refactored)
@@ -1,3 +1,3 @@
data = [1, 2, 3, 4, 5]
-x = filter(lambda x: True if x > 2 else False, data)
+x = [x for x in data if True if x > 2 else False]
print(x)
RefactoringTool: Files that need to be modified:
RefactoringTool: 2.py |
Dear core developers, I 'd like to discuss fixing this issue. 1. Add parenthesize when creating ListComp.
The change will be as follow:
new = ListComp(results.get("fp").clone(),
results.get("fp").clone(),
results.get("it").clone(),
- results.get("xp").clone())
+ parenthesize(results.get("xp").clone())) But generated codes are not pretty.
The generated code will be like this in this case. Personally, I prefer the 2nd option because it's more clear. If there are any ideas, please let me know. |
Thanks Zoran Simic to the bug report, and thanks Dong-hee Na for fixing it. It's fixed in the master branch and backports to 3.7 and 3.8 will land as soon as the CI tests pass. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: