Re:PEP 572: Python assignment expressions has been accepted
by Derbasti on Tuesday July 03, 2018 @10:33AM
(#17450491)
Does this mean that I can write
instead of
I don't know how I feel about this.
[ Parent
| on HN ]
Re:PEP 572: Python assignment expressions has been accepted
by glifchits on Tuesday July 03, 2018 @10:49AM
(#17450635)
Interesting! I figured the `as` in a `with` statement was handled uniquely, but I learned something new about Python today:
x = open('filename')
x.closed # False
with x:
print(x.readline())
x.closed # True
I think you're right. I prefer the `as` variant for readability.
Re:PEP 572: Python assignment expressions has been accepted
by zb on Tuesday July 03, 2018 @11:29AM
(#17450965)
It's the same for classes that define it like:
def __enter__(self):
return self
which is a common pattern (used by open()), but there's no requirement that __enter__() return the same object.In cases where __enter__() does something different, the assignment expression and the 'as' variable would have different values (the object of the 'with' statement, x, and the result of calling x.__enter__(), respectively).
Re:PEP 572: Python assignment expressions has been accepted
by thomasahle on Wednesday July 04, 2018 @10:20AM
(#17457397)
Exactly. Using "as" everywhere might require some small backward incompatible changes to make sure semantics line up, but at least then we wouldn't have redundant syntax.