[Python-Dev] PEP 525, third round, better finalization (original) (raw)

Yury Selivanov yselivanov.ml at gmail.com
Sat Sep 3 15:16:30 EDT 2016


Hi Oscar,

I don't think PyPy is in breach of the language spec here. Python made a decision a long time ago to shun RAII-style implicit cleanup in favour if with-style explicit cleanup.

The solution to this problem is to move resource management outside of the generator functions. This is true for ordinary generators without an event-loop etc. The example in the PEP is async def squareseries(con, to): async with con.transaction(): cursor = con.cursor( 'SELECT generateseries(0, $1) AS i', to) async for row in cursor: yield row['i'] ** 2 async for i in squareseries(con, 1000): if i == 100: break The normal generator equivalent of this is: def squareseries(con, to): with con.transaction(): cursor = con.cursor( 'SELECT generateseries(0, $1) AS i', to) for row in cursor: yield row['i'] ** 2 This code is already broken: move the with statement outside to the caller of the generator function.

Exactly.

I used 'async with' in the PEP to demonstrate that the cleanup mechanisms are powerful enough to handle bad code patterns.

Thank you, Yury



More information about the Python-Dev mailing list