Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #103964

Re: yield in try/finally case

Path csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail
From Peter Otten <__peter__@web.de>
Newsgroups comp.lang.python
Subject Re: yield in try/finally case
Date Thu, 03 Mar 2016 14:47:37 +0100
Organization None
Lines 153
Message-ID <mailman.147.1457012881.20602.python-list@python.org> (permalink)
References <84965b86-819b-4924-bca9-e82eed040606@googlegroups.com> <mailman.146.1457007243.20602.python-list@python.org> <de3f3492-063d-469c-8ad2-c93098335a2f@googlegroups.com>
Mime-Version 1.0
Content-Type text/plain; charset="UTF-8"
Content-Transfer-Encoding 8Bit
X-Trace news.uni-berlin.de Q6tNI1VEGXeRvnujdH6EfQr7iVII8HBVfa25UpD6bTdw==
Return-Path <python-python-list@m.gmane.org>
X-Original-To python-list@python.org
Delivered-To python-list@mail.python.org
X-Spam-Status OK 0.000
X-Spam-Evidence '*H*': 1.00; '*S*': 0.00; '"""': 0.05; 'context': 0.05; 'finally:': 0.05; 'modified': 0.05; 'python3': 0.05; 'sys': 0.05; 'clause': 0.07; 'filename': 0.07; '"""use': 0.09; 'args,': 0.09; 'block.': 0.09; 'called.': 0.09; 'garbage': 0.09; 'open()': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'restriction': 0.09; 'python': 0.10; 'exception': 0.13; 'files.': 0.13; 'question.': 0.13; 'def': 0.13; 'explicitly': 0.15; 'properly': 0.15; '2016': 0.16; 'closed:': 0.16; 'commandline': 0.16; 'construct.': 0.16; 'contextlib': 0.16; 'echo': 0.16; 'executed;': 0.16; 'files)': 0.16; 'fix:': 0.16; 'hams': 0.16; 'meanwhile,': 0.16; 'occur.': 0.16; 'received:80.91.229.3': 0.16; 'received:dip0.t-ipconnect.de': 0.16; 'received:io': 0.16; 'received:plane.gmane.org': 0.16; 'received:psf.io': 0.16; 'received:t-ipconnect.de': 0.16; 'subject:case': 0.16; 'subject:yield': 0.16; 'wrote:': 0.16; 'later': 0.16; 'case.': 0.18; 'try:': 0.18; 'version.': 0.18; 'either.': 0.22; 'pass': 0.22; 'import': 0.24; '(most': 0.24; 'header:User-Agent:1': 0.26; "doesn't": 0.26; 'header:X-Complaints-To:1': 0.26; 'moved': 0.27; 'yield': 0.27; "skip:' 10": 0.28; 'skip:u 20': 0.28; 'looks': 0.29; 'cat': 0.29; 'prints': 0.29; 'url:peps': 0.29; 'allows': 0.30; 'subject:/': 0.30; 'code': 0.30; 'implement': 0.32; 'statement': 0.32; 'run': 0.33; 'problem': 0.33; 'url:python': 0.33; 'common': 0.33; 'date.': 0.33; 'foo': 0.33; 'traceback': 0.33; 'open': 0.33; 'file': 0.34; 'url:dev': 0.35; 'quite': 0.35; 'expected': 0.35; 'but': 0.36; 'too': 0.36; 'there': 0.36; 'url:org': 0.36; 'lines': 0.36; 'possible': 0.36; '(and': 0.36; 'closing': 0.36; "wasn't": 0.36; 'to:addr:python-list': 0.36; 'subject:: ': 0.37; 'really': 0.37; 'method': 0.37; 'received:org': 0.37; 'itself': 0.38; 'anything': 0.38; 'files': 0.38; 'means': 0.39; 'to:addr:python.org': 0.40; 'still': 0.40; 'received:de': 0.40; 'some': 0.40; 'ever': 0.60; 'care': 0.60; 'your': 0.60; 'skip:u 10': 0.61; 'information': 0.63; 'march': 0.64; 'difficulty': 0.66; 'guaranteed': 0.67; 'finally': 0.70; '26,': 0.72; 'upper': 0.76; '**kw)': 0.84; '**kw):': 0.84; 'construct': 0.84; 'oscar': 0.84; 'subject:try': 0.84; 'defeat': 0.91
X-Injected-Via-Gmane http://gmane.org/
X-Gmane-NNTP-Posting-Host p57bd8b46.dip0.t-ipconnect.de
User-Agent KNode/4.13.3
X-BeenThere python-list@python.org
X-Mailman-Version 2.1.21
Precedence list
List-Id General discussion list for the Python programming language <python-list.python.org>
List-Unsubscribe <https://mail.python.org/mailman/options/python-list>, <mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive <http://mail.python.org/pipermail/python-list/>
List-Post <mailto:python-list@python.org>
List-Help <mailto:python-list-request@python.org?subject=help>
List-Subscribe <https://mail.python.org/mailman/listinfo/python-list>, <mailto:python-list-request@python.org?subject=subscribe>
Xref csiph.com comp.lang.python:103964

Show key headers only | View raw


刘琦帆 wrote:

> 在 2016年3月3日星期四 UTC+8下午8:14:29,Oscar Benjamin写道:
>> On 3 March 2016 at 11:52, 刘琦帆 <lqf.txx@gmail.com> wrote:
>> >
>> > "A yield statement is not allowed in the try clause of a try/finally
>> > construct.  The difficulty is that there's no guarantee the generator
>> > will ever be resumed, hence no guarantee that the finally block will
>> > ever get executed; that's too much a violation of finally's purpose to
>> > bear." from https://www.python.org/dev/peps/pep-0255/
>> >
>> > But, meanwhile, the code showed on that page use yield in a try/finally
>> > case. It really puzzles me. Is there anything wrong?
>> 
>> I think what it means is that you can put a yield in the finally block
>> but not the try block so:
>> 
>> # Not allowed
>> def  f():
>>     try:
>>         yield 1
>>     finally:
>>         pass
>> 
>> # Allowed
>> def f():
>>     try:
>>         pass
>>     finally:
>>         yield 1
>> 
>> However that information is out of date. The restriction was removed
>> in some later Python version. Actually the construct is quite common
>> when using generator functions to implement context managers:
>> 
>> @contextlib.contextmanager
>> def replace_stdin(newstdin):
>>     oldstdin = sys.stdin
>>     try:
>>         sys.stdin = newstdin
>>         yield
>>     finally:
>>         sys.stdin = oldstdin
>> 
>> Although the restriction was removed the problem itself still remains.
>> There's no guarantee that a finally block will execute if there is a
>> yield in the try block. The same happens if you use a context manager
>> around a yield statement: the __exit__ method is not guaranteed to be
>> called. One implication of this is that in the following code it is
>> not guaranteed that the file will be closed:
>> 
>> def upperfile(filename):
>>     with open(filename) as fin:
>>         for line in fin:
>>             yield line.upper()
>> 
>> --
>> Oscar
> 
> 
> It really nice of you to answer the question. But I am still confused with
> your last example, is there any case that the file with not be closed? I
> just run the code and no exception occur.

It doesn't happen easily, you have to defeat CPython's garbage collection. 
Consider the follwing script:

$ cat upper1.py
import sys

_open = open
files = []

def open(*args, **kw):
    """Use a modified open() which keeps track of opened files.

    This allows us to check whether the files are properly closed and
    also to defeat garbage collection.
    """
    f = _open(*args, **kw)
    files.append(f)
    return f


for filename in sys.argv[1:]:
    with open(filename) as f:
        for line in f:
            print(line.upper(), end="")
            break

assert all(f.closed for f in files)

$ echo -e 'foo\nbar\nbaz' > tmp1.txt
$ echo -e 'hams\nspam\njam' > tmp2.txt
$ python3 upper1.py *.txt
FOO
HAMS

As expected it prints the first lines of the files provided as commandline 
args, in upper case. Now let's refactor:

$ cat upper2.py
import sys

_open = open
files = []

def open(*args, **kw):
    """Use a modified open() which keeps track of opened files.

    This allows us to check whether the files are properly closed (and
    also defeats garbage collection).
    """
    f = _open(*args, **kw)
    files.append(f)
    return f

def upperfile(filename):
    with open(filename) as f:
        for line in f:
            yield line.upper()

for uf in map(upperfile, sys.argv[1:]):
    for line in uf:
        print(line, end="")
        break

assert all(f.closed for f in files)

The change looks harmless, we moved the with statement and the conversion 
into the generater. But when whe run it:

$ python3 upper2.py *.txt
FOO
HAMS
Traceback (most recent call last):
  File "upper2.py", line 26, in <module>
    assert all(f.closed for f in files)
AssertionError

This is because the last generator uf = upperfile(...) is not garbage-
collected and wasn't explicitly closed either. If you do care here's one 
possible fix:

from contextlib import closing
...
for uf in map(upperfile, sys.argv[1:]):
    with closing(uf):
        for line in uf:
            print(line, end="")
            break

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

yield in try/finally case 刘琦帆 <lqf.txx@gmail.com> - 2016-03-03 03:52 -0800
  Re: yield in try/finally case Oscar Benjamin <oscar.j.benjamin@gmail.com> - 2016-03-03 12:13 +0000
    Re: yield in try/finally case 刘琦帆 <lqf.txx@gmail.com> - 2016-03-03 04:52 -0800
      Re: yield in try/finally case Peter Otten <__peter__@web.de> - 2016-03-03 14:47 +0100
      Re: yield in try/finally case Random832 <random832@fastmail.com> - 2016-03-03 10:12 -0500
      Re: yield in try/finally case Peter Otten <__peter__@web.de> - 2016-03-03 17:20 +0100
      Re: yield in try/finally case Oscar Benjamin <oscar.j.benjamin@gmail.com> - 2016-03-03 16:24 +0000
  Re: yield in try/finally case Random832 <random832@fastmail.com> - 2016-03-03 10:00 -0500
    Re: yield in try/finally case Steven D'Aprano <steve@pearwood.info> - 2016-03-04 02:57 +1100

csiph-web