-
-
Notifications
You must be signed in to change notification settings - Fork 30.7k
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
PEP 572: Assignment Expressions #79405
Comments
This issue will serve to track development and PRs for the implementation of PEP-572: Assignment Expressions. |
This is huge! I do recall there are some minor edge cases where the implementation currently doesn't match the PEP. Could you summarize those here, and add your recommendation (e.g. change the PEP, fix the code, wait and see) with motivation? |
The change broke most buildbots: congrats Emily, each core dev has to do their as part of their training ;-) Don't worry, it's fine. I wrote PR bpo-11670 which should fix test_tools. |
@vstinner Is there something I could/should have checked other than the CI displayed in GitHub before merging? Let me know if I can help. Here's a brief summary of the differences between the PEP spec and implementation: From the "Scope of the target" section of the PEP, there are two cases that should raise a TargetScopeError: when an assignment expression is used in a comprehension inside a class body or for special cases in comprehensions. Invalid examples for the latter include:
However, the following work in the implementation,though the PEP states they should be invalid: >>> [i := i+1 for i in range(5)]
[1, 2, 3, 4, 5]
>>> i
5
>>> [i := 0 for i, j in [(1, 2)]]
[0] The following does not work in the implementation (as desired), but does not throw a TargetScopeError as defined in the PEP: >>> [i+1 for i in i := range(5)]
File "<stdin>", line 1
[i+1 for i in i := range(5)]
^
SyntaxError: invalid syntax IMO, I was leaning towards advocating for changing the PEP to match the implementation. I think the error messages are clear and expected, and restricting what already works would require significant special cases. I'm open to discussion though. There's also documentation that should certainly be added (and I believe a spot where assignment expressions are explicitly mentioned as not being included in the language, which is no longer the case) |
It wasn't your fault. Our pre-commit checks on pull requests is incomplete on purpose: it has to be fast. It's fine to break buildbots sometimes. It's a tradeoff. If you want to help, please merge #11670 as soon as the CI test pass since I'm going to bed :-) You are the victim of a very very specific annoying test, test_unparse with its annoying "randomly pick 10 files from the stdlib" feature... |
I don't know if this is the correct issue for questions/clarifications but it seems parens are mandatory while using named expressions in while statement which makes some of the examples invalid like https://www.python.org/dev/peps/pep-0572/#sysconfig-py . From my limited knowledge while statement Grammar was not modified at https://github.com/python/cpython/pull/10497/files#diff-cb0b9d6312c0d67f6d4aa1966766ceddR73 and no tests for while statement which made me assume it's intentional. I haven't followed the full discussion about PEP-572 so feel free to correct me if it's a conscious decision and in that case the PEP-572 can be updated. # python info ➜ cpython git:(master) ./python.exe
# Example as in PEP-572 to create a simple file that reads itself and prints lines that matches "foo" ➜ cpython git:(master) cat /tmp/foo.py with open("/tmp/foo.py") as f:
while line := f.readline():
if match := re.search(r"foo", line):
print(match.string.strip("\n"))
➜ cpython git:(master) ./python.exe /tmp/foo.py
File "/tmp/foo.py", line 4
while line := f.readline():
^
SyntaxError: invalid syntax # Wrapping named expression with parens for while makes this valid ➜ cpython git:(master) cat /tmp/foo.py with open("/tmp/foo.py") as f:
while (line := f.readline()):
if match := re.search(r"foo", line):
print(match.string.strip("\n"))
➜ cpython git:(master) ./python.exe /tmp/foo.py
with open("/tmp/foo.py") as f:
if match := re.search(r"foo", line): As a user I think parens shouldn't be mandatory in while statement since if statement works fine. Parens can cause while statement to be superfluous in some cases and an extra case to remember while teaching. |
Note: I checked and 3.x buildbots are back to green (ignoring the ones which already failed previously). Good. |
FYI, we need a prominent Whatsnew entry for this. |
@rhettinger absolutely, I'm going to include that in my documentation PR which is currently in progress. :) |
PEP-572 is nowhere to be found in https://docs.python.org/3.8/whatsnew/3.8.html Should I open a separate issue for that? |
(I've somehow missed the previous comments about the same, sorry about that.) |
I have a work-in-progress (WIP) documentation branch I've been working on that I'll push up this week to address the following:
If anyone has another area they think the documentation should be updated, please let me know! |
If we forget something, it's not an issue: it can be added later! |
Now I had the opportunity to play with the walrus (as it is affectionately called in some parts of the community), I have to ask you for a reconsideration of one part of PEP-572.
Correct, but the motivation rests on a wrong premise, that the effect is the same. In one very important case, it is not: in REPL (including things like Jupyter notebooks), the values of expressions are printed (if not None). I really hoped that the walrus would enable me to both assign and see the result at once. (Now it does, but I have to parenthesize, and that just looks ugly.) More than half of the cells in my Jupyter notebooks are of the form name = some.complicated.method(of={some: arguments})
name
another_name = another.method(name, [additional, arguments])
another_name And while I understand why I had to write them like this before PEP-572, now I really think they would look much tidier as
Please reconsider. |
@veky -- please take this up on python-ideas. |
Sorry, I don't have the energy for endless discussions without any result that almost always happen there. If you - of all people - don't see an obvious benefit of this (not even a feature - just a removal of a quite pointless limitation), then I'm probably wrong and there's no point in that. |
@veky As a Jupyter notebook maintainer, I can see your point and I suspect some would like it. I'm not sure how big a benefit it would be for folks based on current notebook usage and practices. I just don't know. It's worth a discussion, but it should take place on python-ideas first to see how much traction your proposal would have. Let's keep this issue focused on the implementation of 572 as accepted. |
You are one person, who has used this feature for what, a month elapsed If the restriction turns out to be "pointless", then we can remove it
but it is surely still an improvement over the status quo: variable = expression; variable But if we remove it now, and it turns out that it wasn't as pointless as I'm glad you've found an excellent use-case for unbracketed assignment Besides, Jypiter already allows interactive code that would be a syntax |
The bug tracker is not the appropriate place to discuss a PEP. This issue is about the implementation of the PEP. |
Carol, if you're willing to go into the lion's den that is Python-ideas with this, you have my eternal gratitude. :-) Steven, sorry, there really is no rush. I really don't think I ever said there is. However, I think it would be much easier to change the behavior while the thing is in alpha. Isn't that the purpose of alpha? (If I'm wrong here, please disregard. I would be fine to see this happening few years from now. I believe in "Python in the limit", not actual versions, but too many times I have been said "what you ask makes sense in the ideal world, but that ship has sailed long ago".) Yes, of course (name := expression) is an improvement over what we have now, and I'm grateful for that. It's just that when I explain it to my students (" = is just assignment, := is for assignment and displaying"), I have no good reason to tell them why they must put the parentheses---except "Python is too worried you will make a mistake", and that just doesn't seem like something Python usually does. (That's something Java would do to people.:) Yes, Jupyter sometimes does allow things that would otherwise be SyntaxErrors (though much less than they used to, since Python gave them a lot of headache by introducing decorators---if you remember that story;), and going to Jupyter was the next thing on my mind after I'm rejected here. I just thought it would be much easier to just allow this "at the source", so Jupyter people don't have to think "what if they finally allow toplevel walruses, but with different semantics (e.g., printing result even if it is None)?". Carol and Victor, I'm sorry I have usurped a bugtracker issue for this discussion. First, I really thought this is about implementation of assignment expressions, and this is the best place to put it. Second, I didn't expect a discussion---I thought it would be either "that makes no sense, go away" or "yeah, good idea, we'll do it". For the next such issue (there will probably be one:), do you suggest that the more appropriate thing would be to open a new issue? (Let me just reiterate that I'm not going to python-ideas. You probably can't understand how stressful that place is, but believe me, it is. I'm not the only one that thinks so. If that's the only sanctioned method to improve Python, even when it is about details, then I'll just withdraw from the game.) |
3.8.0a3 is out, and the What's New still doesn't mention this work yet. |
Ned is correct! I will be sprinting on docs for this at PyCon. |
Maybe we could update the What's New quickly now, and then get the longer more complex docs done later? People have been asking if this feature is in 3.8 because they don't see it mentioned. |
... and probably also because they start Python, type
and get SyntaxError (as explained above). ;-) |
Ouch. That means we need to buy.p the puck format version number.--Guido (mobile) |
I have created PR14313 and triggered a custom build from that PR in the buildbots to confirm our hypothesis. |
Although it can be related, note that the buildbots do indeed delete pyc files. Check for example https://buildbot.python.org/all/#/builders/40/builds/2621/steps/2/logs/stdio : ... But I could be missing something. What I don't understand currently is why it fails only on the Windows buildbots. |
I don't know why the failure is Windows-only, but I suspect that some of This definitely needs a bump of the pyc format version number. |
How are the buildbots doing now? |
All buildbots for 3.8 and master are green again :) |
So bpo-29652 can be closed now? Was all concerns of previous discussions addressed? I suggest to increment the magic number by 1, not by 10. The space of magic numbers is finite. Add please a What's New entry for this change. |
I might be missing it, but I think the Language Reference still doesn't document assignment expressions. https://docs.python.org/3/reference/lexical_analysis.html#operators There are likely other places in the LR that need to be filled out with PEP-572 documentation. |
Did the documentation PR get pushed/merged? Emily mentioned having one in progress above, but it doesn't appear in the linked PRs. |
https://bugs.python.org/issue37757 separates out the TargetScopeError handling for conflicts between assignment expressions and comprehension iteration variables. |
Also, a major procedural note: it is NOT OK to merge a PEP implementation that completely ignores parts of the PEP. The merged tests are actively forcing NON-compliance with the accepted PEP, since they're requiring implementations to accept code that the PEP explicitly states should be disallowed. Those rules were added because the behaviour in CPython leaks CPython implementation details that we *don't want* to be part of the language specification. |
FWIW, I'm working on an improved whatsnew entry in #15127 |
Thanks for catching that this was still incomplete.
It was known the implementation was unfinished in this respect, but it was deemed better to merge what we had lest the work be lost in merge conflicts, and iterate in later betas. I've written some code that uses the walrus operator and have found it quite solid. The early existence of an implementation (albeit incomplete) has also helped get support for this in mypy (python/mypy#6899). I don't recall being aware that there were tests that specifically *checked* that the implementation was incomplete, and that's obviously wrong. |
bpo-37757 now has an associated PR adding the missing TargetScopeError cases: #15131 There's one case where it goes beyond what the PEP specifies: because the outermost iterable expression gets evaluated in a different scope from the rest of the comprehension, it just flat out prohibits the use of assignment expressions in comprehension iterable expressions. This was one of the cases where we explicitly didn't want the CPython implementation behaviour to leak into the language specification (as name binding in the outermost iterable expression would create an unrelated binding in the containing scope, while name binding in other iterable expressions would rebind any conflicting iteration variable in the comprehension), so the current PR takes the more conservative path, and defers allowing name binding in the iterable expressions until a specific use case for doing so is presented). |
Thanks Guido. The former test cases that the new PR removes are the following: res = [i := i for i in range(5)]
res = [i := 0 for i, j in [(1, 2), (3, 4)]]
res = [(i := 0, j := 1) for i, j in [(1, 2), (3, 4)]]
res = [(i := i, j := j) for i, j in [(1, 2), (3, 4)]]
res = [(i := j, j := i) for i, j in [(1, 2), (3, 4)]] These all raise TargetScopeError with the PR applied: >>> res = [i := i for i in range(5)]
File "<stdin>", line 1
TargetScopeError: named expression cannot rebind comprehension iteration variable
>>> res = [i := 0 for i, j in [(1, 2), (3, 4)]]
File "<stdin>", line 1
TargetScopeError: named expression cannot rebind comprehension iteration variable
>>> res = [(i := 0, j := 1) for i, j in [(1, 2), (3, 4)]]
File "<stdin>", line 1
TargetScopeError: named expression cannot rebind comprehension iteration variable
>>> res = [(i := i, j := j) for i, j in [(1, 2), (3, 4)]]
File "<stdin>", line 1
TargetScopeError: named expression cannot rebind comprehension iteration variable
>>> res = [(i := j, j := i) for i, j in [(1, 2), (3, 4)]]
File "<stdin>", line 1
TargetScopeError: named expression cannot rebind comprehension iteration variable |
Can you suggest a PEP update too, for the case that goes beyond the PEP? |
Proposed PEP update is here: python/peps#1140 The update also aims to clarify *why* we're doing the extra work in CPython's compiler to make these cases fail (i.e. we don't want to implicitly impose the current CPython runtime behaviour on other implementations) |
All areas that were identified for additional work have been addressed. If there is anything else that needs to be improved or updated, please create a new issue. Thanks! |
Congrats! Let's party. |
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: