[Python-Dev] PEP 343 - Abstract Block Redux
Nick Coghlan
ncoghlan at gmail.com
Sat May 14 03:15:32 CEST 2005
Guido van Rossum wrote:
> I've written up the specs for my "PEP 340 redux" proposal as a
> separate PEP, PEP 343.
>
> http://python.org/peps/pep-0343.html
>
> Those who have been following the thread "Merging PEP 310 and PEP
> 340-redux?" will recognize my proposal in that thread, which received
> mostly positive responses there.
>
> Please review and ask for clarifications of anything that's unclear.
+1 here.
The stdout redirection example needs to be corrected to avoid yielding inside a
try/finally though:
5. Redirect stdout temporarily:
@do_template
def redirecting_stdout(new_stdout):
save_stdout = sys.stdout
try:
sys.stdout = new_stdout
except:
sys.stdout = save_stdout
raise
else:
yield None
sys.stdout = save_stdout
Used as follows:
do opening(filename, "w") as f:
do redirecting_stdout(f):
print "Hello world"
This could be left as the more elegant original if iterator finalisation (e.g.
using a "__finish__()" slot) came in at the same time as user defined
statements, allowing the above to be written naturally with try/finally.
Arnold deVos's HTML tagging example would need access to the exception
information and could be rewritten as a class:
def tag(object):
def __init__(self, name):
self.name = cgi.escape(name)
def __enter__(self):
print '<%s>' % self.name
return self.name
def __exit__(self, *exc_info):
if not exc_info or exc_info[0] is None:
print '</%s>' % self.name
Used as follows::
do tag('html'):
do tag('head'):
do tag('title'):
print 'A web page'
do tag('body'):
for par in pars:
do tag('p'):
print par
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.blogspot.com
More information about the Python-Dev
mailing list