forked from python/python-docs-tr
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path2.5.html
More file actions
2351 lines (2277 loc) · 254 KB
/
2.5.html
File metadata and controls
2351 lines (2277 loc) · 254 KB
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
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" />
<meta property="og:title" content="What’s New in Python 2.5" />
<meta property="og:type" content="website" />
<meta property="og:url" content="https://docs.python.org/3/whatsnew/2.5.html" />
<meta property="og:site_name" content="Python documentation" />
<meta property="og:description" content="Author, A.M. Kuchling,. This article explains the new features in Python 2.5. The final release of Python 2.5 is scheduled for August 2006; PEP 356 describes the planned release schedule. Python 2...." />
<meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
<meta property="og:image:alt" content="Python documentation" />
<meta name="description" content="Author, A.M. Kuchling,. This article explains the new features in Python 2.5. The final release of Python 2.5 is scheduled for August 2006; PEP 356 describes the planned release schedule. Python 2...." />
<meta property="og:image:width" content="200" />
<meta property="og:image:height" content="200" />
<meta name="theme-color" content="#3776ab" />
<title>What’s New in Python 2.5 — Python 3.11.5 belgelendirmesi</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?digest=b37c26da2f7529d09fe70b41c4b2133fe4931a90" />
<link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css" />
<script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
<script src="../_static/doctools.js"></script>
<script src="../_static/sphinx_highlight.js"></script>
<script src="../_static/translations.js"></script>
<script src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="Python 3.11.5 belgelendirmesi içinde ara"
href="../_static/opensearch.xml"/>
<link rel="author" title="Bu belgeler hakkında" href="../about.html" />
<link rel="index" title="Dizin" href="../genindex.html" />
<link rel="search" title="Ara" href="../search.html" />
<link rel="copyright" title="Telif Hakkı" href="../copyright.html" />
<link rel="next" title="What’s New in Python 2.4" href="2.4.html" />
<link rel="prev" title="What’s New in Python 2.6" href="2.6.html" />
<link rel="canonical" href="https://docs.python.org/3/whatsnew/2.5.html" />
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
<link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/menu.js"></script>
<script type="text/javascript" src="../_static/search-focus.js"></script>
<script type="text/javascript" src="../_static/themetoggle.js"></script>
</head>
<body>
<div class="mobile-nav">
<input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
<nav class="nav-content" role="navigation">
<label for="menuToggler" class="toggler__label">
<span></span>
</label>
<span class="nav-items-wrapper">
<a href="https://www.python.org/" class="nav-logo">
<img src="../_static/py.svg" alt="Logo"/>
</a>
<span class="version_switcher_placeholder"></span>
<form role="search" class="search" action="../search.html" method="get">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
<path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>
</svg>
<input placeholder="Hızlı Arama" aria-label="Hızlı Arama" type="search" name="q" />
<input type="submit" value="Git"/>
</form>
</span>
</nav>
<div class="menu-wrapper">
<nav class="menu" role="navigation" aria-label="main navigation">
<div class="language_switcher_placeholder"></div>
<label class="theme-selector-label">
Theme
<select class="theme-selector" oninput="activateTheme(this.value)">
<option value="auto" selected>Auto</option>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
</label>
<div>
<h3><a href="../contents.html">İçindekiler</a></h3>
<ul>
<li><a class="reference internal" href="#">What’s New in Python 2.5</a><ul>
<li><a class="reference internal" href="#pep-308-conditional-expressions">PEP 308: Conditional Expressions</a></li>
<li><a class="reference internal" href="#pep-309-partial-function-application">PEP 309: Partial Function Application</a></li>
<li><a class="reference internal" href="#pep-314-metadata-for-python-software-packages-v1-1">PEP 314: Metadata for Python Software Packages v1.1</a></li>
<li><a class="reference internal" href="#pep-328-absolute-and-relative-imports">PEP 328: Absolute and Relative Imports</a></li>
<li><a class="reference internal" href="#pep-338-executing-modules-as-scripts">PEP 338: Executing Modules as Scripts</a></li>
<li><a class="reference internal" href="#pep-341-unified-try-except-finally">PEP 341: Unified try/except/finally</a></li>
<li><a class="reference internal" href="#pep-342-new-generator-features">PEP 342: New Generator Features</a></li>
<li><a class="reference internal" href="#pep-343-the-with-statement">PEP 343: The ‘with’ statement</a><ul>
<li><a class="reference internal" href="#writing-context-managers">Writing Context Managers</a></li>
<li><a class="reference internal" href="#the-contextlib-module">The contextlib module</a></li>
</ul>
</li>
<li><a class="reference internal" href="#pep-352-exceptions-as-new-style-classes">PEP 352: Exceptions as New-Style Classes</a></li>
<li><a class="reference internal" href="#pep-353-using-ssize-t-as-the-index-type">PEP 353: Using ssize_t as the index type</a></li>
<li><a class="reference internal" href="#pep-357-the-index-method">PEP 357: The ‘__index__’ method</a></li>
<li><a class="reference internal" href="#other-language-changes">Other Language Changes</a><ul>
<li><a class="reference internal" href="#interactive-interpreter-changes">Interactive Interpreter Changes</a></li>
<li><a class="reference internal" href="#optimizations">Optimizations</a></li>
</ul>
</li>
<li><a class="reference internal" href="#new-improved-and-removed-modules">New, Improved, and Removed Modules</a><ul>
<li><a class="reference internal" href="#the-ctypes-package">The ctypes package</a></li>
<li><a class="reference internal" href="#the-elementtree-package">The ElementTree package</a></li>
<li><a class="reference internal" href="#the-hashlib-package">The hashlib package</a></li>
<li><a class="reference internal" href="#the-sqlite3-package">The sqlite3 package</a></li>
<li><a class="reference internal" href="#the-wsgiref-package">The wsgiref package</a></li>
</ul>
</li>
<li><a class="reference internal" href="#build-and-c-api-changes">Build and C API Changes</a><ul>
<li><a class="reference internal" href="#port-specific-changes">Port-Specific Changes</a></li>
</ul>
</li>
<li><a class="reference internal" href="#porting-to-python-2-5">Porting to Python 2.5</a></li>
<li><a class="reference internal" href="#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
</ul>
</div>
<div>
<h4>Önceki konu</h4>
<p class="topless"><a href="2.6.html"
title="önceki bölüm">What’s New in Python 2.6</a></p>
</div>
<div>
<h4>Sonraki konu</h4>
<p class="topless"><a href="2.4.html"
title="sonraki bölüm">What’s New in Python 2.4</a></p>
</div>
<div role="note" aria-label="source link">
<h3>Bu Sayfa</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">Hata Bildir</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.11/Doc/whatsnew/2.5.rst"
rel="nofollow">Kaynağı Göster
</a>
</li>
</ul>
</div>
</nav>
</div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Gezinti</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="Genel Endeks"
accesskey="I">dizin</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python Modül Dizini"
>modülleri</a> |</li>
<li class="right" >
<a href="2.4.html" title="What’s New in Python 2.4"
accesskey="N">sonraki</a> |</li>
<li class="right" >
<a href="2.6.html" title="What’s New in Python 2.6"
accesskey="P">önceki</a> |</li>
<li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> »</li>
<li class="switchers">
<div class="language_switcher_placeholder"></div>
<div class="version_switcher_placeholder"></div>
</li>
<li>
</li>
<li id="cpython-language-and-version">
<a href="../index.html">3.11.5 Documentation</a> »
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">What’s New in Python</a> »</li>
<li class="nav-item nav-item-this"><a href="">What’s New in Python 2.5</a></li>
<li class="right">
<div class="inline-search" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Hızlı Arama" aria-label="Hızlı Arama" type="search" name="q" id="search-box" />
<input type="submit" value="Git" />
</form>
</div>
|
</li>
<li class="right">
<label class="theme-selector-label">
Theme
<select class="theme-selector" oninput="activateTheme(this.value)">
<option value="auto" selected>Auto</option>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
</label> |</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<section id="what-s-new-in-python-2-5">
<h1>What’s New in Python 2.5<a class="headerlink" href="#what-s-new-in-python-2-5" title="Permalink to this heading">¶</a></h1>
<dl class="field-list simple">
<dt class="field-odd">Author<span class="colon">:</span></dt>
<dd class="field-odd"><p>A.M. Kuchling</p>
</dd>
</dl>
<p>This article explains the new features in Python 2.5. The final release of
Python 2.5 is scheduled for August 2006; <span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0356/"><strong>PEP 356</strong></a> describes the planned
release schedule. Python 2.5 was released on September 19, 2006.</p>
<p>The changes in Python 2.5 are an interesting mix of language and library
improvements. The library enhancements will be more important to Python’s user
community, I think, because several widely useful packages were added. New
modules include ElementTree for XML processing (<code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree</span></code>),
the SQLite database module (<code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite</span></code>), and the <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a>
module for calling C functions.</p>
<p>The language changes are of middling significance. Some pleasant new features
were added, but most of them aren’t features that you’ll use every day.
Conditional expressions were finally added to the language using a novel syntax;
see section <a class="reference internal" href="#pep-308"><span class="std std-ref">PEP 308: Conditional Expressions</span></a>. The new ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement will make
writing cleanup code easier (section <a class="reference internal" href="#pep-343"><span class="std std-ref">PEP 343: The ‘with’ statement</span></a>). Values can now be passed
into generators (section <a class="reference internal" href="#pep-342"><span class="std std-ref">PEP 342: New Generator Features</span></a>). Imports are now visible as either
absolute or relative (section <a class="reference internal" href="#pep-328"><span class="std std-ref">PEP 328: Absolute and Relative Imports</span></a>). Some corner cases of exception
handling are handled better (section <a class="reference internal" href="#pep-341"><span class="std std-ref">PEP 341: Unified try/except/finally</span></a>). All these improvements
are worthwhile, but they’re improvements to one specific language feature or
another; none of them are broad modifications to Python’s semantics.</p>
<p>As well as the language and library additions, other improvements and bugfixes
were made throughout the source tree. A search through the SVN change logs
finds there were 353 patches applied and 458 bugs fixed between Python 2.4 and
2.5. (Both figures are likely to be underestimates.)</p>
<p>This article doesn’t try to be a complete specification of the new features;
instead changes are briefly introduced using helpful examples. For full
details, you should always refer to the documentation for Python 2.5 at
<a class="reference external" href="https://docs.python.org">https://docs.python.org</a>. If you want to understand the complete implementation
and design rationale, refer to the PEP for a particular new feature.</p>
<p>Comments, suggestions, and error reports for this document are welcome; please
e-mail them to the author or open a bug in the Python bug tracker.</p>
<section id="pep-308-conditional-expressions">
<span id="pep-308"></span><h2>PEP 308: Conditional Expressions<a class="headerlink" href="#pep-308-conditional-expressions" title="Permalink to this heading">¶</a></h2>
<p>For a long time, people have been requesting a way to write conditional
expressions, which are expressions that return value A or value B depending on
whether a Boolean value is true or false. A conditional expression lets you
write a single assignment statement that has the same effect as the following:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">condition</span><span class="p">:</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">true_value</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">false_value</span>
</pre></div>
</div>
<p>There have been endless tedious discussions of syntax on both python-dev and
comp.lang.python. A vote was even held that found the majority of voters wanted
conditional expressions in some form, but there was no syntax that was preferred
by a clear majority. Candidates included C’s <code class="docutils literal notranslate"><span class="pre">cond</span> <span class="pre">?</span> <span class="pre">true_v</span> <span class="pre">:</span> <span class="pre">false_v</span></code>, <code class="docutils literal notranslate"><span class="pre">if</span>
<span class="pre">cond</span> <span class="pre">then</span> <span class="pre">true_v</span> <span class="pre">else</span> <span class="pre">false_v</span></code>, and 16 other variations.</p>
<p>Guido van Rossum eventually chose a surprising syntax:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="n">true_value</span> <span class="k">if</span> <span class="n">condition</span> <span class="k">else</span> <span class="n">false_value</span>
</pre></div>
</div>
<p>Evaluation is still lazy as in existing Boolean expressions, so the order of
evaluation jumps around a bit. The <em>condition</em> expression in the middle is
evaluated first, and the <em>true_value</em> expression is evaluated only if the
condition was true. Similarly, the <em>false_value</em> expression is only evaluated
when the condition is false.</p>
<p>This syntax may seem strange and backwards; why does the condition go in the
<em>middle</em> of the expression, and not in the front as in C’s <code class="docutils literal notranslate"><span class="pre">c</span> <span class="pre">?</span> <span class="pre">x</span> <span class="pre">:</span> <span class="pre">y</span></code>? The
decision was checked by applying the new syntax to the modules in the standard
library and seeing how the resulting code read. In many cases where a
conditional expression is used, one value seems to be the ‘common case’ and one
value is an ‘exceptional case’, used only on rarer occasions when the condition
isn’t met. The conditional syntax makes this pattern a bit more obvious:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">contents</span> <span class="o">=</span> <span class="p">((</span><span class="n">doc</span> <span class="o">+</span> <span class="s1">'</span><span class="se">\n</span><span class="s1">'</span><span class="p">)</span> <span class="k">if</span> <span class="n">doc</span> <span class="k">else</span> <span class="s1">''</span><span class="p">)</span>
</pre></div>
</div>
<p>I read the above statement as meaning “here <em>contents</em> is usually assigned a
value of <code class="docutils literal notranslate"><span class="pre">doc+'\n'</span></code>; sometimes <em>doc</em> is empty, in which special case an empty
string is returned.” I doubt I will use conditional expressions very often
where there isn’t a clear common and uncommon case.</p>
<p>There was some discussion of whether the language should require surrounding
conditional expressions with parentheses. The decision was made to <em>not</em>
require parentheses in the Python language’s grammar, but as a matter of style I
think you should always use them. Consider these two statements:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># First version -- no parens</span>
<span class="n">level</span> <span class="o">=</span> <span class="mi">1</span> <span class="k">if</span> <span class="n">logging</span> <span class="k">else</span> <span class="mi">0</span>
<span class="c1"># Second version -- with parens</span>
<span class="n">level</span> <span class="o">=</span> <span class="p">(</span><span class="mi">1</span> <span class="k">if</span> <span class="n">logging</span> <span class="k">else</span> <span class="mi">0</span><span class="p">)</span>
</pre></div>
</div>
<p>In the first version, I think a reader’s eye might group the statement into
‘level = 1’, ‘if logging’, ‘else 0’, and think that the condition decides
whether the assignment to <em>level</em> is performed. The second version reads
better, in my opinion, because it makes it clear that the assignment is always
performed and the choice is being made between two values.</p>
<p>Another reason for including the brackets: a few odd combinations of list
comprehensions and lambdas could look like incorrect conditional expressions.
See <span class="target" id="index-1"></span><a class="pep reference external" href="https://peps.python.org/pep-0308/"><strong>PEP 308</strong></a> for some examples. If you put parentheses around your
conditional expressions, you won’t run into this case.</p>
<div class="admonition seealso">
<p class="admonition-title">Ayrıca bakınız</p>
<dl class="simple">
<dt><span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-0308/"><strong>PEP 308</strong></a> - Conditional Expressions</dt><dd><p>PEP written by Guido van Rossum and Raymond D. Hettinger; implemented by Thomas
Wouters.</p>
</dd>
</dl>
</div>
</section>
<section id="pep-309-partial-function-application">
<span id="pep-309"></span><h2>PEP 309: Partial Function Application<a class="headerlink" href="#pep-309-partial-function-application" title="Permalink to this heading">¶</a></h2>
<p>The <a class="reference internal" href="../library/functools.html#module-functools" title="functools: Higher-order functions and operations on callable objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">functools</span></code></a> module is intended to contain tools for functional-style
programming.</p>
<p>One useful tool in this module is the <code class="xref py py-func docutils literal notranslate"><span class="pre">partial()</span></code> function. For programs
written in a functional style, you’ll sometimes want to construct variants of
existing functions that have some of the parameters filled in. Consider a
Python function <code class="docutils literal notranslate"><span class="pre">f(a,</span> <span class="pre">b,</span> <span class="pre">c)</span></code>; you could create a new function <code class="docutils literal notranslate"><span class="pre">g(b,</span> <span class="pre">c)</span></code> that
was equivalent to <code class="docutils literal notranslate"><span class="pre">f(1,</span> <span class="pre">b,</span> <span class="pre">c)</span></code>. This is called “partial function
application”.</p>
<p><code class="xref py py-func docutils literal notranslate"><span class="pre">partial()</span></code> takes the arguments <code class="docutils literal notranslate"><span class="pre">(function,</span> <span class="pre">arg1,</span> <span class="pre">arg2,</span> <span class="pre">...</span> <span class="pre">kwarg1=value1,</span>
<span class="pre">kwarg2=value2)</span></code>. The resulting object is callable, so you can just call it to
invoke <em>function</em> with the filled-in arguments.</p>
<p>Here’s a small but realistic example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">functools</span>
<span class="k">def</span> <span class="nf">log</span> <span class="p">(</span><span class="n">message</span><span class="p">,</span> <span class="n">subsystem</span><span class="p">):</span>
<span class="s2">"Write the contents of 'message' to the specified subsystem."</span>
<span class="nb">print</span> <span class="s1">'</span><span class="si">%s</span><span class="s1">: </span><span class="si">%s</span><span class="s1">'</span> <span class="o">%</span> <span class="p">(</span><span class="n">subsystem</span><span class="p">,</span> <span class="n">message</span><span class="p">)</span>
<span class="o">...</span>
<span class="n">server_log</span> <span class="o">=</span> <span class="n">functools</span><span class="o">.</span><span class="n">partial</span><span class="p">(</span><span class="n">log</span><span class="p">,</span> <span class="n">subsystem</span><span class="o">=</span><span class="s1">'server'</span><span class="p">)</span>
<span class="n">server_log</span><span class="p">(</span><span class="s1">'Unable to open socket'</span><span class="p">)</span>
</pre></div>
</div>
<p>Here’s another example, from a program that uses PyGTK. Here a context-sensitive
pop-up menu is being constructed dynamically. The callback provided
for the menu option is a partially applied version of the <code class="xref py py-meth docutils literal notranslate"><span class="pre">open_item()</span></code>
method, where the first argument has been provided.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="o">...</span>
<span class="k">class</span> <span class="nc">Application</span><span class="p">:</span>
<span class="k">def</span> <span class="nf">open_item</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">path</span><span class="p">):</span>
<span class="o">...</span>
<span class="k">def</span> <span class="nf">init</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="n">open_func</span> <span class="o">=</span> <span class="n">functools</span><span class="o">.</span><span class="n">partial</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">open_item</span><span class="p">,</span> <span class="n">item_path</span><span class="p">)</span>
<span class="n">popup_menu</span><span class="o">.</span><span class="n">append</span><span class="p">(</span> <span class="p">(</span><span class="s2">"Open"</span><span class="p">,</span> <span class="n">open_func</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span> <span class="p">)</span>
</pre></div>
</div>
<p>Another function in the <a class="reference internal" href="../library/functools.html#module-functools" title="functools: Higher-order functions and operations on callable objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">functools</span></code></a> module is the
<code class="docutils literal notranslate"><span class="pre">update_wrapper(wrapper,</span> <span class="pre">wrapped)</span></code> function that helps you write
well-behaved decorators. <code class="xref py py-func docutils literal notranslate"><span class="pre">update_wrapper()</span></code> copies the name, module, and
docstring attribute to a wrapper function so that tracebacks inside the wrapped
function are easier to understand. For example, you might write:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">my_decorator</span><span class="p">(</span><span class="n">f</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">wrapper</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">):</span>
<span class="nb">print</span> <span class="s1">'Calling decorated function'</span>
<span class="k">return</span> <span class="n">f</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">)</span>
<span class="n">functools</span><span class="o">.</span><span class="n">update_wrapper</span><span class="p">(</span><span class="n">wrapper</span><span class="p">,</span> <span class="n">f</span><span class="p">)</span>
<span class="k">return</span> <span class="n">wrapper</span>
</pre></div>
</div>
<p><code class="xref py py-func docutils literal notranslate"><span class="pre">wraps()</span></code> is a decorator that can be used inside your own decorators to copy
the wrapped function’s information. An alternate version of the previous
example would be:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">my_decorator</span><span class="p">(</span><span class="n">f</span><span class="p">):</span>
<span class="nd">@functools</span><span class="o">.</span><span class="n">wraps</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">wrapper</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">):</span>
<span class="nb">print</span> <span class="s1">'Calling decorated function'</span>
<span class="k">return</span> <span class="n">f</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">)</span>
<span class="k">return</span> <span class="n">wrapper</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="admonition-title">Ayrıca bakınız</p>
<dl class="simple">
<dt><span class="target" id="index-3"></span><a class="pep reference external" href="https://peps.python.org/pep-0309/"><strong>PEP 309</strong></a> - Partial Function Application</dt><dd><p>PEP proposed and written by Peter Harris; implemented by Hye-Shik Chang and Nick
Coghlan, with adaptations by Raymond Hettinger.</p>
</dd>
</dl>
</div>
</section>
<section id="pep-314-metadata-for-python-software-packages-v1-1">
<span id="pep-314"></span><h2>PEP 314: Metadata for Python Software Packages v1.1<a class="headerlink" href="#pep-314-metadata-for-python-software-packages-v1-1" title="Permalink to this heading">¶</a></h2>
<p>Some simple dependency support was added to Distutils. The <code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code>
function now has <code class="docutils literal notranslate"><span class="pre">requires</span></code>, <code class="docutils literal notranslate"><span class="pre">provides</span></code>, and <code class="docutils literal notranslate"><span class="pre">obsoletes</span></code> keyword
parameters. When you build a source distribution using the <code class="docutils literal notranslate"><span class="pre">sdist</span></code> command,
the dependency information will be recorded in the <code class="file docutils literal notranslate"><span class="pre">PKG-INFO</span></code> file.</p>
<p>Another new keyword parameter is <code class="docutils literal notranslate"><span class="pre">download_url</span></code>, which should be set to a URL
for the package’s source code. This means it’s now possible to look up an entry
in the package index, determine the dependencies for a package, and download the
required packages.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">VERSION</span> <span class="o">=</span> <span class="s1">'1.0'</span>
<span class="n">setup</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">'PyPackage'</span><span class="p">,</span>
<span class="n">version</span><span class="o">=</span><span class="n">VERSION</span><span class="p">,</span>
<span class="n">requires</span><span class="o">=</span><span class="p">[</span><span class="s1">'numarray'</span><span class="p">,</span> <span class="s1">'zlib (>=1.1.4)'</span><span class="p">],</span>
<span class="n">obsoletes</span><span class="o">=</span><span class="p">[</span><span class="s1">'OldPackage'</span><span class="p">]</span>
<span class="n">download_url</span><span class="o">=</span><span class="p">(</span><span class="s1">'http://www.example.com/pypackage/dist/pkg-</span><span class="si">%s</span><span class="s1">.tar.gz'</span>
<span class="o">%</span> <span class="n">VERSION</span><span class="p">),</span>
<span class="p">)</span>
</pre></div>
</div>
<p>Another new enhancement to the Python package index at
<a class="reference external" href="https://pypi.org">https://pypi.org</a> is storing source and binary archives for a
package. The new <strong class="command">upload</strong> Distutils command will upload a package to
the repository.</p>
<p>Before a package can be uploaded, you must be able to build a distribution using
the <strong class="command">sdist</strong> Distutils command. Once that works, you can run <code class="docutils literal notranslate"><span class="pre">python</span>
<span class="pre">setup.py</span> <span class="pre">upload</span></code> to add your package to the PyPI archive. Optionally you can
GPG-sign the package by supplying the <code class="xref std std-option docutils literal notranslate"><span class="pre">--sign</span></code> and <code class="xref std std-option docutils literal notranslate"><span class="pre">--identity</span></code>
options.</p>
<p>Package uploading was implemented by Martin von Löwis and Richard Jones.</p>
<div class="admonition seealso">
<p class="admonition-title">Ayrıca bakınız</p>
<dl class="simple">
<dt><span class="target" id="index-4"></span><a class="pep reference external" href="https://peps.python.org/pep-0314/"><strong>PEP 314</strong></a> - Metadata for Python Software Packages v1.1</dt><dd><p>PEP proposed and written by A.M. Kuchling, Richard Jones, and Fred Drake;
implemented by Richard Jones and Fred Drake.</p>
</dd>
</dl>
</div>
</section>
<section id="pep-328-absolute-and-relative-imports">
<span id="pep-328"></span><h2>PEP 328: Absolute and Relative Imports<a class="headerlink" href="#pep-328-absolute-and-relative-imports" title="Permalink to this heading">¶</a></h2>
<p>The simpler part of <span class="target" id="index-5"></span><a class="pep reference external" href="https://peps.python.org/pep-0328/"><strong>PEP 328</strong></a> was implemented in Python 2.4: parentheses could now
be used to enclose the names imported from a module using the <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">...</span> <span class="pre">import</span>
<span class="pre">...</span></code> statement, making it easier to import many different names.</p>
<p>The more complicated part has been implemented in Python 2.5: importing a module
can be specified to use absolute or package-relative imports. The plan is to
move toward making absolute imports the default in future versions of Python.</p>
<p>Let’s say you have a package directory like this:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">pkg</span><span class="o">/</span>
<span class="n">pkg</span><span class="o">/</span><span class="fm">__init__</span><span class="o">.</span><span class="n">py</span>
<span class="n">pkg</span><span class="o">/</span><span class="n">main</span><span class="o">.</span><span class="n">py</span>
<span class="n">pkg</span><span class="o">/</span><span class="n">string</span><span class="o">.</span><span class="n">py</span>
</pre></div>
</div>
<p>This defines a package named <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg</span></code> containing the <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.main</span></code> and
<code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.string</span></code> submodules.</p>
<p>Consider the code in the <code class="file docutils literal notranslate"><span class="pre">main.py</span></code> module. What happens if it executes
the statement <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">string</span></code>? In Python 2.4 and earlier, it will first look
in the package’s directory to perform a relative import, finds
<code class="file docutils literal notranslate"><span class="pre">pkg/string.py</span></code>, imports the contents of that file as the
<code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.string</span></code> module, and that module is bound to the name <code class="docutils literal notranslate"><span class="pre">string</span></code> in the
<code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.main</span></code> module’s namespace.</p>
<p>That’s fine if <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.string</span></code> was what you wanted. But what if you wanted
Python’s standard <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module? There’s no clean way to ignore
<code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.string</span></code> and look for the standard module; generally you had to look at
the contents of <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code>, which is slightly unclean. Holger Krekel’s
<code class="xref py py-mod docutils literal notranslate"><span class="pre">py.std</span></code> package provides a tidier way to perform imports from the standard
library, <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">py;</span> <span class="pre">py.std.string.join()</span></code>, but that package isn’t available
on all Python installations.</p>
<p>Reading code which relies on relative imports is also less clear, because a
reader may be confused about which module, <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> or <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.string</span></code>,
is intended to be used. Python users soon learned not to duplicate the names of
standard library modules in the names of their packages’ submodules, but you
can’t protect against having your submodule’s name being used for a new module
added in a future version of Python.</p>
<p>In Python 2.5, you can switch <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a>’s behaviour to absolute imports
using a <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">absolute_import</span></code> directive. This absolute-import
behaviour will become the default in a future version (probably Python
2.7). Once absolute imports are the default, <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">string</span></code> will always
find the standard library’s version. It’s suggested that users should begin
using absolute imports as much as possible, so it’s preferable to begin writing
<code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">pkg</span> <span class="pre">import</span> <span class="pre">string</span></code> in your code.</p>
<p>Relative imports are still possible by adding a leading period to the module
name when using the <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">...</span> <span class="pre">import</span></code> form:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Import names from pkg.string</span>
<span class="kn">from</span> <span class="nn">.string</span> <span class="kn">import</span> <span class="n">name1</span><span class="p">,</span> <span class="n">name2</span>
<span class="c1"># Import pkg.string</span>
<span class="kn">from</span> <span class="nn">.</span> <span class="kn">import</span> <span class="n">string</span>
</pre></div>
</div>
<p>This imports the <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module relative to the current package, so in
<code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.main</span></code> this will import <em>name1</em> and <em>name2</em> from <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.string</span></code>.
Additional leading periods perform the relative import starting from the parent
of the current package. For example, code in the <code class="xref py py-mod docutils literal notranslate"><span class="pre">A.B.C</span></code> module can do:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">.</span> <span class="kn">import</span> <span class="n">D</span> <span class="c1"># Imports A.B.D</span>
<span class="kn">from</span> <span class="nn">..</span> <span class="kn">import</span> <span class="n">E</span> <span class="c1"># Imports A.E</span>
<span class="kn">from</span> <span class="nn">..F</span> <span class="kn">import</span> <span class="n">G</span> <span class="c1"># Imports A.F.G</span>
</pre></div>
</div>
<p>Leading periods cannot be used with the <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">modname</span></code> form of the import
statement, only the <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">...</span> <span class="pre">import</span></code> form.</p>
<div class="admonition seealso">
<p class="admonition-title">Ayrıca bakınız</p>
<dl class="simple">
<dt><span class="target" id="index-6"></span><a class="pep reference external" href="https://peps.python.org/pep-0328/"><strong>PEP 328</strong></a> - Imports: Multi-Line and Absolute/Relative</dt><dd><p>PEP written by Aahz; implemented by Thomas Wouters.</p>
</dd>
<dt><a class="reference external" href="https://pylib.readthedocs.io/">https://pylib.readthedocs.io/</a></dt><dd><p>The py library by Holger Krekel, which contains the <code class="xref py py-mod docutils literal notranslate"><span class="pre">py.std</span></code> package.</p>
</dd>
</dl>
</div>
</section>
<section id="pep-338-executing-modules-as-scripts">
<span id="pep-338"></span><h2>PEP 338: Executing Modules as Scripts<a class="headerlink" href="#pep-338-executing-modules-as-scripts" title="Permalink to this heading">¶</a></h2>
<p>The <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a> switch added in Python 2.4 to execute a module as a script
gained a few more abilities. Instead of being implemented in C code inside the
Python interpreter, the switch now uses an implementation in a new module,
<a class="reference internal" href="../library/runpy.html#module-runpy" title="runpy: Locate and run Python modules without importing them first."><code class="xref py py-mod docutils literal notranslate"><span class="pre">runpy</span></code></a>.</p>
<p>The <a class="reference internal" href="../library/runpy.html#module-runpy" title="runpy: Locate and run Python modules without importing them first."><code class="xref py py-mod docutils literal notranslate"><span class="pre">runpy</span></code></a> module implements a more sophisticated import mechanism so that
it’s now possible to run modules in a package such as <code class="xref py py-mod docutils literal notranslate"><span class="pre">pychecker.checker</span></code>.
The module also supports alternative import mechanisms such as the
<a class="reference internal" href="../library/zipimport.html#module-zipimport" title="zipimport: Support for importing Python modules from ZIP archives."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipimport</span></code></a> module. This means you can add a .zip archive’s path to
<code class="docutils literal notranslate"><span class="pre">sys.path</span></code> and then use the <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a> switch to execute code from the
archive.</p>
<div class="admonition seealso">
<p class="admonition-title">Ayrıca bakınız</p>
<dl class="simple">
<dt><span class="target" id="index-7"></span><a class="pep reference external" href="https://peps.python.org/pep-0338/"><strong>PEP 338</strong></a> - Executing modules as scripts</dt><dd><p>PEP written and implemented by Nick Coghlan.</p>
</dd>
</dl>
</div>
</section>
<section id="pep-341-unified-try-except-finally">
<span id="pep-341"></span><h2>PEP 341: Unified try/except/finally<a class="headerlink" href="#pep-341-unified-try-except-finally" title="Permalink to this heading">¶</a></h2>
<p>Until Python 2.5, the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement came in two flavours. You could
use a <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> block to ensure that code is always executed, or one or
more <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> blocks to catch specific exceptions. You couldn’t
combine both <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> blocks and a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> block, because
generating the right bytecode for the combined version was complicated and it
wasn’t clear what the semantics of the combined statement should be.</p>
<p>Guido van Rossum spent some time working with Java, which does support the
equivalent of combining <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> blocks and a <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> block,
and this clarified what the statement should mean. In Python 2.5, you can now
write:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
<span class="n">block</span><span class="o">-</span><span class="mi">1</span> <span class="o">...</span>
<span class="k">except</span> <span class="n">Exception1</span><span class="p">:</span>
<span class="n">handler</span><span class="o">-</span><span class="mi">1</span> <span class="o">...</span>
<span class="k">except</span> <span class="n">Exception2</span><span class="p">:</span>
<span class="n">handler</span><span class="o">-</span><span class="mi">2</span> <span class="o">...</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">else</span><span class="o">-</span><span class="n">block</span>
<span class="k">finally</span><span class="p">:</span>
<span class="n">final</span><span class="o">-</span><span class="n">block</span>
</pre></div>
</div>
<p>The code in <em>block-1</em> is executed. If the code raises an exception, the various
<a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> blocks are tested: if the exception is of class
<code class="xref py py-class docutils literal notranslate"><span class="pre">Exception1</span></code>, <em>handler-1</em> is executed; otherwise if it’s of class
<code class="xref py py-class docutils literal notranslate"><span class="pre">Exception2</span></code>, <em>handler-2</em> is executed, and so forth. If no exception is
raised, the <em>else-block</em> is executed.</p>
<p>No matter what happened previously, the <em>final-block</em> is executed once the code
block is complete and any raised exceptions handled. Even if there’s an error in
an exception handler or the <em>else-block</em> and a new exception is raised, the code
in the <em>final-block</em> is still run.</p>
<div class="admonition seealso">
<p class="admonition-title">Ayrıca bakınız</p>
<dl class="simple">
<dt><span class="target" id="index-8"></span><a class="pep reference external" href="https://peps.python.org/pep-0341/"><strong>PEP 341</strong></a> - Unifying try-except and try-finally</dt><dd><p>PEP written by Georg Brandl; implementation by Thomas Lee.</p>
</dd>
</dl>
</div>
</section>
<section id="pep-342-new-generator-features">
<span id="pep-342"></span><h2>PEP 342: New Generator Features<a class="headerlink" href="#pep-342-new-generator-features" title="Permalink to this heading">¶</a></h2>
<p>Python 2.5 adds a simple way to pass values <em>into</em> a generator. As introduced in
Python 2.3, generators only produce output; once a generator’s code was invoked
to create an iterator, there was no way to pass any new information into the
function when its execution is resumed. Sometimes the ability to pass in some
information would be useful. Hackish solutions to this include making the
generator’s code look at a global variable and then changing the global
variable’s value, or passing in some mutable object that callers then modify.</p>
<p>To refresh your memory of basic generators, here’s a simple example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">counter</span> <span class="p">(</span><span class="n">maximum</span><span class="p">):</span>
<span class="n">i</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">while</span> <span class="n">i</span> <span class="o"><</span> <span class="n">maximum</span><span class="p">:</span>
<span class="k">yield</span> <span class="n">i</span>
<span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span>
</pre></div>
</div>
<p>When you call <code class="docutils literal notranslate"><span class="pre">counter(10)</span></code>, the result is an iterator that returns the values
from 0 up to 9. On encountering the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement, the iterator
returns the provided value and suspends the function’s execution, preserving the
local variables. Execution resumes on the following call to the iterator’s
<a class="reference internal" href="../library/functions.html#next" title="next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method, picking up after the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code> statement.</p>
<p>In Python 2.3, <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> was a statement; it didn’t return any value. In
2.5, <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code> is now an expression, returning a value that can be
assigned to a variable or otherwise operated on:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">val</span> <span class="o">=</span> <span class="p">(</span><span class="k">yield</span> <span class="n">i</span><span class="p">)</span>
</pre></div>
</div>
<p>I recommend that you always put parentheses around a <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> expression
when you’re doing something with the returned value, as in the above example.
The parentheses aren’t always necessary, but it’s easier to always add them
instead of having to remember when they’re needed.</p>
<p>(<span class="target" id="index-9"></span><a class="pep reference external" href="https://peps.python.org/pep-0342/"><strong>PEP 342</strong></a> explains the exact rules, which are that a
<a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a>-expression must always be parenthesized except when it
occurs at the top-level
expression on the right-hand side of an assignment. This means you can write
<code class="docutils literal notranslate"><span class="pre">val</span> <span class="pre">=</span> <span class="pre">yield</span> <span class="pre">i</span></code> but have to use parentheses when there’s an operation, as in
<code class="docutils literal notranslate"><span class="pre">val</span> <span class="pre">=</span> <span class="pre">(yield</span> <span class="pre">i)</span> <span class="pre">+</span> <span class="pre">12</span></code>.)</p>
<p>Values are sent into a generator by calling its <code class="docutils literal notranslate"><span class="pre">send(value)</span></code> method. The
generator’s code is then resumed and the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> expression returns the
specified <em>value</em>. If the regular <a class="reference internal" href="../library/functions.html#next" title="next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method is called, the
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code> returns <a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p>
<p>Here’s the previous example, modified to allow changing the value of the
internal counter.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">counter</span> <span class="p">(</span><span class="n">maximum</span><span class="p">):</span>
<span class="n">i</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">while</span> <span class="n">i</span> <span class="o"><</span> <span class="n">maximum</span><span class="p">:</span>
<span class="n">val</span> <span class="o">=</span> <span class="p">(</span><span class="k">yield</span> <span class="n">i</span><span class="p">)</span>
<span class="c1"># If value provided, change counter</span>
<span class="k">if</span> <span class="n">val</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">i</span> <span class="o">=</span> <span class="n">val</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span>
</pre></div>
</div>
<p>And here’s an example of changing the counter:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">it</span> <span class="o">=</span> <span class="n">counter</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="gp">>>> </span><span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">0</span>
<span class="gp">>>> </span><span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">1</span>
<span class="gp">>>> </span><span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="mi">8</span><span class="p">)</span>
<span class="go">8</span>
<span class="gp">>>> </span><span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">9</span>
<span class="gp">>>> </span><span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">"t.py"</span>, line <span class="m">15</span>, in <span class="n">?</span>
<span class="w"> </span><span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="gr">StopIteration</span>
</pre></div>
</div>
<p><a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> will usually return <a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, so you should always check
for this case. Don’t just use its value in expressions unless you’re sure that
the <code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code> method will be the only method used to resume your generator
function.</p>
<p>In addition to <code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code>, there are two other new methods on generators:</p>
<ul>
<li><p><code class="docutils literal notranslate"><span class="pre">throw(type,</span> <span class="pre">value=None,</span> <span class="pre">traceback=None)</span></code> is used to raise an exception
inside the generator; the exception is raised by the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> expression
where the generator’s execution is paused.</p></li>
<li><p><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> raises a new <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> exception inside the generator
to terminate the iteration. On receiving this exception, the generator’s code
must either raise <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> or <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>. Catching the
<a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> exception and returning a value is illegal and will trigger
a <a class="reference internal" href="../library/exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>; if the function raises some other exception, that
exception is propagated to the caller. <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> will also be called by
Python’s garbage collector when the generator is garbage-collected.</p>
<p>If you need to run cleanup code when a <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> occurs, I suggest
using a <code class="docutils literal notranslate"><span class="pre">try:</span> <span class="pre">...</span> <span class="pre">finally:</span></code> suite instead of catching <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a>.</p>
</li>
</ul>
<p>The cumulative effect of these changes is to turn generators from one-way
producers of information into both producers and consumers.</p>
<p>Generators also become <em>coroutines</em>, a more generalized form of subroutines.
Subroutines are entered at one point and exited at another point (the top of the
function, and a <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement), but coroutines can be entered,
exited, and resumed at many different points (the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statements).
We’ll have to figure out patterns for using coroutines effectively in Python.</p>
<p>The addition of the <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> method has one side effect that isn’t obvious.
<code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> is called when a generator is garbage-collected, so this means the
generator’s code gets one last chance to run before the generator is destroyed.
This last chance means that <code class="docutils literal notranslate"><span class="pre">try...finally</span></code> statements in generators can now
be guaranteed to work; the <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause will now always get a
chance to run. The syntactic restriction that you couldn’t mix <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a>
statements with a <code class="docutils literal notranslate"><span class="pre">try...finally</span></code> suite has therefore been removed. This
seems like a minor bit of language trivia, but using generators and
<code class="docutils literal notranslate"><span class="pre">try...finally</span></code> is actually necessary in order to implement the
<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement described by <span class="target" id="index-10"></span><a class="pep reference external" href="https://peps.python.org/pep-0343/"><strong>PEP 343</strong></a>. I’ll look at this new statement
in the following section.</p>
<p>Another even more esoteric effect of this change: previously, the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">gi_frame</span></code> attribute of a generator was always a frame object. It’s now
possible for <code class="xref py py-attr docutils literal notranslate"><span class="pre">gi_frame</span></code> to be <code class="docutils literal notranslate"><span class="pre">None</span></code> once the generator has been
exhausted.</p>
<div class="admonition seealso">
<p class="admonition-title">Ayrıca bakınız</p>
<dl>
<dt><span class="target" id="index-11"></span><a class="pep reference external" href="https://peps.python.org/pep-0342/"><strong>PEP 342</strong></a> - Coroutines via Enhanced Generators</dt><dd><p>PEP written by Guido van Rossum and Phillip J. Eby; implemented by Phillip J.
Eby. Includes examples of some fancier uses of generators as coroutines.</p>
<p>Earlier versions of these features were proposed in <span class="target" id="index-12"></span><a class="pep reference external" href="https://peps.python.org/pep-0288/"><strong>PEP 288</strong></a> by Raymond
Hettinger and <span class="target" id="index-13"></span><a class="pep reference external" href="https://peps.python.org/pep-0325/"><strong>PEP 325</strong></a> by Samuele Pedroni.</p>
</dd>
<dt><a class="reference external" href="https://en.wikipedia.org/wiki/Coroutine">https://en.wikipedia.org/wiki/Coroutine</a></dt><dd><p>The Wikipedia entry for coroutines.</p>
</dd>
<dt><a class="reference external" href="https://web.archive.org/web/20160321211320/http://www.sidhe.org/~dan/blog/archives/000178.html">https://web.archive.org/web/20160321211320/http://www.sidhe.org/~dan/blog/archives/000178.html</a></dt><dd><p>An explanation of coroutines from a Perl point of view, written by Dan Sugalski.</p>
</dd>
</dl>
</div>
</section>
<section id="pep-343-the-with-statement">
<span id="pep-343"></span><h2>PEP 343: The ‘with’ statement<a class="headerlink" href="#pep-343-the-with-statement" title="Permalink to this heading">¶</a></h2>
<p>The ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement clarifies code that previously would use
<code class="docutils literal notranslate"><span class="pre">try...finally</span></code> blocks to ensure that clean-up code is executed. In this
section, I’ll discuss the statement as it will commonly be used. In the next
section, I’ll examine the implementation details and show how to write objects
for use with this statement.</p>
<p>The ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement is a new control-flow structure whose basic
structure is:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">expression</span> <span class="p">[</span><span class="k">as</span> <span class="n">variable</span><span class="p">]:</span>
<span class="k">with</span><span class="o">-</span><span class="n">block</span>
</pre></div>
</div>
<p>The expression is evaluated, and it should result in an object that supports the
context management protocol (that is, has <code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code>
methods.</p>
<p>The object’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code> is called before <em>with-block</em> is executed and
therefore can run set-up code. It also may return a value that is bound to the
name <em>variable</em>, if given. (Note carefully that <em>variable</em> is <em>not</em> assigned
the result of <em>expression</em>.)</p>
<p>After execution of the <em>with-block</em> is finished, the object’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code>
method is called, even if the block raised an exception, and can therefore run
clean-up code.</p>
<p>To enable the statement in Python 2.5, you need to add the following directive
to your module:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">__future__</span> <span class="kn">import</span> <span class="n">with_statement</span>
</pre></div>
</div>
<p>The statement will always be enabled in Python 2.6.</p>
<p>Some standard Python objects now support the context management protocol and can
be used with the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement. File objects are one example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'/etc/passwd'</span><span class="p">,</span> <span class="s1">'r'</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
<span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
<span class="nb">print</span> <span class="n">line</span>
<span class="o">...</span> <span class="n">more</span> <span class="n">processing</span> <span class="n">code</span> <span class="o">...</span>
</pre></div>
</div>
<p>After this statement has executed, the file object in <em>f</em> will have been
automatically closed, even if the <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop raised an exception
part-way through the block.</p>
<div class="admonition note">
<p class="admonition-title">Not</p>
<p>In this case, <em>f</em> is the same object created by <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>, because
<code class="xref py py-meth docutils literal notranslate"><span class="pre">file.__enter__()</span></code> returns <em>self</em>.</p>
</div>
<p>The <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Thread-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module’s locks and condition variables also support the
‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">lock</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">Lock</span><span class="p">()</span>
<span class="k">with</span> <span class="n">lock</span><span class="p">:</span>
<span class="c1"># Critical section of code</span>
<span class="o">...</span>
</pre></div>
</div>
<p>The lock is acquired before the block is executed and always released once the
block is complete.</p>
<p>The new <code class="xref py py-func docutils literal notranslate"><span class="pre">localcontext()</span></code> function in the <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module makes it easy
to save and restore the current decimal context, which encapsulates the desired
precision and rounding characteristics for computations:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">decimal</span> <span class="kn">import</span> <span class="n">Decimal</span><span class="p">,</span> <span class="n">Context</span><span class="p">,</span> <span class="n">localcontext</span>
<span class="c1"># Displays with default precision of 28 digits</span>
<span class="n">v</span> <span class="o">=</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">'578'</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">v</span><span class="o">.</span><span class="n">sqrt</span><span class="p">()</span>
<span class="k">with</span> <span class="n">localcontext</span><span class="p">(</span><span class="n">Context</span><span class="p">(</span><span class="n">prec</span><span class="o">=</span><span class="mi">16</span><span class="p">)):</span>
<span class="c1"># All code in this block uses a precision of 16 digits.</span>
<span class="c1"># The original context is restored on exiting the block.</span>
<span class="nb">print</span> <span class="n">v</span><span class="o">.</span><span class="n">sqrt</span><span class="p">()</span>
</pre></div>
</div>
<section id="writing-context-managers">
<span id="new-25-context-managers"></span><h3>Writing Context Managers<a class="headerlink" href="#writing-context-managers" title="Permalink to this heading">¶</a></h3>
<p>Under the hood, the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement is fairly complicated. Most
people will only use ‘<code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code>’ in company with existing objects and
don’t need to know these details, so you can skip the rest of this section if
you like. Authors of new objects will need to understand the details of the
underlying implementation and should keep reading.</p>
<p>A high-level explanation of the context management protocol is:</p>
<ul class="simple">
<li><p>The expression is evaluated and should result in an object called a “context
manager”. The context manager must have <code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code>
methods.</p></li>
<li><p>The context manager’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code> method is called. The value returned
is assigned to <em>VAR</em>. If no <code class="docutils literal notranslate"><span class="pre">'as</span> <span class="pre">VAR'</span></code> clause is present, the value is simply
discarded.</p></li>
<li><p>The code in <em>BLOCK</em> is executed.</p></li>
<li><p>If <em>BLOCK</em> raises an exception, the <code class="docutils literal notranslate"><span class="pre">__exit__(type,</span> <span class="pre">value,</span> <span class="pre">traceback)</span></code>
is called with the exception details, the same values returned by
<a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>. The method’s return value controls whether the exception
is re-raised: any false value re-raises the exception, and <code class="docutils literal notranslate"><span class="pre">True</span></code> will result
in suppressing it. You’ll only rarely want to suppress the exception, because
if you do the author of the code containing the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement will
never realize anything went wrong.</p></li>
<li><p>If <em>BLOCK</em> didn’t raise an exception, the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code> method is still
called, but <em>type</em>, <em>value</em>, and <em>traceback</em> are all <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p></li>
</ul>
<p>Let’s think through an example. I won’t present detailed code but will only
sketch the methods necessary for a database that supports transactions.</p>
<p>(For people unfamiliar with database terminology: a set of changes to the
database are grouped into a transaction. Transactions can be either committed,
meaning that all the changes are written into the database, or rolled back,
meaning that the changes are all discarded and the database is unchanged. See
any database textbook for more information.)</p>
<p>Let’s assume there’s an object representing a database connection. Our goal will
be to let the user write code like this:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">db_connection</span> <span class="o">=</span> <span class="n">DatabaseConnection</span><span class="p">()</span>
<span class="k">with</span> <span class="n">db_connection</span> <span class="k">as</span> <span class="n">cursor</span><span class="p">:</span>
<span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">'insert into ...'</span><span class="p">)</span>
<span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">'delete from ...'</span><span class="p">)</span>
<span class="c1"># ... more operations ...</span>
</pre></div>
</div>
<p>The transaction should be committed if the code in the block runs flawlessly or
rolled back if there’s an exception. Here’s the basic interface for
<code class="xref py py-class docutils literal notranslate"><span class="pre">DatabaseConnection</span></code> that I’ll assume:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DatabaseConnection</span><span class="p">:</span>
<span class="c1"># Database interface</span>
<span class="k">def</span> <span class="nf">cursor</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="s2">"Returns a cursor object and starts a new transaction"</span>
<span class="k">def</span> <span class="nf">commit</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="s2">"Commits current transaction"</span>
<span class="k">def</span> <span class="nf">rollback</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="s2">"Rolls back current transaction"</span>
</pre></div>
</div>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code> method is pretty easy, having only to start a new
transaction. For this application the resulting cursor object would be a useful
result, so the method will return it. The user can then add <code class="docutils literal notranslate"><span class="pre">as</span> <span class="pre">cursor</span></code> to
their ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement to bind the cursor to a variable name.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DatabaseConnection</span><span class="p">:</span>
<span class="o">...</span>
<span class="k">def</span> <span class="fm">__enter__</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="c1"># Code to start a new transaction</span>
<span class="n">cursor</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="k">return</span> <span class="n">cursor</span>
</pre></div>
</div>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code> method is the most complicated because it’s where most of
the work has to be done. The method has to check if an exception occurred. If
there was no exception, the transaction is committed. The transaction is rolled
back if there was an exception.</p>
<p>In the code below, execution will just fall off the end of the function,
returning the default value of <code class="docutils literal notranslate"><span class="pre">None</span></code>. <code class="docutils literal notranslate"><span class="pre">None</span></code> is false, so the exception
will be re-raised automatically. If you wished, you could be more explicit and
add a <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement at the marked location.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DatabaseConnection</span><span class="p">:</span>
<span class="o">...</span>
<span class="k">def</span> <span class="fm">__exit__</span> <span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="nb">type</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">tb</span><span class="p">):</span>
<span class="k">if</span> <span class="n">tb</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="c1"># No exception, so commit</span>
<span class="bp">self</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
<span class="k">else</span><span class="p">:</span>
<span class="c1"># Exception occurred, so rollback.</span>
<span class="bp">self</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
<span class="c1"># return False</span>
</pre></div>
</div>
</section>
<section id="the-contextlib-module">
<span id="contextlibmod"></span><h3>The contextlib module<a class="headerlink" href="#the-contextlib-module" title="Permalink to this heading">¶</a></h3>
<p>The new <a class="reference internal" href="../library/contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code></a> module provides some functions and a decorator that
are useful for writing objects for use with the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement.</p>
<p>The decorator is called <code class="xref py py-func docutils literal notranslate"><span class="pre">contextmanager()</span></code>, and lets you write a single
generator function instead of defining a new class. The generator should yield
exactly one value. The code up to the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> will be executed as the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code> method, and the value yielded will be the method’s return
value that will get bound to the variable in the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement’s
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code> clause, if any. The code after the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> will be
executed in the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code> method. Any exception raised in the block will
be raised by the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code> statement.</p>
<p>Our database example from the previous section could be written using this
decorator as:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">contextmanager</span>
<span class="nd">@contextmanager</span>
<span class="k">def</span> <span class="nf">db_transaction</span> <span class="p">(</span><span class="n">connection</span><span class="p">):</span>
<span class="n">cursor</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="k">try</span><span class="p">:</span>
<span class="k">yield</span> <span class="n">cursor</span>
<span class="k">except</span><span class="p">:</span>
<span class="n">connection</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
<span class="k">raise</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">connection</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
<span class="n">db</span> <span class="o">=</span> <span class="n">DatabaseConnection</span><span class="p">()</span>
<span class="k">with</span> <span class="n">db_transaction</span><span class="p">(</span><span class="n">db</span><span class="p">)</span> <span class="k">as</span> <span class="n">cursor</span><span class="p">:</span>
<span class="o">...</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code></a> module also has a <code class="docutils literal notranslate"><span class="pre">nested(mgr1,</span> <span class="pre">mgr2,</span> <span class="pre">...)</span></code> function
that combines a number of context managers so you don’t need to write nested
‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statements. In this example, the single ‘<code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code>’
statement both starts a database transaction and acquires a thread lock:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">lock</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">Lock</span><span class="p">()</span>
<span class="k">with</span> <span class="n">nested</span> <span class="p">(</span><span class="n">db_transaction</span><span class="p">(</span><span class="n">db</span><span class="p">),</span> <span class="n">lock</span><span class="p">)</span> <span class="k">as</span> <span class="p">(</span><span class="n">cursor</span><span class="p">,</span> <span class="n">locked</span><span class="p">):</span>
<span class="o">...</span>
</pre></div>
</div>
<p>Finally, the <code class="docutils literal notranslate"><span class="pre">closing(object)</span></code> function returns <em>object</em> so that it can be
bound to a variable, and calls <code class="docutils literal notranslate"><span class="pre">object.close</span></code> at the end of the block.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">urllib</span><span class="o">,</span> <span class="nn">sys</span>
<span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">closing</span>
<span class="k">with</span> <span class="n">closing</span><span class="p">(</span><span class="n">urllib</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s1">'http://www.yahoo.com'</span><span class="p">))</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
<span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
<span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">line</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="admonition-title">Ayrıca bakınız</p>
<dl class="simple">
<dt><span class="target" id="index-14"></span><a class="pep reference external" href="https://peps.python.org/pep-0343/"><strong>PEP 343</strong></a> - The “with” statement</dt><dd><p>PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland,
Guido van Rossum, and Neal Norwitz. The PEP shows the code generated for a
‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement, which can be helpful in learning how the statement
works.</p>
</dd>
</dl>
<p>The documentation for the <a class="reference internal" href="../library/contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code></a> module.</p>
</div>
</section>
</section>
<section id="pep-352-exceptions-as-new-style-classes">
<span id="pep-352"></span><h2>PEP 352: Exceptions as New-Style Classes<a class="headerlink" href="#pep-352-exceptions-as-new-style-classes" title="Permalink to this heading">¶</a></h2>
<p>Exception classes can now be new-style classes, not just classic classes, and
the built-in <a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> class and all the standard built-in exceptions
(<a class="reference internal" href="../library/exceptions.html#NameError" title="NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a>, <a class="reference internal" href="../library/exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>, etc.) are now new-style classes.</p>
<p>The inheritance hierarchy for exceptions has been rearranged a bit. In 2.5, the
inheritance relationships are:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="ne">BaseException</span> <span class="c1"># New in Python 2.5</span>
<span class="o">|-</span> <span class="ne">KeyboardInterrupt</span>
<span class="o">|-</span> <span class="ne">SystemExit</span>
<span class="o">|-</span> <span class="ne">Exception</span>
<span class="o">|-</span> <span class="p">(</span><span class="nb">all</span> <span class="n">other</span> <span class="n">current</span> <span class="n">built</span><span class="o">-</span><span class="ow">in</span> <span class="n">exceptions</span><span class="p">)</span>
</pre></div>
</div>
<p>This rearrangement was done because people often want to catch all exceptions
that indicate program errors. <a class="reference internal" href="../library/exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> and <a class="reference internal" href="../library/exceptions.html#SystemExit" title="SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a>
aren’t errors, though, and usually represent an explicit action such as the user
hitting <kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">Control</kbd>-<kbd class="kbd docutils literal notranslate">C</kbd></kbd> or code calling <a class="reference internal" href="../library/sys.html#sys.exit" title="sys.exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exit()</span></code></a>. A bare <code class="docutils literal notranslate"><span class="pre">except:</span></code> will
catch all exceptions, so you commonly need to list <a class="reference internal" href="../library/exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> and
<a class="reference internal" href="../library/exceptions.html#SystemExit" title="SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a> in order to re-raise them. The usual pattern is:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
<span class="o">...</span>
<span class="k">except</span> <span class="p">(</span><span class="ne">KeyboardInterrupt</span><span class="p">,</span> <span class="ne">SystemExit</span><span class="p">):</span>
<span class="k">raise</span>
<span class="k">except</span><span class="p">:</span>
<span class="c1"># Log error...</span>
<span class="c1"># Continue running program...</span>
</pre></div>
</div>
<p>In Python 2.5, you can now write <code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">Exception</span></code> to achieve the same
result, catching all the exceptions that usually indicate errors but leaving
<a class="reference internal" href="../library/exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> and <a class="reference internal" href="../library/exceptions.html#SystemExit" title="SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a> alone. As in previous versions,
a bare <code class="docutils literal notranslate"><span class="pre">except:</span></code> still catches all exceptions.</p>
<p>The goal for Python 3.0 is to require any class raised as an exception to derive
from <a class="reference internal" href="../library/exceptions.html#BaseException" title="BaseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseException</span></code></a> or some descendant of <a class="reference internal" href="../library/exceptions.html#BaseException" title="BaseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseException</span></code></a>, and future
releases in the Python 2.x series may begin to enforce this constraint.
Therefore, I suggest you begin making all your exception classes derive from
<a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> now. It’s been suggested that the bare <code class="docutils literal notranslate"><span class="pre">except:</span></code> form should
be removed in Python 3.0, but Guido van Rossum hasn’t decided whether to do this
or not.</p>
<p>Raising of strings as exceptions, as in the statement <code class="docutils literal notranslate"><span class="pre">raise</span> <span class="pre">"Error</span>
<span class="pre">occurred"</span></code>, is deprecated in Python 2.5 and will trigger a warning. The aim is
to be able to remove the string-exception feature in a few releases.</p>
<div class="admonition seealso">
<p class="admonition-title">Ayrıca bakınız</p>
<dl class="simple">
<dt><span class="target" id="index-15"></span><a class="pep reference external" href="https://peps.python.org/pep-0352/"><strong>PEP 352</strong></a> - Required Superclass for Exceptions</dt><dd><p>PEP written by Brett Cannon and Guido van Rossum; implemented by Brett Cannon.</p>
</dd>
</dl>
</div>
</section>
<section id="pep-353-using-ssize-t-as-the-index-type">
<span id="pep-353"></span><h2>PEP 353: Using ssize_t as the index type<a class="headerlink" href="#pep-353-using-ssize-t-as-the-index-type" title="Permalink to this heading">¶</a></h2>
<p>A wide-ranging change to Python’s C API, using a new <a class="reference internal" href="../c-api/intro.html#c.Py_ssize_t" title="Py_ssize_t"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code></a> type
definition instead of <span class="c-expr sig sig-inline c"><span class="kt">int</span></span>, will permit the interpreter to handle more
data on 64-bit platforms. This change doesn’t affect Python’s capacity on 32-bit
platforms.</p>
<p>Various pieces of the Python interpreter used C’s <span class="c-expr sig sig-inline c"><span class="kt">int</span></span> type to store
sizes or counts; for example, the number of items in a list or tuple were stored
in an <span class="c-expr sig sig-inline c"><span class="kt">int</span></span>. The C compilers for most 64-bit platforms still define
<span class="c-expr sig sig-inline c"><span class="kt">int</span></span> as a 32-bit type, so that meant that lists could only hold up to
<code class="docutils literal notranslate"><span class="pre">2**31</span> <span class="pre">-</span> <span class="pre">1</span></code> = 2147483647 items. (There are actually a few different
programming models that 64-bit C compilers can use – see
<a class="reference external" href="https://unix.org/version2/whatsnew/lp64_wp.html">https://unix.org/version2/whatsnew/lp64_wp.html</a> for a discussion – but the
most commonly available model leaves <span class="c-expr sig sig-inline c"><span class="kt">int</span></span> as 32 bits.)</p>
<p>A limit of 2147483647 items doesn’t really matter on a 32-bit platform because
you’ll run out of memory before hitting the length limit. Each list item
requires space for a pointer, which is 4 bytes, plus space for a
<a class="reference internal" href="../c-api/structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> representing the item. 2147483647*4 is already more bytes
than a 32-bit address space can contain.</p>
<p>It’s possible to address that much memory on a 64-bit platform, however. The
pointers for a list that size would only require 16 GiB of space, so it’s not
unreasonable that Python programmers might construct lists that large.
Therefore, the Python interpreter had to be changed to use some type other than
<span class="c-expr sig sig-inline c"><span class="kt">int</span></span>, and this will be a 64-bit type on 64-bit platforms. The change