Skip Montanaro wrote:
    Guido> or perhaps even (making "for VAR" optional in the for-loop syntax)
    Guido> with

    Guido>     in synchronized(the_lock):
    Guido>         BODY

This could be a new statement, so the problematic issue of implicit
try/finally in every for statement wouldn't be necessary.  That complication
would only be needed for the above form.

s/in/with/ to get PEP 310.

A parallel which has been bugging me is the existence of the iterator protocol (__iter__, next()) which you can implement manually if you want, and the existence of generators, which provide a nice clean way of writing iterators as functions.

I'm wondering if something similar can't be found for the __enter__/__exit__ resource protocol.

Guido's recent screed crystallised the idea of writing resources as two-part generators:

def my_resource():
  print "Hi!"   # Do entrance code
  yield None    # Go on with the contents of the 'with' block
  print "Bye!"  # Do exit code

Giving the internal generator object an enter method that calls self.next() (expecting None to be returned), and an exit method that does the same (but expects StopIteration to be raised) should suffice to make this possible with a PEP 310 style syntax.

Interestingly, with this approach, "for dummy in my_resource()" would still wrap the block of code in the entrance/exit code (because my_resource *is* a generator), but it wouldn't get the try/finally semantics.

An alternative would be to replace the 'yield None' with a 'break' or 'continue', and create an object which supports the resource protocol and NOT the iterator protocol. Something like:

def my_resource():
  print "Hi!"   # Do entrance code
  continue      # Go on with the contents of the 'with' block
  print "Bye!"  # Do exit code

(This is currently a SyntaxError, so it isn't ambiguous in any way)

Cheers,
Nick.

--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---------------------------------------------------------------
            http://boredomandlaziness.skystorm.net
_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to