←back to thread

317 points est | 2 comments | | HN request time: 0.449s | source
Show context
Derbasti ◴[] No.17450491[source]
Does this mean that I can write

    with file := open('filename'):
        data = file.read()
instead of

    with open('filename') as file:
        data = file.read()
I don't know how I feel about this.
replies(2): >>17450635 #>>17457397 #
1. glifchits ◴[] No.17450635[source]
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.
replies(1): >>17450965 #
2. zb ◴[] No.17450965[source]
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).