forked from python/peps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpep-0346.txt
1303 lines (988 loc) · 43.6 KB
/
pep-0346.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
PEP: 346
Title: User Defined ("``with``") Statements
Version: $Revision$
Last-Modified: $Date$
Author: Nick Coghlan <[email protected]>
Status: Withdrawn
Type: Standards Track
Content-Type: text/x-rst
Created: 6-May-2005
Python-Version: 2.5
Post-History:
Abstract
========
This PEP is a combination of PEP 310's "Reliable Acquisition/Release
Pairs" with the "Anonymous Block Statements" of Guido's PEP 340. This
PEP aims to take the good parts of PEP 340, blend them with parts of
PEP 310 and rearrange the lot into an elegant whole. It borrows from
various other PEPs in order to paint a complete picture, and is
intended to stand on its own.
Author's Note
=============
During the discussion of PEP 340, I maintained drafts of this PEP as
PEP 3XX on my own website (since I didn't have CVS access to update a
submitted PEP fast enough to track the activity on python-dev).
Since the first draft of this PEP, Guido wrote PEP 343 as a simplified
version of PEP 340. PEP 343 (at the time of writing) uses the exact
same semantics for the new statements as this PEP, but uses a slightly
different mechanism to allow generators to be used to write statement
templates. However, Guido has indicated that he intends to accept a
new PEP being written by Raymond Hettinger that will integrate PEP 288
and PEP 325, and will permit a generator decorator like the one
described in this PEP to be used to write statement templates for PEP
343. The other difference was the choice of keyword ('with' versus
'do') and Guido has stated he will organise a vote on that in the
context of PEP 343.
Accordingly, the version of this PEP submitted for archiving on
python.org is to be WITHDRAWN immediately after submission. PEP 343
and the combined generator enhancement PEP will cover the important
ideas.
Introduction
============
This PEP proposes that Python's ability to reliably manage resources
be enhanced by the introduction of a new ``with`` statement that
allows factoring out of arbitrary ``try``/``finally`` and some
``try``/``except``/``else`` boilerplate. The new construct is called
a 'user defined statement', and the associated class definitions are
called 'statement templates'.
The above is the main point of the PEP. However, if that was all it
said, then PEP 310 would be sufficient and this PEP would be
essentially redundant. Instead, this PEP recommends additional
enhancements that make it natural to write these statement templates
using appropriately decorated generators. A side effect of those
enhancements is that it becomes important to appropriately deal
with the management of resources inside generators.
This is quite similar to PEP 343, but the exceptions that occur are
re-raised inside the generators frame, and the issue of generator
finalisation needs to be addressed as a result. The template
generator decorator suggested by this PEP also creates reusable
templates, rather than the single use templates of PEP 340.
In comparison to PEP 340, this PEP eliminates the ability to suppress
exceptions, and makes the user defined statement a non-looping
construct. The other main difference is the use of a decorator to
turn generators into statement templates, and the incorporation of
ideas for addressing iterator finalisation.
If all that seems like an ambitious operation. . . well, Guido was the
one to set the bar that high when he wrote PEP 340 :)
Relationship with other PEPs
============================
This PEP competes directly with PEP 310 [1]_, PEP 340 [2]_ and PEP 343
[3]_, as those PEPs all describe alternative mechanisms for handling
deterministic resource management.
It does not compete with PEP 342 [4]_ which splits off PEP 340's
enhancements related to passing data into iterators. The associated
changes to the ``for`` loop semantics would be combined with the
iterator finalisation changes suggested in this PEP. User defined
statements would not be affected.
Neither does this PEP compete with the generator enhancements
described in PEP 288 [5]_. While this PEP proposes the ability to
inject exceptions into generator frames, it is an internal
implementation detail, and does not require making that ability
publicly available to Python code. PEP 288 is, in part, about
making that implementation detail easily accessible.
This PEP would, however, make the generator resource release support
described in PEP 325 [6]_ redundant - iterators which require
finalisation should provide an appropriate implementation of the
statement template protocol.
User defined statements
=======================
To steal the motivating example from PEP 310, correct handling of a
synchronisation lock currently looks like this::
the_lock.acquire()
try:
# Code here executes with the lock held
finally:
the_lock.release()
Like PEP 310, this PEP proposes that such code be able to be written
as::
with the_lock:
# Code here executes with the lock held
These user defined statements are primarily designed to allow easy
factoring of ``try`` blocks that are not easily converted to
functions. This is most commonly the case when the exception handling
pattern is consistent, but the body of the ``try`` block changes.
With a user-defined statement, it is straightforward to factor out the
exception handling into a statement template, with the body of the
``try`` clause provided inline in the user code.
The term 'user defined statement' reflects the fact that the meaning
of a ``with`` statement is governed primarily by the statement
template used, and programmers are free to create their own statement
templates, just as they are free to create their own iterators for use
in ``for`` loops.
Usage syntax for user defined statements
----------------------------------------
The proposed syntax is simple::
with EXPR1 [as VAR1]:
BLOCK1
Semantics for user defined statements
-------------------------------------
::
the_stmt = EXPR1
stmt_enter = getattr(the_stmt, "__enter__", None)
stmt_exit = getattr(the_stmt, "__exit__", None)
if stmt_enter is None or stmt_exit is None:
raise TypeError("Statement template required")
VAR1 = stmt_enter() # Omit 'VAR1 =' if no 'as' clause
exc = (None, None, None)
try:
try:
BLOCK1
except:
exc = sys.exc_info()
raise
finally:
stmt_exit(*exc)
Other than ``VAR1``, none of the local variables shown above will be
visible to user code. Like the iteration variable in a ``for`` loop,
``VAR1`` is visible in both ``BLOCK1`` and code following the user
defined statement.
Note that the statement template can only react to exceptions, it
cannot suppress them. See `Rejected Options`_ for an explanation as
to why.
Statement template protocol: ``__enter__``
------------------------------------------
The ``__enter__()`` method takes no arguments, and if it raises an
exception, ``BLOCK1`` is never executed. If this happens, the
``__exit__()`` method is not called. The value returned by this
method is assigned to VAR1 if the ``as`` clause is used. Object's
with no other value to return should generally return ``self`` rather
than ``None`` to permit in-place creation in the ``with`` statement.
Statement templates should use this method to set up the conditions
that are to exist during execution of the statement (e.g. acquisition
of a synchronisation lock).
Statement templates which are not always usable (e.g. closed file
objects) should raise a ``RuntimeError`` if an attempt is made to call
``__enter__()`` when the template is not in a valid state.
Statement template protocol: ``__exit__``
-----------------------------------------
The ``__exit__()`` method accepts three arguments which correspond to
the three "arguments" to the ``raise`` statement: type, value, and
traceback. All arguments are always supplied, and will be set to
``None`` if no exception occurred. This method will be called exactly
once by the ``with`` statement machinery if the ``__enter__()`` method
completes successfully.
Statement templates perform their exception handling in this method.
If the first argument is ``None``, it indicates non-exceptional
completion of ``BLOCK1`` - execution either reached the end of block,
or early completion was forced using a ``return``, ``break`` or
``continue`` statement. Otherwise, the three arguments reflect the
exception that terminated ``BLOCK1``.
Any exceptions raised by the ``__exit__()`` method are propagated to
the scope containing the ``with`` statement. If the user code in
``BLOCK1`` also raised an exception, that exception would be lost, and
replaced by the one raised by the ``__exit__()`` method.
Factoring out arbitrary exception handling
------------------------------------------
Consider the following exception handling arrangement::
SETUP_BLOCK
try:
try:
TRY_BLOCK
except exc_type1, exc:
EXCEPT_BLOCK1
except exc_type2, exc:
EXCEPT_BLOCK2
except:
EXCEPT_BLOCK3
else:
ELSE_BLOCK
finally:
FINALLY_BLOCK
It can be roughly translated to a statement template as follows::
class my_template(object):
def __init__(self, *args):
# Any required arguments (e.g. a file name)
# get stored in member variables
# The various BLOCK's will need updating to reflect
# that.
def __enter__(self):
SETUP_BLOCK
def __exit__(self, exc_type, value, traceback):
try:
try:
if exc_type is not None:
raise exc_type, value, traceback
except exc_type1, exc:
EXCEPT_BLOCK1
except exc_type2, exc:
EXCEPT_BLOCK2
except:
EXCEPT_BLOCK3
else:
ELSE_BLOCK
finally:
FINALLY_BLOCK
Which can then be used as::
with my_template(*args):
TRY_BLOCK
However, there are two important semantic differences between this
code and the original ``try`` statement.
Firstly, in the original ``try`` statement, if a ``break``, ``return``
or ``continue`` statement is encountered in ``TRY_BLOCK``, only
``FINALLY_BLOCK`` will be executed as the statement completes. With
the statement template, ``ELSE_BLOCK`` will also execute, as these
statements are treated like any other non-exceptional block
termination. For use cases where it matters, this is likely to be a
good thing (see ``transaction`` in the Examples_), as this hole where
neither the ``except`` nor the ``else`` clause gets executed is easy
to forget when writing exception handlers.
Secondly, the statement template will not suppress any exceptions.
If, for example, the original code suppressed the ``exc_type1`` and
``exc_type2`` exceptions, then this would still need to be done inline
in the user code::
try:
with my_template(*args):
TRY_BLOCK
except (exc_type1, exc_type2):
pass
However, even in these cases where the suppression of exceptions needs
to be made explicit, the amount of boilerplate repeated at the calling
site is significantly reduced (See `Rejected Options`_ for further
discussion of this behaviour).
In general, not all of the clauses will be needed. For resource
handling (like files or synchronisation locks), it is possible to
simply execute the code that would have been part of ``FINALLY_BLOCK``
in the ``__exit__()`` method. This can be seen in the following
implementation that makes synchronisation locks into statement
templates as mentioned at the beginning of this section::
# New methods of synchronisation lock objects
def __enter__(self):
self.acquire()
return self
def __exit__(self, *exc_info):
self.release()
Generators
==========
With their ability to suspend execution, and return control to the
calling frame, generators are natural candidates for writing statement
templates. Adding user defined statements to the language does *not*
require the generator changes described in this section, thus making
this PEP an obvious candidate for a phased implementation (``with``
statements in phase 1, generator integration in phase 2). The
suggested generator updates allow arbitrary exception handling to
be factored out like this::
@statement_template
def my_template(*arguments):
SETUP_BLOCK
try:
try:
yield
except exc_type1, exc:
EXCEPT_BLOCK1
except exc_type2, exc:
EXCEPT_BLOCK2
except:
EXCEPT_BLOCK3
else:
ELSE_BLOCK
finally:
FINALLY_BLOCK
Notice that, unlike the class based version, none of the blocks need
to be modified, as shared values are local variables of the
generator's internal frame, including the arguments passed in by the
invoking code. The semantic differences noted earlier (all
non-exceptional block termination triggers the ``else`` clause, and
the template is unable to suppress exceptions) still apply.
Default value for ``yield``
---------------------------
When creating a statement template with a generator, the ``yield``
statement will often be used solely to return control to the body of
the user defined statement, rather than to return a useful value.
Accordingly, if this PEP is accepted, ``yield``, like ``return``, will
supply a default value of ``None`` (i.e. ``yield`` and ``yield None``
will become equivalent statements).
This same change is being suggested in PEP 342. Obviously, it would
only need to be implemented once if both PEPs were accepted :)
Template generator decorator: ``statement_template``
----------------------------------------------------
As with PEP 343, a new decorator is suggested that wraps a generator
in an object with the appropriate statement template semantics.
Unlike PEP 343, the templates suggested here are reusable, as the
generator is instantiated anew in each call to ``__enter__()``.
Additionally, any exceptions that occur in ``BLOCK1`` are re-raised in
the generator's internal frame::
class template_generator_wrapper(object):
def __init__(self, func, func_args, func_kwds):
self.func = func
self.args = func_args
self.kwds = func_kwds
self.gen = None
def __enter__(self):
if self.gen is not None:
raise RuntimeError("Enter called without exit!")
self.gen = self.func(*self.args, **self.kwds)
try:
return self.gen.next()
except StopIteration:
raise RuntimeError("Generator didn't yield")
def __exit__(self, *exc_info):
if self.gen is None:
raise RuntimeError("Exit called without enter!")
try:
try:
if exc_info[0] is not None:
self.gen._inject_exception(*exc_info)
else:
self.gen.next()
except StopIteration:
pass
else:
raise RuntimeError("Generator didn't stop")
finally:
self.gen = None
def statement_template(func):
def factory(*args, **kwds):
return template_generator_wrapper(func, args, kwds)
return factory
Template generator wrapper: ``__enter__()`` method
--------------------------------------------------
The template generator wrapper has an ``__enter__()`` method that
creates a new instance of the contained generator, and then invokes
``next()`` once. It will raise a ``RuntimeError`` if the last
generator instance has not been cleaned up, or if the generator
terminates instead of yielding a value.
Template generator wrapper: ``__exit__()`` method
-------------------------------------------------
The template generator wrapper has an ``__exit__()`` method that
simply invokes ``next()`` on the generator if no exception is passed
in. If an exception is passed in, it is re-raised in the contained
generator at the point of the last ``yield`` statement.
In either case, the generator wrapper will raise a RuntimeError if the
internal frame does not terminate as a result of the operation. The
``__exit__()`` method will always clean up the reference to the used
generator instance, permitting ``__enter__()`` to be called again.
A ``StopIteration`` raised by the body of the user defined statement
may be inadvertently suppressed inside the ``__exit__()`` method, but
this is unimportant, as the originally raised exception still
propagates correctly.
Injecting exceptions into generators
------------------------------------
To implement the ``__exit__()`` method of the template generator
wrapper, it is necessary to inject exceptions into the internal frame
of the generator. This is new implementation level behaviour that has
no current Python equivalent.
The injection mechanism (referred to as ``_inject_exception`` in this
PEP) raises an exception in the generator's frame with the specified
type, value and traceback information. This means that the exception
looks like the original if it is allowed to propagate.
For the purposes of this PEP, there is no need to make this capability
available outside the Python implementation code.
Generator finalisation
----------------------
To support resource management in template generators, this PEP will
eliminate the restriction on ``yield`` statements inside the ``try``
block of a ``try``/``finally`` statement. Accordingly, generators
which require the use of a file or some such object can ensure the
object is managed correctly through the use of ``try``/``finally`` or
``with`` statements.
This restriction will likely need to be lifted globally - it would be
difficult to restrict it so that it was only permitted inside
generators used to define statement templates. Accordingly, this PEP
includes suggestions designed to ensure generators which are not used
as statement templates are still finalised appropriately.
Generator finalisation: ``TerminateIteration`` exception
--------------------------------------------------------
A new exception is proposed::
class TerminateIteration(Exception): pass
The new exception is injected into a generator in order to request
finalisation. It should not be suppressed by well-behaved code.
Generator finalisation: ``__del__()`` method
--------------------------------------------
To ensure a generator is finalised eventually (within the limits of
Python's garbage collection), generators will acquire a ``__del__()``
method with the following semantics::
def __del__(self):
try:
self._inject_exception(TerminateIteration, None, None)
except TerminateIteration:
pass
Deterministic generator finalisation
------------------------------------
There is a simple way to provide deterministic finalisation of
generators - give them appropriate ``__enter__()`` and ``__exit__()``
methods::
def __enter__(self):
return self
def __exit__(self, *exc_info):
try:
self._inject_exception(TerminateIteration, None, None)
except TerminateIteration:
pass
Then any generator can be finalised promptly by wrapping the relevant
``for`` loop inside a ``with`` statement::
with all_lines(filenames) as lines:
for line in lines:
print lines
(See the Examples_ for the definition of ``all_lines``, and the reason
it requires prompt finalisation)
Compare the above example to the usage of file objects::
with open(filename) as f:
for line in f:
print f
Generators as user defined statement templates
----------------------------------------------
When used to implement a user defined statement, a generator should
yield only once on a given control path. The result of that yield
will then be provided as the result of the generator's ``__enter__()``
method. Having a single ``yield`` on each control path ensures that
the internal frame will terminate when the generator's ``__exit__()``
method is called. Multiple ``yield`` statements on a single control
path will result in a ``RuntimeError`` being raised by the
``__exit__()`` method when the internal frame fails to terminate
correctly. Such an error indicates a bug in the statement template.
To respond to exceptions, or to clean up resources, it is sufficient
to wrap the ``yield`` statement in an appropriately constructed
``try`` statement. If execution resumes after the ``yield`` without
an exception, the generator knows that the body of the ``do``
statement completed without incident.
Examples
========
1. A template for ensuring that a lock, acquired at the start of a
block, is released when the block is left::
# New methods on synchronisation locks
def __enter__(self):
self.acquire()
return self
def __exit__(self, *exc_info):
lock.release()
Used as follows::
with myLock:
# Code here executes with myLock held. The lock is
# guaranteed to be released when the block is left (even
# if via return or by an uncaught exception).
2. A template for opening a file that ensures the file is closed when
the block is left::
# New methods on file objects
def __enter__(self):
if self.closed:
raise RuntimeError, "Cannot reopen closed file handle"
return self
def __exit__(self, *args):
self.close()
Used as follows::
with open("/etc/passwd") as f:
for line in f:
print line.rstrip()
3. A template for committing or rolling back a database transaction::
def transaction(db):
try:
yield
except:
db.rollback()
else:
db.commit()
Used as follows::
with transaction(the_db):
make_table(the_db)
add_data(the_db)
# Getting to here automatically triggers a commit
# Any exception automatically triggers a rollback
4. It is possible to nest blocks and combine templates::
@statement_template
def lock_opening(lock, filename, mode="r"):
with lock:
with open(filename, mode) as f:
yield f
Used as follows::
with lock_opening(myLock, "/etc/passwd") as f:
for line in f:
print line.rstrip()
5. Redirect stdout temporarily::
@statement_template
def redirected_stdout(new_stdout):
save_stdout = sys.stdout
try:
sys.stdout = new_stdout
yield
finally:
sys.stdout = save_stdout
Used as follows::
with open(filename, "w") as f:
with redirected_stdout(f):
print "Hello world"
6. A variant on ``open()`` that also returns an error condition::
@statement_template
def open_w_error(filename, mode="r"):
try:
f = open(filename, mode)
except IOError, err:
yield None, err
else:
try:
yield f, None
finally:
f.close()
Used as follows::
do open_w_error("/etc/passwd", "a") as f, err:
if err:
print "IOError:", err
else:
f.write("guido::0:0::/:/bin/sh\n")
7. Find the first file with a specific header::
for name in filenames:
with open(name) as f:
if f.read(2) == 0xFEB0:
break
8. Find the first item you can handle, holding a lock for the entire
loop, or just for each iteration::
with lock:
for item in items:
if handle(item):
break
for item in items:
with lock:
if handle(item):
break
9. Hold a lock while inside a generator, but release it when
returning control to the outer scope::
@statement_template
def released(lock):
lock.release()
try:
yield
finally:
lock.acquire()
Used as follows::
with lock:
for item in items:
with released(lock):
yield item
10. Read the lines from a collection of files (e.g. processing
multiple configuration sources)::
def all_lines(filenames):
for name in filenames:
with open(name) as f:
for line in f:
yield line
Used as follows::
with all_lines(filenames) as lines:
for line in lines:
update_config(line)
11. Not all uses need to involve resource management::
@statement_template
def tag(*args, **kwds):
name = cgi.escape(args[0])
if kwds:
kwd_pairs = ["%s=%s" % cgi.escape(key), cgi.escape(value)
for key, value in kwds]
print '<%s %s>' % name, " ".join(kwd_pairs)
else:
print '<%s>' % name
yield
print '</%s>' % name
Used as follows::
with tag('html'):
with tag('head'):
with tag('title'):
print 'A web page'
with tag('body'):
for par in pars:
with tag('p'):
print par
with tag('a', href="http://www.python.org"):
print "Not a dead parrot!"
12. From PEP 343, another useful example would be an operation that
blocks signals. The use could be like this::
from signal import blocked_signals
with blocked_signals():
# code executed without worrying about signals
An optional argument might be a list of signals to be blocked; by
default all signals are blocked. The implementation is left as an
exercise to the reader.
13. Another use for this feature is for Decimal contexts::
# New methods on decimal Context objects
def __enter__(self):
if self._old_context is not None:
raise RuntimeError("Already suspending other Context")
self._old_context = getcontext()
setcontext(self)
def __exit__(self, *args):
setcontext(self._old_context)
self._old_context = None
Used as follows::
with decimal.Context(precision=28):
# Code here executes with the given context
# The context always reverts after this statement
Open Issues
===========
None, as this PEP has been withdrawn.
Rejected Options
================
Having the basic construct be a looping construct
-------------------------------------------------
The major issue with this idea, as illustrated by PEP 340's
``block`` statements, is that it causes problems with factoring
``try`` statements that are inside loops, and contain ``break`` and
``continue`` statements (as these statements would then apply to the
``block`` construct, instead of the original loop). As a key goal is
to be able to factor out arbitrary exception handling (other than
suppression) into statement templates, this is a definite problem.
There is also an understandability problem, as can be seen in the
Examples_. In the example showing acquisition of a lock either for an
entire loop, or for each iteration of the loop, if the user defined
statement was itself a loop, moving it from outside the ``for`` loop
to inside the ``for`` loop would have major semantic implications,
beyond those one would expect.
Finally, with a looping construct, there are significant problems with
TOOWTDI, as it is frequently unclear whether a particular situation
should be handled with a conventional ``for`` loop or the new looping
construct. With the current PEP, there is no such problem - ``for``
loops continue to be used for iteration, and the new ``do`` statements
are used to factor out exception handling.
Another issue, specifically with PEP 340's anonymous block statements,
is that they make it quite difficult to write statement templates
directly (i.e. not using a generator). This problem is addressed by
the current proposal, as can be seen by the relative simplicity of the
various class based implementations of statement templates in the
Examples_.
Allowing statement templates to suppress exceptions
---------------------------------------------------
Earlier versions of this PEP gave statement templates the ability to
suppress exceptions. The BDFL expressed concern over the associated
complexity, and I agreed after reading an article by Raymond Chen
about the evils of hiding flow control inside macros in C code [7]_.
Removing the suppression ability eliminated a whole lot of complexity
from both the explanation and implementation of user defined
statements, further supporting it as the correct choice. Older
versions of the PEP had to jump through some horrible hoops to avoid
inadvertently suppressing exceptions in ``__exit__()`` methods - that
issue does not exist with the current suggested semantics.
There was one example (``auto_retry``) that actually used the ability
to suppress exceptions. This use case, while not quite as elegant,
has significantly more obvious control flow when written out in full
in the user code::
def attempts(num_tries):
return reversed(xrange(num_tries))
for retry in attempts(3):
try:
make_attempt()
except IOError:
if not retry:
raise
For what it's worth, the perverse could still write this as::
for attempt in auto_retry(3, IOError):
try:
with attempt:
make_attempt()
except FailedAttempt:
pass
To protect the innocent, the code to actually support that is not
included here.
Differentiating between non-exceptional exits
---------------------------------------------
Earlier versions of this PEP allowed statement templates to
distinguish between exiting the block normally, and exiting via a
``return``, ``break`` or ``continue`` statement. The BDFL flirted
with a similar idea in PEP 343 and its associated discussion. This
added significant complexity to the description of the semantics, and
it required each and every statement template to decide whether or not
those statements should be treated like exceptions, or like a normal
mechanism for exiting the block.
This template-by-template decision process raised great potential for
confusion - consider if one database connector provided a transaction
template that treated early exits like an exception, whereas a second
connector treated them as normal block termination.
Accordingly, this PEP now uses the simplest solution - early exits
appear identical to normal block termination as far as the statement
template is concerned.
Not injecting raised exceptions into generators
-----------------------------------------------
PEP 343 suggests simply invoking next() unconditionally on generators
used to define statement templates. This means the template
generators end up looking rather unintuitive, and the retention of the
ban against yielding inside ``try``/``finally`` means that Python's
exception handling capabilities cannot be used to deal with management
of multiple resources.
The alternative which this PEP advocates (injecting raised exceptions
into the generator frame), means that multiple resources can be
managed elegantly as shown by ``lock_opening`` in the Examples_
Making all generators statement templates
-----------------------------------------
Separating the template object from the generator itself makes it
possible to have reusable generator templates. That is, the following
code will work correctly if this PEP is accepted::
open_it = lock_opening(parrot_lock, "dead_parrot.txt")
with open_it as f:
# use the file for a while
with open_it as f:
# use the file again
The second benefit is that iterator generators and template generators
are very different things - the decorator keeps that distinction
clear, and prevents one being used where the other is required.
Finally, requiring the decorator allows the native methods of
generator objects to be used to implement generator finalisation.
Using ``do`` as the keyword
---------------------------
``do`` was an alternative keyword proposed during the PEP 340
discussion. It reads well with appropriately named functions, but it
reads poorly when used with methods, or with objects that provide
native statement template support.
When ``do`` was first suggested, the BDFL had rejected PEP 310's
``with`` keyword, based on a desire to use it for a Pascal/Delphi
style ``with`` statement. Since then, the BDFL has retracted this
objection, as he no longer intends to provide such a statement. This
change of heart was apparently based on the C# developers reasons for
not providing the feature [8]_.
Not having a keyword
--------------------
This is an interesting option, and can be made to read quite well.
However, it's awkward to look up in the documentation for new users,
and strikes some as being too magical. Accordingly, this PEP goes
with a keyword based suggestion.
Enhancing ``try`` statements
----------------------------
This suggestion involves give bare ``try`` statements a signature
similar to that proposed for ``with`` statements.
I think that trying to write a ``with`` statement as an enhanced
``try`` statement makes as much sense as trying to write a ``for``
loop as an enhanced ``while`` loop. That is, while the semantics of
the former can be explained as a particular way of using the latter,
the former is not an *instance* of the latter. The additional
semantics added around the more fundamental statement result in a new
construct, and the two different statements shouldn't be confused.
This can be seen by the fact that the 'enhanced' ``try`` statement
still needs to be explained in terms of a 'non-enhanced' ``try``
statement. If it's something different, it makes more sense to give
it a different name.
Having the template protocol directly reflect ``try`` statements
----------------------------------------------------------------
One suggestion was to have separate methods in the protocol to cover
different parts of the structure of a generalised ``try`` statement.
Using the terms ``try``, ``except``, ``else`` and ``finally``, we
would have something like::
class my_template(object):
def __init__(self, *args):
# Any required arguments (e.g. a file name)
# get stored in member variables
# The various BLOCK's will need to updated to reflect
# that.
def __try__(self):
SETUP_BLOCK