[Python-Dev] Simpler finalization semantics (was Re: PEP 343 - Abstract Block Redux)
Phillip J. Eby
pje at telecommunity.com
Tue May 17 17:55:46 CEST 2005
At 11:03 PM 5/17/2005 +1000, Nick Coghlan wrote:
>Do you mean translating this:
>
> with EXPR1 as VAR1:
> BLOCK1
>
>To something along the lines of:
>
> the_stmt = EXPR1
> stmt_enter = getattr(the_stmt, "__enter__", None)
> stmt_exit = getattr(the_stmt, "__exit__", None)
>
> if stmt_enter is None:
> VAR1 = the_stmt
> else:
> VAR1 = stmt_enter()
>
> if stmt_exit is None:
> BLOCK1
> else:
> exc = (None, None, None)
> try:
> try:
> BLOCK1
> except:
> exc = sys.exc_info()
> raise
> finally:
> stmt_exit(*exc)
Essentially, yes; although I was actually suggesting that there be
PyResource_Enter() and PyResource_Exit() C APIs that would supply the
default behaviors if the tp_resource_enter and tp_resource_exit slots were
missing from the object's type. But that's an implementation detail.
>It has a certain elegance - you can switch from using an object that needs
>finalisation to one that doesn't without having to change your code.
>
>And library code can safely ensure finalisation without having to check
>whether
>the object needs it or not - that check becomes an inherent part of the with
>statement.
Precisely.
More information about the Python-Dev
mailing list