[Python-Dev] PEP 340: Deterministic Finalisation (new PEP draft, either a competitor or update to PEP 340)

Eric Nieuwland eric.nieuwland at xs4all.nl
Mon May 9 20:21:15 CEST 2005


Greg Ewing wrote:
> Ron Adam wrote:
>> There seems to be some confusion as to weather or
>> not 'for's will do finalizing.  So I was trying to stress I think
>> regular 'for' loops should not finalize. They should probably give an
>> error if an object with an try-finally in them or an __exit__ method.
>
> But if the for-loop can tell whether the iterator
> needs finalizing or not, why not have it finalize
> the ones that need it and not finalize the ones
> that don't? That would be backwards compatible,
> since old for-loops working on old iterators would
> work as before.

That's why I suggested to have the behaviour depend on what is passed 
in as EXPR.

for VAR in EXPR:
	BLOCK

could be translated to:

__cleanup = False
__itr = EXPR
if not isinstance(__itr,iterator):
	__itr = iter(__itr)
	__cleanup = True
while True:
	try:
		VAR = __itr.next()
	except StopIteration:
		break
	BLOCK
if __cleanup:
	__itr.__exit__()

Which would require isinstance(__itr,iterator) or equivalent to act as 
a robust test on iterators.
I'll leave 'for' with an 'else' clause as an exercise to the reader.

--eric



More information about the Python-Dev mailing list