-
-
Notifications
You must be signed in to change notification settings - Fork 214
/
Copy pathexpressions.html
1902 lines (1848 loc) · 215 KB
/
expressions.html
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="zh-TW" data-content_root="../">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
<title>6. 運算式 — Python 3.13.2 說明文件</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />
<link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=23252803" />
<link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />
<script src="../_static/documentation_options.js?v=9a295789"></script>
<script src="../_static/doctools.js?v=9bcbadda"></script>
<script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="../_static/translations.js?v=cbf116e0"></script>
<script src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="在 Python 3.13.2 說明文件 中搜尋"
href="../_static/opensearch.xml"/>
<link rel="author" title="關於這些文件" href="../about.html" />
<link rel="index" title="索引" href="../genindex.html" />
<link rel="search" title="搜尋" href="../search.html" />
<link rel="copyright" title="版權" href="../copyright.html" />
<link rel="next" title="7. 簡單陳述式" href="simple_stmts.html" />
<link rel="prev" title="5. 模組引入系統" href="import.html" />
<link rel="canonical" href="https://docs.python.org/3/reference/expressions.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>
<script type="text/javascript" src="../_static/rtd_switcher.js"></script>
<meta name="readthedocs-addons-api-version" content="1">
</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="Python 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="快速搜尋" aria-label="快速搜尋" type="search" name="q" />
<input type="submit" value="前往"/>
</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">目錄</a></h3>
<ul>
<li><a class="reference internal" href="#">6. 運算式</a><ul>
<li><a class="reference internal" href="#arithmetic-conversions">6.1. Arithmetic conversions</a></li>
<li><a class="reference internal" href="#atoms">6.2. Atoms</a><ul>
<li><a class="reference internal" href="#atom-identifiers">6.2.1. Identifiers (Names)</a><ul>
<li><a class="reference internal" href="#index-5">6.2.1.1. Private name mangling</a></li>
</ul>
</li>
<li><a class="reference internal" href="#literals">6.2.2. Literals</a></li>
<li><a class="reference internal" href="#parenthesized-forms">6.2.3. Parenthesized forms</a></li>
<li><a class="reference internal" href="#displays-for-lists-sets-and-dictionaries">6.2.4. Displays for lists, sets and dictionaries</a></li>
<li><a class="reference internal" href="#list-displays">6.2.5. List displays</a></li>
<li><a class="reference internal" href="#set-displays">6.2.6. Set displays</a></li>
<li><a class="reference internal" href="#dictionary-displays">6.2.7. Dictionary displays</a></li>
<li><a class="reference internal" href="#generator-expressions">6.2.8. Generator expressions</a></li>
<li><a class="reference internal" href="#yield-expressions">6.2.9. Yield expressions</a><ul>
<li><a class="reference internal" href="#generator-iterator-methods">6.2.9.1. Generator-iterator methods</a></li>
<li><a class="reference internal" href="#examples">6.2.9.2. 模組</a></li>
<li><a class="reference internal" href="#asynchronous-generator-functions">6.2.9.3. 非同步產生器函式</a></li>
<li><a class="reference internal" href="#asynchronous-generator-iterator-methods">6.2.9.4. Asynchronous generator-iterator methods</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="reference internal" href="#primaries">6.3. Primaries</a><ul>
<li><a class="reference internal" href="#attribute-references">6.3.1. Attribute references</a></li>
<li><a class="reference internal" href="#subscriptions">6.3.2. Subscriptions</a></li>
<li><a class="reference internal" href="#slicings">6.3.3. Slicings</a></li>
<li><a class="reference internal" href="#calls">6.3.4. Calls</a></li>
</ul>
</li>
<li><a class="reference internal" href="#await-expression">6.4. Await expression</a></li>
<li><a class="reference internal" href="#the-power-operator">6.5. The power operator</a></li>
<li><a class="reference internal" href="#unary-arithmetic-and-bitwise-operations">6.6. Unary arithmetic and bitwise operations</a></li>
<li><a class="reference internal" href="#binary-arithmetic-operations">6.7. Binary arithmetic operations</a></li>
<li><a class="reference internal" href="#shifting-operations">6.8. Shifting operations</a></li>
<li><a class="reference internal" href="#binary-bitwise-operations">6.9. Binary bitwise operations</a></li>
<li><a class="reference internal" href="#comparisons">6.10. Comparisons</a><ul>
<li><a class="reference internal" href="#value-comparisons">6.10.1. Value comparisons</a></li>
<li><a class="reference internal" href="#membership-test-operations">6.10.2. Membership test operations</a></li>
<li><a class="reference internal" href="#is-not">6.10.3. Identity comparisons</a></li>
</ul>
</li>
<li><a class="reference internal" href="#boolean-operations">6.11. Boolean operations</a></li>
<li><a class="reference internal" href="#assignment-expressions">6.12. Assignment expressions</a></li>
<li><a class="reference internal" href="#conditional-expressions">6.13. Conditional expressions</a></li>
<li><a class="reference internal" href="#lambda">6.14. Lambdas</a></li>
<li><a class="reference internal" href="#expression-lists">6.15. Expression lists</a></li>
<li><a class="reference internal" href="#evaluation-order">6.16. Evaluation order</a></li>
<li><a class="reference internal" href="#operator-precedence">6.17. Operator precedence</a></li>
</ul>
</li>
</ul>
</div>
<div>
<h4>上個主題</h4>
<p class="topless"><a href="import.html"
title="上一章"><span class="section-number">5. </span>模組引入系統</a></p>
</div>
<div>
<h4>下個主題</h4>
<p class="topless"><a href="simple_stmts.html"
title="下一章"><span class="section-number">7. </span>簡單陳述式</a></p>
</div>
<div role="note" aria-label="source link">
<h3>此頁面</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">回報錯誤</a></li>
<li>
<a href="https://github.com/python/cpython/blob/main/Doc/reference/expressions.rst"
rel="nofollow">顯示原始碼
</a>
</li>
</ul>
</div>
</nav>
</div>
</div>
<div class="related" role="navigation" aria-label="Related">
<h3>瀏覽</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="總索引"
accesskey="I">索引</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python 模組索引"
>模組</a> |</li>
<li class="right" >
<a href="simple_stmts.html" title="7. 簡單陳述式"
accesskey="N">下一頁</a> |</li>
<li class="right" >
<a href="import.html" title="5. 模組引入系統"
accesskey="P">上一頁</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.13.2 Documentation</a> »
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python 語言參考手冊</a> »</li>
<li class="nav-item nav-item-this"><a href=""><span class="section-number">6. </span>運算式</a></li>
<li class="right">
<div class="inline-search" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="快速搜尋" aria-label="快速搜尋" type="search" name="q" id="search-box" />
<input type="submit" value="前往" />
</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="expressions">
<span id="id1"></span><h1><span class="section-number">6. </span>運算式<a class="headerlink" href="#expressions" title="連結到這個標頭">¶</a></h1>
<p id="index-0">This chapter explains the meaning of the elements of expressions in Python.</p>
<p><strong>Syntax Notes:</strong> In this and the following chapters, extended BNF notation will
be used to describe syntax, not lexical analysis. When (one alternative of) a
syntax rule has the form</p>
<pre>
<strong id="grammar-token-python-grammar-name">name</strong> ::= othername
</pre>
<p>and no semantics are given, the semantics of this form of <code class="docutils literal notranslate"><span class="pre">name</span></code> are the same
as for <code class="docutils literal notranslate"><span class="pre">othername</span></code>.</p>
<section id="arithmetic-conversions">
<span id="conversions"></span><h2><span class="section-number">6.1. </span>Arithmetic conversions<a class="headerlink" href="#arithmetic-conversions" title="連結到這個標頭">¶</a></h2>
<p id="index-1">When a description of an arithmetic operator below uses the phrase "the numeric
arguments are converted to a common type", this means that the operator
implementation for built-in types works as follows:</p>
<ul class="simple">
<li><p>If either argument is a complex number, the other is converted to complex;</p></li>
<li><p>otherwise, if either argument is a floating-point number, the other is
converted to floating point;</p></li>
<li><p>otherwise, both must be integers and no conversion is necessary.</p></li>
</ul>
<p>Some additional rules apply for certain operators (e.g., a string as a left
argument to the '%' operator). Extensions must define their own conversion
behavior.</p>
</section>
<section id="atoms">
<span id="id2"></span><h2><span class="section-number">6.2. </span>Atoms<a class="headerlink" href="#atoms" title="連結到這個標頭">¶</a></h2>
<p id="index-2">Atoms are the most basic elements of expressions. The simplest atoms are
identifiers or literals. Forms enclosed in parentheses, brackets or braces are
also categorized syntactically as atoms. The syntax for atoms is:</p>
<pre>
<strong id="grammar-token-python-grammar-atom">atom</strong> ::= <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-literal"><code class="xref docutils literal notranslate"><span class="pre">literal</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-enclosure"><code class="xref docutils literal notranslate"><span class="pre">enclosure</span></code></a>
<strong id="grammar-token-python-grammar-enclosure">enclosure</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-parenth_form"><code class="xref docutils literal notranslate"><span class="pre">parenth_form</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-list_display"><code class="xref docutils literal notranslate"><span class="pre">list_display</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-dict_display"><code class="xref docutils literal notranslate"><span class="pre">dict_display</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-set_display"><code class="xref docutils literal notranslate"><span class="pre">set_display</span></code></a>
| <a class="reference internal" href="#grammar-token-python-grammar-generator_expression"><code class="xref docutils literal notranslate"><span class="pre">generator_expression</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-yield_atom"><code class="xref docutils literal notranslate"><span class="pre">yield_atom</span></code></a>
</pre>
<section id="atom-identifiers">
<span id="identifiers-names"></span><h3><span class="section-number">6.2.1. </span>Identifiers (Names)<a class="headerlink" href="#atom-identifiers" title="連結到這個標頭">¶</a></h3>
<p id="index-3">An identifier occurring as an atom is a name. See section <a class="reference internal" href="lexical_analysis.html#identifiers"><span class="std std-ref">Identifiers and keywords</span></a>
for lexical definition and section <a class="reference internal" href="executionmodel.html#naming"><span class="std std-ref">Naming and binding</span></a> for documentation of naming and
binding.</p>
<p id="index-4">When the name is bound to an object, evaluation of the atom yields that object.
When a name is not bound, an attempt to evaluate it raises a <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>
exception.</p>
<section id="index-5">
<span id="private-name-mangling"></span><span id="id3"></span><h4><span class="section-number">6.2.1.1. </span>Private name mangling<a class="headerlink" href="#index-5" title="連結到這個標頭">¶</a></h4>
<p>When an identifier that textually occurs in a class definition begins with two
or more underscore characters and does not end in two or more underscores, it
is considered a <em class="dfn">private name</em> of that class.</p>
<div class="admonition seealso">
<p class="admonition-title">也參考</p>
<p>The <a class="reference internal" href="compound_stmts.html#class"><span class="std std-ref">class specifications</span></a>.</p>
</div>
<p>More precisely, private names are transformed to a longer form before code is
generated for them. If the transformed name is longer than 255 characters,
implementation-defined truncation may happen.</p>
<p>The transformation is independent of the syntactical context in which the
identifier is used but only the following private identifiers are mangled:</p>
<ul>
<li><p>Any name used as the name of a variable that is assigned or read or any
name of an attribute being accessed.</p>
<p>The <a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> attribute of nested functions, classes, and
type aliases is however not mangled.</p>
</li>
<li><p>The name of imported modules, e.g., <code class="docutils literal notranslate"><span class="pre">__spam</span></code> in <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">__spam</span></code>.
If the module is part of a package (i.e., its name contains a dot),
the name is <em>not</em> mangled, e.g., the <code class="docutils literal notranslate"><span class="pre">__foo</span></code> in <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">__foo.bar</span></code>
is not mangled.</p></li>
<li><p>The name of an imported member, e.g., <code class="docutils literal notranslate"><span class="pre">__f</span></code> in <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">spam</span> <span class="pre">import</span> <span class="pre">__f</span></code>.</p></li>
</ul>
<p>The transformation rule is defined as follows:</p>
<ul class="simple">
<li><p>The class name, with leading underscores removed and a single leading
underscore inserted, is inserted in front of the identifier, e.g., the
identifier <code class="docutils literal notranslate"><span class="pre">__spam</span></code> occurring in a class named <code class="docutils literal notranslate"><span class="pre">Foo</span></code>, <code class="docutils literal notranslate"><span class="pre">_Foo</span></code> or
<code class="docutils literal notranslate"><span class="pre">__Foo</span></code> is transformed to <code class="docutils literal notranslate"><span class="pre">_Foo__spam</span></code>.</p></li>
<li><p>If the class name consists only of underscores, the transformation is the
identity, e.g., the identifier <code class="docutils literal notranslate"><span class="pre">__spam</span></code> occurring in a class named <code class="docutils literal notranslate"><span class="pre">_</span></code>
or <code class="docutils literal notranslate"><span class="pre">__</span></code> is left as is.</p></li>
</ul>
</section>
</section>
<section id="literals">
<span id="atom-literals"></span><h3><span class="section-number">6.2.2. </span>Literals<a class="headerlink" href="#literals" title="連結到這個標頭">¶</a></h3>
<p id="index-6">Python supports string and bytes literals and various numeric literals:</p>
<pre>
<strong id="grammar-token-python-grammar-literal">literal</strong> ::= <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-stringliteral"><code class="xref docutils literal notranslate"><span class="pre">stringliteral</span></code></a> | <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-bytesliteral"><code class="xref docutils literal notranslate"><span class="pre">bytesliteral</span></code></a>
| <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-integer"><code class="xref docutils literal notranslate"><span class="pre">integer</span></code></a> | <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-floatnumber"><code class="xref docutils literal notranslate"><span class="pre">floatnumber</span></code></a> | <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-imagnumber"><code class="xref docutils literal notranslate"><span class="pre">imagnumber</span></code></a>
</pre>
<p>Evaluation of a literal yields an object of the given type (string, bytes,
integer, floating-point number, complex number) with the given value. The value
may be approximated in the case of floating-point and imaginary (complex)
literals. See section <a class="reference internal" href="lexical_analysis.html#literals"><span class="std std-ref">Literals</span></a> for details.</p>
<p id="index-7">All literals correspond to immutable data types, and hence the object's identity
is less important than its value. Multiple evaluations of literals with the
same value (either the same occurrence in the program text or a different
occurrence) may obtain the same object or a different object with the same
value.</p>
</section>
<section id="parenthesized-forms">
<span id="parenthesized"></span><h3><span class="section-number">6.2.3. </span>Parenthesized forms<a class="headerlink" href="#parenthesized-forms" title="連結到這個標頭">¶</a></h3>
<p id="index-8">A parenthesized form is an optional expression list enclosed in parentheses:</p>
<pre>
<strong id="grammar-token-python-grammar-parenth_form">parenth_form</strong> ::= "(" [<a class="reference internal" href="#grammar-token-python-grammar-starred_expression"><code class="xref docutils literal notranslate"><span class="pre">starred_expression</span></code></a>] ")"
</pre>
<p>A parenthesized expression list yields whatever that expression list yields: if
the list contains at least one comma, it yields a tuple; otherwise, it yields
the single expression that makes up the expression list.</p>
<p id="index-9">An empty pair of parentheses yields an empty tuple object. Since tuples are
immutable, the same rules as for literals apply (i.e., two occurrences of the empty
tuple may or may not yield the same object).</p>
<p id="index-10">Note that tuples are not formed by the parentheses, but rather by use of the
comma. The exception is the empty tuple, for which parentheses <em>are</em>
required --- allowing unparenthesized "nothing" in expressions would cause
ambiguities and allow common typos to pass uncaught.</p>
</section>
<section id="displays-for-lists-sets-and-dictionaries">
<span id="comprehensions"></span><h3><span class="section-number">6.2.4. </span>Displays for lists, sets and dictionaries<a class="headerlink" href="#displays-for-lists-sets-and-dictionaries" title="連結到這個標頭">¶</a></h3>
<p id="index-11">For constructing a list, a set or a dictionary Python provides special syntax
called "displays", each of them in two flavors:</p>
<ul class="simple">
<li><p>either the container contents are listed explicitly, or</p></li>
<li><p>they are computed via a set of looping and filtering instructions, called a
<em class="dfn">comprehension</em>.</p></li>
</ul>
<p id="index-12">Common syntax elements for comprehensions are:</p>
<pre>
<strong id="grammar-token-python-grammar-comprehension">comprehension</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-assignment_expression"><code class="xref docutils literal notranslate"><span class="pre">assignment_expression</span></code></a> <a class="reference internal" href="#grammar-token-python-grammar-comp_for"><code class="xref docutils literal notranslate"><span class="pre">comp_for</span></code></a>
<strong id="grammar-token-python-grammar-comp_for">comp_for</strong> ::= ["async"] "for" <a class="reference internal" href="simple_stmts.html#grammar-token-python-grammar-target_list"><code class="xref docutils literal notranslate"><span class="pre">target_list</span></code></a> "in" <a class="reference internal" href="#grammar-token-python-grammar-or_test"><code class="xref docutils literal notranslate"><span class="pre">or_test</span></code></a> [<a class="reference internal" href="#grammar-token-python-grammar-comp_iter"><code class="xref docutils literal notranslate"><span class="pre">comp_iter</span></code></a>]
<strong id="grammar-token-python-grammar-comp_iter">comp_iter</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-comp_for"><code class="xref docutils literal notranslate"><span class="pre">comp_for</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-comp_if"><code class="xref docutils literal notranslate"><span class="pre">comp_if</span></code></a>
<strong id="grammar-token-python-grammar-comp_if">comp_if</strong> ::= "if" <a class="reference internal" href="#grammar-token-python-grammar-or_test"><code class="xref docutils literal notranslate"><span class="pre">or_test</span></code></a> [<a class="reference internal" href="#grammar-token-python-grammar-comp_iter"><code class="xref docutils literal notranslate"><span class="pre">comp_iter</span></code></a>]
</pre>
<p>The comprehension consists of a single expression followed by at least one
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clause and zero or more <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> or <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> clauses.
In this case, the elements of the new container are those that would be produced
by considering each of the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> or <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> clauses a block,
nesting from left to right, and evaluating the expression to produce an element
each time the innermost block is reached.</p>
<p>However, aside from the iterable expression in the leftmost <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clause,
the comprehension is executed in a separate implicitly nested scope. This ensures
that names assigned to in the target list don't "leak" into the enclosing scope.</p>
<p>The iterable expression in the leftmost <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clause is evaluated
directly in the enclosing scope and then passed as an argument to the implicitly
nested scope. Subsequent <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clauses and any filter condition in the
leftmost <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clause cannot be evaluated in the enclosing scope as
they may depend on the values obtained from the leftmost iterable. For example:
<code class="docutils literal notranslate"><span class="pre">[x*y</span> <span class="pre">for</span> <span class="pre">x</span> <span class="pre">in</span> <span class="pre">range(10)</span> <span class="pre">for</span> <span class="pre">y</span> <span class="pre">in</span> <span class="pre">range(x,</span> <span class="pre">x+10)]</span></code>.</p>
<p>To ensure the comprehension always results in a container of the appropriate
type, <code class="docutils literal notranslate"><span class="pre">yield</span></code> and <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code> expressions are prohibited in the implicitly
nested scope.</p>
<p id="index-13">Since Python 3.6, in an <a class="reference internal" href="compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> function, an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code>
clause may be used to iterate over a <a class="reference internal" href="../glossary.html#term-asynchronous-iterator"><span class="xref std std-term">asynchronous iterator</span></a>.
A comprehension in an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code> function may consist of either a
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> or <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code> clause following the leading
expression, may contain additional <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> or <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code>
clauses, and may also use <a class="reference internal" href="#await"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code></a> expressions.</p>
<p>If a comprehension contains <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code> clauses, or if it contains
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code> expressions or other asynchronous comprehensions anywhere except
the iterable expression in the leftmost <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clause, it is called an
<em class="dfn">asynchronous comprehension</em>. An asynchronous comprehension may suspend the
execution of the coroutine function in which it appears.
See also <span class="target" id="index-14"></span><a class="pep reference external" href="https://peps.python.org/pep-0530/"><strong>PEP 530</strong></a>.</p>
<div class="versionadded">
<p><span class="versionmodified added">在 3.6 版被加入: </span>Asynchronous comprehensions were introduced.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.8 版的變更: </span><code class="docutils literal notranslate"><span class="pre">yield</span></code> and <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code> prohibited in the implicitly nested scope.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.11 版的變更: </span>Asynchronous comprehensions are now allowed inside comprehensions in
asynchronous functions. Outer comprehensions implicitly become
asynchronous.</p>
</div>
</section>
<section id="list-displays">
<span id="lists"></span><h3><span class="section-number">6.2.5. </span>List displays<a class="headerlink" href="#list-displays" title="連結到這個標頭">¶</a></h3>
<p id="index-15">A list display is a possibly empty series of expressions enclosed in square
brackets:</p>
<pre>
<strong id="grammar-token-python-grammar-list_display">list_display</strong> ::= "[" [<a class="reference internal" href="#grammar-token-python-grammar-flexible_expression_list"><code class="xref docutils literal notranslate"><span class="pre">flexible_expression_list</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-comprehension"><code class="xref docutils literal notranslate"><span class="pre">comprehension</span></code></a>] "]"
</pre>
<p>A list display yields a new list object, the contents being specified by either
a list of expressions or a comprehension. When a comma-separated list of
expressions is supplied, its elements are evaluated from left to right and
placed into the list object in that order. When a comprehension is supplied,
the list is constructed from the elements resulting from the comprehension.</p>
</section>
<section id="set-displays">
<span id="set"></span><h3><span class="section-number">6.2.6. </span>Set displays<a class="headerlink" href="#set-displays" title="連結到這個標頭">¶</a></h3>
<p id="index-16">A set display is denoted by curly braces and distinguishable from dictionary
displays by the lack of colons separating keys and values:</p>
<pre>
<strong id="grammar-token-python-grammar-set_display">set_display</strong> ::= "{" (<a class="reference internal" href="#grammar-token-python-grammar-flexible_expression_list"><code class="xref docutils literal notranslate"><span class="pre">flexible_expression_list</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-comprehension"><code class="xref docutils literal notranslate"><span class="pre">comprehension</span></code></a>) "}"
</pre>
<p>A set display yields a new mutable set object, the contents being specified by
either a sequence of expressions or a comprehension. When a comma-separated
list of expressions is supplied, its elements are evaluated from left to right
and added to the set object. When a comprehension is supplied, the set is
constructed from the elements resulting from the comprehension.</p>
<p>An empty set cannot be constructed with <code class="docutils literal notranslate"><span class="pre">{}</span></code>; this literal constructs an empty
dictionary.</p>
</section>
<section id="dictionary-displays">
<span id="dict"></span><h3><span class="section-number">6.2.7. </span>Dictionary displays<a class="headerlink" href="#dictionary-displays" title="連結到這個標頭">¶</a></h3>
<p id="index-17">A dictionary display is a possibly empty series of dict items (key/value pairs)
enclosed in curly braces:</p>
<pre>
<strong id="grammar-token-python-grammar-dict_display">dict_display</strong> ::= "{" [<a class="reference internal" href="#grammar-token-python-grammar-dict_item_list"><code class="xref docutils literal notranslate"><span class="pre">dict_item_list</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-dict_comprehension"><code class="xref docutils literal notranslate"><span class="pre">dict_comprehension</span></code></a>] "}"
<strong id="grammar-token-python-grammar-dict_item_list">dict_item_list</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-dict_item"><code class="xref docutils literal notranslate"><span class="pre">dict_item</span></code></a> ("," <a class="reference internal" href="#grammar-token-python-grammar-dict_item"><code class="xref docutils literal notranslate"><span class="pre">dict_item</span></code></a>)* [","]
<strong id="grammar-token-python-grammar-dict_item">dict_item</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> ":" <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> | "**" <a class="reference internal" href="#grammar-token-python-grammar-or_expr"><code class="xref docutils literal notranslate"><span class="pre">or_expr</span></code></a>
<strong id="grammar-token-python-grammar-dict_comprehension">dict_comprehension</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> ":" <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> <a class="reference internal" href="#grammar-token-python-grammar-comp_for"><code class="xref docutils literal notranslate"><span class="pre">comp_for</span></code></a>
</pre>
<p>A dictionary display yields a new dictionary object.</p>
<p>If a comma-separated sequence of dict items is given, they are evaluated
from left to right to define the entries of the dictionary: each key object is
used as a key into the dictionary to store the corresponding value. This means
that you can specify the same key multiple times in the dict item list, and the
final dictionary's value for that key will be the last one given.</p>
<p id="index-18">A double asterisk <code class="docutils literal notranslate"><span class="pre">**</span></code> denotes <em class="dfn">dictionary unpacking</em>.
Its operand must be a <a class="reference internal" href="../glossary.html#term-mapping"><span class="xref std std-term">mapping</span></a>. Each mapping item is added
to the new dictionary. Later values replace values already set by
earlier dict items and earlier dictionary unpackings.</p>
<div class="versionadded">
<p><span class="versionmodified added">在 3.5 版被加入: </span>Unpacking into dictionary displays, originally proposed by <span class="target" id="index-19"></span><a class="pep reference external" href="https://peps.python.org/pep-0448/"><strong>PEP 448</strong></a>.</p>
</div>
<p>A dict comprehension, in contrast to list and set comprehensions, needs two
expressions separated with a colon followed by the usual "for" and "if" clauses.
When the comprehension is run, the resulting key and value elements are inserted
in the new dictionary in the order they are produced.</p>
<p id="index-20">Restrictions on the types of the key values are listed earlier in section
<a class="reference internal" href="datamodel.html#types"><span class="std std-ref">標準型別階層</span></a>. (To summarize, the key type should be <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a>, which excludes
all mutable objects.) Clashes between duplicate keys are not detected; the last
value (textually rightmost in the display) stored for a given key value
prevails.</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.8 版的變更: </span>Prior to Python 3.8, in dict comprehensions, the evaluation order of key
and value was not well-defined. In CPython, the value was evaluated before
the key. Starting with 3.8, the key is evaluated before the value, as
proposed by <span class="target" id="index-21"></span><a class="pep reference external" href="https://peps.python.org/pep-0572/"><strong>PEP 572</strong></a>.</p>
</div>
</section>
<section id="generator-expressions">
<span id="genexpr"></span><h3><span class="section-number">6.2.8. </span>Generator expressions<a class="headerlink" href="#generator-expressions" title="連結到這個標頭">¶</a></h3>
<p id="index-22">A generator expression is a compact generator notation in parentheses:</p>
<pre>
<strong id="grammar-token-python-grammar-generator_expression">generator_expression</strong> ::= "(" <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> <a class="reference internal" href="#grammar-token-python-grammar-comp_for"><code class="xref docutils literal notranslate"><span class="pre">comp_for</span></code></a> ")"
</pre>
<p>A generator expression yields a new generator object. Its syntax is the same as
for comprehensions, except that it is enclosed in parentheses instead of
brackets or curly braces.</p>
<p>Variables used in the generator expression are evaluated lazily when the
<a class="reference internal" href="#generator.__next__" title="generator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code></a> method is called for the generator object (in the same
fashion as normal generators). However, the iterable expression in the
leftmost <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clause is immediately evaluated, so that an error
produced by it will be emitted at the point where the generator expression
is defined, rather than at the point where the first value is retrieved.
Subsequent <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clauses and any filter condition in the leftmost
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clause cannot be evaluated in the enclosing scope as they may
depend on the values obtained from the leftmost iterable. For example:
<code class="docutils literal notranslate"><span class="pre">(x*y</span> <span class="pre">for</span> <span class="pre">x</span> <span class="pre">in</span> <span class="pre">range(10)</span> <span class="pre">for</span> <span class="pre">y</span> <span class="pre">in</span> <span class="pre">range(x,</span> <span class="pre">x+10))</span></code>.</p>
<p>The parentheses can be omitted on calls with only one argument. See section
<a class="reference internal" href="#calls"><span class="std std-ref">Calls</span></a> for details.</p>
<p>To avoid interfering with the expected operation of the generator expression
itself, <code class="docutils literal notranslate"><span class="pre">yield</span></code> and <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code> expressions are prohibited in the
implicitly defined generator.</p>
<p>If a generator expression contains either <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code>
clauses or <a class="reference internal" href="#await"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code></a> expressions it is called an
<em class="dfn">asynchronous generator expression</em>. An asynchronous generator
expression returns a new asynchronous generator object,
which is an asynchronous iterator (see <a class="reference internal" href="datamodel.html#async-iterators"><span class="std std-ref">Asynchronous Iterators</span></a>).</p>
<div class="versionadded">
<p><span class="versionmodified added">在 3.6 版被加入: </span>Asynchronous generator expressions were introduced.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版的變更: </span>Prior to Python 3.7, asynchronous generator expressions could
only appear in <a class="reference internal" href="compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> coroutines. Starting
with 3.7, any function can use asynchronous generator expressions.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.8 版的變更: </span><code class="docutils literal notranslate"><span class="pre">yield</span></code> and <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code> prohibited in the implicitly nested scope.</p>
</div>
</section>
<section id="yield-expressions">
<span id="yieldexpr"></span><h3><span class="section-number">6.2.9. </span>Yield expressions<a class="headerlink" href="#yield-expressions" title="連結到這個標頭">¶</a></h3>
<pre id="index-23">
<strong id="grammar-token-python-grammar-yield_atom">yield_atom</strong> ::= "(" <a class="reference internal" href="#grammar-token-python-grammar-yield_expression"><code class="xref docutils literal notranslate"><span class="pre">yield_expression</span></code></a> ")"
<strong id="grammar-token-python-grammar-yield_from">yield_from</strong> ::= "yield" "from" <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
<strong id="grammar-token-python-grammar-yield_expression">yield_expression</strong> ::= "yield" <a class="reference internal" href="#grammar-token-python-grammar-yield_list"><code class="xref docutils literal notranslate"><span class="pre">yield_list</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-yield_from"><code class="xref docutils literal notranslate"><span class="pre">yield_from</span></code></a>
</pre>
<p>The yield expression is used when defining a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a> function
or an <a class="reference internal" href="../glossary.html#term-asynchronous-generator"><span class="xref std std-term">asynchronous generator</span></a> function and
thus can only be used in the body of a function definition. Using a yield
expression in a function's body causes that function to be a generator function,
and using it in an <a class="reference internal" href="compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> function's body causes that
coroutine function to be an asynchronous generator function. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">gen</span><span class="p">():</span> <span class="c1"># defines a generator function</span>
<span class="k">yield</span> <span class="mi">123</span>
<span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">agen</span><span class="p">():</span> <span class="c1"># defines an asynchronous generator function</span>
<span class="k">yield</span> <span class="mi">123</span>
</pre></div>
</div>
<p>Due to their side effects on the containing scope, <code class="docutils literal notranslate"><span class="pre">yield</span></code> expressions
are not permitted as part of the implicitly defined scopes used to
implement comprehensions and generator expressions.</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.8 版的變更: </span>Yield expressions prohibited in the implicitly nested scopes used to
implement comprehensions and generator expressions.</p>
</div>
<p>Generator functions are described below, while asynchronous generator
functions are described separately in section
<a class="reference internal" href="#asynchronous-generator-functions"><span class="std std-ref">非同步產生器函式</span></a>.</p>
<p>When a generator function is called, it returns an iterator known as a
generator. That generator then controls the execution of the generator
function. The execution starts when one of the generator's methods is called.
At that time, the execution proceeds to the first yield expression, where it is
suspended again, returning the value of <a class="reference internal" href="#grammar-token-python-grammar-yield_list"><code class="xref std std-token docutils literal notranslate"><span class="pre">yield_list</span></code></a>
to the generator's caller,
or <code class="docutils literal notranslate"><span class="pre">None</span></code> if <a class="reference internal" href="#grammar-token-python-grammar-yield_list"><code class="xref std std-token docutils literal notranslate"><span class="pre">yield_list</span></code></a> is omitted.
By suspended, we mean that all local state is
retained, including the current bindings of local variables, the instruction
pointer, the internal evaluation stack, and the state of any exception handling.
When the execution is resumed by calling one of the generator's methods, the
function can proceed exactly as if the yield expression were just another
external call. The value of the yield expression after resuming depends on the
method which resumed the execution. If <a class="reference internal" href="#generator.__next__" title="generator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code></a> is used
(typically via either a <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> or the <a class="reference internal" href="../library/functions.html#next" title="next"><code class="xref py py-func docutils literal notranslate"><span class="pre">next()</span></code></a> builtin) then the
result is <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>. Otherwise, if <a class="reference internal" href="#generator.send" title="generator.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> is used, then
the result will be the value passed in to that method.</p>
<p id="index-24">All of this makes generator functions quite similar to coroutines; they yield
multiple times, they have more than one entry point and their execution can be
suspended. The only difference is that a generator function cannot control
where the execution should continue after it yields; the control is always
transferred to the generator's caller.</p>
<p>Yield expressions are allowed anywhere in a <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> construct. If the
generator is not resumed before it is
finalized (by reaching a zero reference count or by being garbage collected),
the generator-iterator's <a class="reference internal" href="#generator.close" title="generator.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method will be called,
allowing any pending <a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clauses to execute.</p>
<p id="index-25">When <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span> <span class="pre"><expr></span></code> is used, the supplied expression must be an
iterable. The values produced by iterating that iterable are passed directly
to the caller of the current generator's methods. Any values passed in with
<a class="reference internal" href="#generator.send" title="generator.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> and any exceptions passed in with
<a class="reference internal" href="#generator.throw" title="generator.throw"><code class="xref py py-meth docutils literal notranslate"><span class="pre">throw()</span></code></a> are passed to the underlying iterator if it has the
appropriate methods. If this is not the case, then <a class="reference internal" href="#generator.send" title="generator.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a>
will raise <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> or <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>, while
<a class="reference internal" href="#generator.throw" title="generator.throw"><code class="xref py py-meth docutils literal notranslate"><span class="pre">throw()</span></code></a> will just raise the passed in exception immediately.</p>
<p>When the underlying iterator is complete, the <a class="reference internal" href="../library/exceptions.html#StopIteration.value" title="StopIteration.value"><code class="xref py py-attr docutils literal notranslate"><span class="pre">value</span></code></a>
attribute of the raised <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> instance becomes the value of
the yield expression. It can be either set explicitly when raising
<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>, or automatically when the subiterator is a generator
(by returning a value from the subgenerator).</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.3 版的變更: </span>Added <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span> <span class="pre"><expr></span></code> to delegate control flow to a subiterator.</p>
</div>
<p>The parentheses may be omitted when the yield expression is the sole expression
on the right hand side of an assignment statement.</p>
<div class="admonition seealso">
<p class="admonition-title">也參考</p>
<dl class="simple">
<dt><span class="target" id="index-26"></span><a class="pep reference external" href="https://peps.python.org/pep-0255/"><strong>PEP 255</strong></a> - Simple Generators</dt><dd><p>The proposal for adding generators and the <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement to Python.</p>
</dd>
<dt><span class="target" id="index-27"></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>The proposal to enhance the API and syntax of generators, making them
usable as simple coroutines.</p>
</dd>
<dt><span class="target" id="index-28"></span><a class="pep reference external" href="https://peps.python.org/pep-0380/"><strong>PEP 380</strong></a> - Syntax for Delegating to a Subgenerator</dt><dd><p>The proposal to introduce the <a class="reference internal" href="#grammar-token-python-grammar-yield_from"><code class="xref std std-token docutils literal notranslate"><span class="pre">yield_from</span></code></a> syntax,
making delegation to subgenerators easy.</p>
</dd>
<dt><span class="target" id="index-29"></span><a class="pep reference external" href="https://peps.python.org/pep-0525/"><strong>PEP 525</strong></a> - Asynchronous Generators</dt><dd><p>The proposal that expanded on <span class="target" id="index-30"></span><a class="pep reference external" href="https://peps.python.org/pep-0492/"><strong>PEP 492</strong></a> by adding generator capabilities to
coroutine functions.</p>
</dd>
</dl>
</div>
<section id="generator-iterator-methods">
<span id="generator-methods"></span><span id="index-31"></span><h4><span class="section-number">6.2.9.1. </span>Generator-iterator methods<a class="headerlink" href="#generator-iterator-methods" title="連結到這個標頭">¶</a></h4>
<p>This subsection describes the methods of a generator iterator. They can
be used to control the execution of a generator function.</p>
<p>Note that calling any of the generator methods below when the generator
is already executing raises 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> exception.</p>
<dl class="py method" id="index-32">
<dt class="sig sig-object py" id="generator.__next__">
<span class="sig-prename descclassname"><span class="pre">generator.</span></span><span class="sig-name descname"><span class="pre">__next__</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#generator.__next__" title="連結到這個定義">¶</a></dt>
<dd><p>Starts the execution of a generator function or resumes it at the last
executed yield expression. When a generator function is resumed with a
<a class="reference internal" href="#generator.__next__" title="generator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code></a> method, the current yield expression always
evaluates to <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>. The execution then continues to the next yield
expression, where the generator is suspended again, and the value of the
<a class="reference internal" href="#grammar-token-python-grammar-yield_list"><code class="xref std std-token docutils literal notranslate"><span class="pre">yield_list</span></code></a> is returned to <a class="reference internal" href="#generator.__next__" title="generator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code></a>'s
caller. If the generator exits without yielding another value, a
<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> exception is raised.</p>
<p>This method is normally called implicitly, e.g. by a <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop, or
by the built-in <a class="reference internal" href="../library/functions.html#next" title="next"><code class="xref py py-func docutils literal notranslate"><span class="pre">next()</span></code></a> function.</p>
</dd></dl>
<dl class="py method">
<dt class="sig sig-object py" id="generator.send">
<span class="sig-prename descclassname"><span class="pre">generator.</span></span><span class="sig-name descname"><span class="pre">send</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#generator.send" title="連結到這個定義">¶</a></dt>
<dd><p>Resumes the execution and "sends" a value into the generator function. The
<em>value</em> argument becomes the result of the current yield expression. The
<a class="reference internal" href="#generator.send" title="generator.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> method returns the next value yielded by the generator, or
raises <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> if the generator exits without yielding another
value. When <a class="reference internal" href="#generator.send" title="generator.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> is called to start the generator, it must be called
with <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> as the argument, because there is no yield expression that
could receive the value.</p>
</dd></dl>
<dl class="py method">
<dt class="sig sig-object py" id="generator.throw">
<span class="sig-prename descclassname"><span class="pre">generator.</span></span><span class="sig-name descname"><span class="pre">throw</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#generator.throw" title="連結到這個定義">¶</a></dt>
<dt class="sig sig-object py">
<span class="sig-prename descclassname"><span class="pre">generator.</span></span><span class="sig-name descname"><span class="pre">throw</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">type</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">traceback</span></span></em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Raises an exception at the point where the generator was paused,
and returns the next value yielded by the generator function. If the generator
exits without yielding another value, a <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> exception is
raised. If the generator function does not catch the passed-in exception, or
raises a different exception, then that exception propagates to the caller.</p>
<p>In typical use, this is called with a single exception instance similar to the
way the <a class="reference internal" href="simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> keyword is used.</p>
<p>For backwards compatibility, however, the second signature is
supported, following a convention from older versions of Python.
The <em>type</em> argument should be an exception class, and <em>value</em>
should be an exception instance. If the <em>value</em> is not provided, the
<em>type</em> constructor is called to get an instance. If <em>traceback</em>
is provided, it is set on the exception, otherwise any existing
<a class="reference internal" href="../library/exceptions.html#BaseException.__traceback__" title="BaseException.__traceback__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__traceback__</span></code></a> attribute stored in <em>value</em> may
be cleared.</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.12 版的變更: </span>The second signature (type[, value[, traceback]]) is deprecated and
may be removed in a future version of Python.</p>
</div>
</dd></dl>
<dl class="py method" id="index-33">
<dt class="sig sig-object py" id="generator.close">
<span class="sig-prename descclassname"><span class="pre">generator.</span></span><span class="sig-name descname"><span class="pre">close</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#generator.close" title="連結到這個定義">¶</a></dt>
<dd><p>Raises 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> at the point where the generator function was
paused. If the generator function catches the exception and returns a
value, this value is returned from <a class="reference internal" href="#generator.close" title="generator.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a>. If the generator function
is already closed, or raises <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> (by not catching the
exception), <a class="reference internal" href="#generator.close" title="generator.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> 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>. If the generator yields a
value, 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> is raised. If the generator raises any other
exception, it is propagated to the caller. If the generator has already
exited due to an exception or normal exit, <a class="reference internal" href="#generator.close" title="generator.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> 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> and has no other effect.</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.13 版的變更: </span>If a generator returns a value upon being closed, the value is returned
by <a class="reference internal" href="#generator.close" title="generator.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a>.</p>
</div>
</dd></dl>
</section>
<section id="examples">
<span id="index-34"></span><h4><span class="section-number">6.2.9.2. </span>模組<a class="headerlink" href="#examples" title="連結到這個標頭">¶</a></h4>
<p>Here is a simple example that demonstrates the behavior of generators and
generator functions:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span><span class="w"> </span><span class="nf">echo</span><span class="p">(</span><span class="n">value</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"Execution starts when 'next()' is called for the first time."</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="n">value</span> <span class="o">=</span> <span class="p">(</span><span class="k">yield</span> <span class="n">value</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
<span class="gp">... </span> <span class="n">value</span> <span class="o">=</span> <span class="n">e</span>
<span class="gp">... </span> <span class="k">finally</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"Don't forget to clean up when 'close()' is called."</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">>>> </span><span class="n">generator</span> <span class="o">=</span> <span class="n">echo</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="nb">next</span><span class="p">(</span><span class="n">generator</span><span class="p">))</span>
<span class="go">Execution starts when 'next()' is called for the first time.</span>
<span class="go">1</span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="nb">next</span><span class="p">(</span><span class="n">generator</span><span class="p">))</span>
<span class="go">None</span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">generator</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="mi">2</span><span class="p">))</span>
<span class="go">2</span>
<span class="gp">>>> </span><span class="n">generator</span><span class="o">.</span><span class="n">throw</span><span class="p">(</span><span class="ne">TypeError</span><span class="p">,</span> <span class="s2">"spam"</span><span class="p">)</span>
<span class="go">TypeError('spam',)</span>
<span class="gp">>>> </span><span class="n">generator</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="go">Don't forget to clean up when 'close()' is called.</span>
</pre></div>
</div>
<p>For examples using <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code>, see <a class="reference internal" href="../whatsnew/3.3.html#pep-380"><span class="std std-ref">PEP 380: Syntax for Delegating to a Subgenerator</span></a> in "What's New in
Python."</p>
</section>
<section id="asynchronous-generator-functions">
<span id="id4"></span><h4><span class="section-number">6.2.9.3. </span>非同步產生器函式<a class="headerlink" href="#asynchronous-generator-functions" title="連結到這個標頭">¶</a></h4>
<p>The presence of a yield expression in a function or method defined using
<a class="reference internal" href="compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> further defines the function as an
<a class="reference internal" href="../glossary.html#term-asynchronous-generator"><span class="xref std std-term">asynchronous generator</span></a> function.</p>
<p>When an asynchronous generator function is called, it returns an
asynchronous iterator known as an asynchronous generator object.
That object then controls the execution of the generator function.
An asynchronous generator object is typically used in an
<a class="reference internal" href="compound_stmts.html#async-for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code></a> statement in a coroutine function analogously to
how a generator object would be used in a <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statement.</p>
<p>Calling one of the asynchronous generator's methods returns an <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a>
object, and the execution starts when this object is awaited on. At that time,
the execution proceeds to the first yield expression, where it is suspended
again, returning the value of <a class="reference internal" href="#grammar-token-python-grammar-yield_list"><code class="xref std std-token docutils literal notranslate"><span class="pre">yield_list</span></code></a> to the
awaiting coroutine. As with a generator, suspension means that all local state
is retained, including the current bindings of local variables, the instruction
pointer, the internal evaluation stack, and the state of any exception handling.
When the execution is resumed by awaiting on the next object returned by the
asynchronous generator's methods, the function can proceed exactly as if the
yield expression were just another external call. The value of the yield
expression after resuming depends on the method which resumed the execution. If
<a class="reference internal" href="#agen.__anext__" title="agen.__anext__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__anext__()</span></code></a> is used then the result is <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>. Otherwise, if
<a class="reference internal" href="#agen.asend" title="agen.asend"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asend()</span></code></a> is used, then the result will be the value passed in to that
method.</p>
<p>If an asynchronous generator happens to exit early by <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a>, the caller
task being cancelled, or other exceptions, the generator's async cleanup code
will run and possibly raise exceptions or access context variables in an
unexpected context--perhaps after the lifetime of tasks it depends, or
during the event loop shutdown when the async-generator garbage collection hook
is called.
To prevent this, the caller must explicitly close the async generator by calling
<a class="reference internal" href="#agen.aclose" title="agen.aclose"><code class="xref py py-meth docutils literal notranslate"><span class="pre">aclose()</span></code></a> method to finalize the generator and ultimately detach it
from the event loop.</p>
<p>In an asynchronous generator function, yield expressions are allowed anywhere
in a <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> construct. However, if an asynchronous generator is not
resumed before it is finalized (by reaching a zero reference count or by
being garbage collected), then a yield expression within a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code>
construct could result in a failure to execute pending <a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a>
clauses. In this case, it is the responsibility of the event loop or
scheduler running the asynchronous generator to call the asynchronous
generator-iterator's <a class="reference internal" href="#agen.aclose" title="agen.aclose"><code class="xref py py-meth docutils literal notranslate"><span class="pre">aclose()</span></code></a> method and run the resulting
coroutine object, thus allowing any pending <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clauses
to execute.</p>
<p>To take care of finalization upon event loop termination, an event loop should
define a <em>finalizer</em> function which takes an asynchronous generator-iterator and
presumably calls <a class="reference internal" href="#agen.aclose" title="agen.aclose"><code class="xref py py-meth docutils literal notranslate"><span class="pre">aclose()</span></code></a> and executes the coroutine.
This <em>finalizer</em> may be registered by calling <a class="reference internal" href="../library/sys.html#sys.set_asyncgen_hooks" title="sys.set_asyncgen_hooks"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.set_asyncgen_hooks()</span></code></a>.
When first iterated over, an asynchronous generator-iterator will store the
registered <em>finalizer</em> to be called upon finalization. For a reference example
of a <em>finalizer</em> method see the implementation of
<code class="docutils literal notranslate"><span class="pre">asyncio.Loop.shutdown_asyncgens</span></code> in <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/3.13/Lib/asyncio/base_events.py">Lib/asyncio/base_events.py</a>.</p>
<p>The expression <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span> <span class="pre"><expr></span></code> is a syntax error when used in an
asynchronous generator function.</p>
</section>
<section id="asynchronous-generator-iterator-methods">
<span id="asynchronous-generator-methods"></span><span id="index-35"></span><h4><span class="section-number">6.2.9.4. </span>Asynchronous generator-iterator methods<a class="headerlink" href="#asynchronous-generator-iterator-methods" title="連結到這個標頭">¶</a></h4>
<p>This subsection describes the methods of an asynchronous generator iterator,
which are used to control the execution of a generator function.</p>
<dl class="py method" id="index-36">
<dt class="sig sig-object py" id="agen.__anext__">
<em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">agen.</span></span><span class="sig-name descname"><span class="pre">__anext__</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#agen.__anext__" title="連結到這個定義">¶</a></dt>
<dd><p>Returns an awaitable which when run starts to execute the asynchronous
generator or resumes it at the last executed yield expression. When an
asynchronous generator function is resumed with an <a class="reference internal" href="#agen.__anext__" title="agen.__anext__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__anext__()</span></code></a>
method, the current yield expression always evaluates to <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> in the
returned awaitable, which when run will continue to the next yield
expression. The value of the <a class="reference internal" href="#grammar-token-python-grammar-yield_list"><code class="xref std std-token docutils literal notranslate"><span class="pre">yield_list</span></code></a> of the
yield expression is the value of the <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> exception raised by
the completing coroutine. If the asynchronous generator exits without
yielding another value, the awaitable instead raises a
<a class="reference internal" href="../library/exceptions.html#StopAsyncIteration" title="StopAsyncIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopAsyncIteration</span></code></a> exception, signalling that the asynchronous
iteration has completed.</p>
<p>This method is normally called implicitly by a <a class="reference internal" href="compound_stmts.html#async-for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code></a> loop.</p>
</dd></dl>
<dl class="py method">
<dt class="sig sig-object py" id="agen.asend">
<em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">agen.</span></span><span class="sig-name descname"><span class="pre">asend</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#agen.asend" title="連結到這個定義">¶</a></dt>
<dd><p>Returns an awaitable which when run resumes the execution of the
asynchronous generator. As with the <a class="reference internal" href="#generator.send" title="generator.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> method for a
generator, this "sends" a value into the asynchronous generator function,
and the <em>value</em> argument becomes the result of the current yield expression.
The awaitable returned by the <a class="reference internal" href="#agen.asend" title="agen.asend"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asend()</span></code></a> method will return the next
value yielded by the generator as the value of the raised
<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>, or raises <a class="reference internal" href="../library/exceptions.html#StopAsyncIteration" title="StopAsyncIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopAsyncIteration</span></code></a> if the
asynchronous generator exits without yielding another value. When
<a class="reference internal" href="#agen.asend" title="agen.asend"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asend()</span></code></a> is called to start the asynchronous
generator, it must be called with <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> as the argument,
because there is no yield expression that could receive the value.</p>
</dd></dl>
<dl class="py method">
<dt class="sig sig-object py" id="agen.athrow">
<em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">agen.</span></span><span class="sig-name descname"><span class="pre">athrow</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#agen.athrow" title="連結到這個定義">¶</a></dt>
<dt class="sig sig-object py">
<em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">agen.</span></span><span class="sig-name descname"><span class="pre">athrow</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">type</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">traceback</span></span></em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Returns an awaitable that raises an exception of type <code class="docutils literal notranslate"><span class="pre">type</span></code> at the point
where the asynchronous generator was paused, and returns the next value
yielded by the generator function as the value of the raised
<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> exception. If the asynchronous generator exits
without yielding another value, a <a class="reference internal" href="../library/exceptions.html#StopAsyncIteration" title="StopAsyncIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopAsyncIteration</span></code></a> exception is
raised by the awaitable.
If the generator function does not catch the passed-in exception, or
raises a different exception, then when the awaitable is run that exception
propagates to the caller of the awaitable.</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.12 版的變更: </span>The second signature (type[, value[, traceback]]) is deprecated and
may be removed in a future version of Python.</p>
</div>
</dd></dl>
<dl class="py method" id="index-37">
<dt class="sig sig-object py" id="agen.aclose">
<em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">agen.</span></span><span class="sig-name descname"><span class="pre">aclose</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#agen.aclose" title="連結到這個定義">¶</a></dt>
<dd><p>Returns an awaitable that when run will throw 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> into
the asynchronous generator function at the point where it was paused.
If the asynchronous generator function then exits gracefully, is already
closed, or raises <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> (by not catching the exception),
then the returned awaitable will raise a <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> exception.
Any further awaitables returned by subsequent calls to the asynchronous
generator will raise a <a class="reference internal" href="../library/exceptions.html#StopAsyncIteration" title="StopAsyncIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopAsyncIteration</span></code></a> exception. If the
asynchronous generator yields a value, 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> is raised
by the awaitable. If the asynchronous generator raises any other exception,
it is propagated to the caller of the awaitable. If the asynchronous
generator has already exited due to an exception or normal exit, then
further calls to <a class="reference internal" href="#agen.aclose" title="agen.aclose"><code class="xref py py-meth docutils literal notranslate"><span class="pre">aclose()</span></code></a> will return an awaitable that does nothing.</p>
</dd></dl>
</section>
</section>
</section>
<section id="primaries">
<span id="id5"></span><h2><span class="section-number">6.3. </span>Primaries<a class="headerlink" href="#primaries" title="連結到這個標頭">¶</a></h2>
<p id="index-38">Primaries represent the most tightly bound operations of the language. Their
syntax is:</p>
<pre>
<strong id="grammar-token-python-grammar-primary">primary</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-atom"><code class="xref docutils literal notranslate"><span class="pre">atom</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-attributeref"><code class="xref docutils literal notranslate"><span class="pre">attributeref</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-subscription"><code class="xref docutils literal notranslate"><span class="pre">subscription</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-slicing"><code class="xref docutils literal notranslate"><span class="pre">slicing</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-call"><code class="xref docutils literal notranslate"><span class="pre">call</span></code></a>
</pre>
<section id="attribute-references">
<span id="id6"></span><h3><span class="section-number">6.3.1. </span>Attribute references<a class="headerlink" href="#attribute-references" title="連結到這個標頭">¶</a></h3>
<p id="index-39">An attribute reference is a primary followed by a period and a name:</p>
<pre>
<strong id="grammar-token-python-grammar-attributeref">attributeref</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a> "." <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>
</pre>
<p id="index-40">The primary must evaluate to an object of a type that supports attribute
references, which most objects do. This object is then asked to produce the
attribute whose name is the identifier. The type and value produced is
determined by the object. Multiple evaluations of the same attribute
reference may yield different objects.</p>
<p>This production can be customized by overriding the
<a class="reference internal" href="datamodel.html#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> method or the <a class="reference internal" href="datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a>
method. The <code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code> method is called first and either
returns a value or raises <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> if the attribute is not
available.</p>
<p>If an <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> is raised and the object has a <code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code>
method, that method is called as a fallback.</p>
</section>
<section id="subscriptions">
<span id="id7"></span><h3><span class="section-number">6.3.2. </span>Subscriptions<a class="headerlink" href="#subscriptions" title="連結到這個標頭">¶</a></h3>
<p id="index-42"><span id="index-41"></span>The subscription of an instance of a <a class="reference internal" href="datamodel.html#sequence-types"><span class="std std-ref">container class</span></a>
will generally select an element from the container. The subscription of a
<a class="reference internal" href="../glossary.html#term-generic-type"><span class="xref std std-term">generic class</span></a> will generally return a
<a class="reference internal" href="../library/stdtypes.html#types-genericalias"><span class="std std-ref">GenericAlias</span></a> object.</p>
<pre>
<strong id="grammar-token-python-grammar-subscription">subscription</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a> "[" <a class="reference internal" href="#grammar-token-python-grammar-flexible_expression_list"><code class="xref docutils literal notranslate"><span class="pre">flexible_expression_list</span></code></a> "]"
</pre>
<p>When an object is subscripted, the interpreter will evaluate the primary and
the expression list.</p>
<p>The primary must evaluate to an object that supports subscription. An object
may support subscription through defining one or both of
<a class="reference internal" href="datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> and <a class="reference internal" href="datamodel.html#object.__class_getitem__" title="object.__class_getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__class_getitem__()</span></code></a>. When the
primary is subscripted, the evaluated result of the expression list will be
passed to one of these methods. For more details on when <code class="docutils literal notranslate"><span class="pre">__class_getitem__</span></code>
is called instead of <code class="docutils literal notranslate"><span class="pre">__getitem__</span></code>, see <a class="reference internal" href="datamodel.html#classgetitem-versus-getitem"><span class="std std-ref">__class_getitem__ versus __getitem__</span></a>.</p>
<p>If the expression list contains at least one comma, or if any of the expressions
are starred, the expression list will evaluate to a <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> containing
the items of the expression list. Otherwise, the expression list will evaluate
to the value of the list's sole member.</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.11 版的變更: </span>Expressions in an expression list may be starred. See <span class="target" id="index-43"></span><a class="pep reference external" href="https://peps.python.org/pep-0646/"><strong>PEP 646</strong></a>.</p>
</div>
<p>For built-in objects, there are two types of objects that support subscription
via <a class="reference internal" href="datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>:</p>
<ol class="arabic simple">
<li><p>Mappings. If the primary is a <a class="reference internal" href="../glossary.html#term-mapping"><span class="xref std std-term">mapping</span></a>, the expression list must
evaluate to an object whose value is one of the keys of the mapping, and the
subscription selects the value in the mapping that corresponds to that key.
An example of a builtin mapping class is the <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> class.</p></li>
<li><p>Sequences. If the primary is a <a class="reference internal" href="../glossary.html#term-sequence"><span class="xref std std-term">sequence</span></a>, the expression list must
evaluate to an <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> or a <a class="reference internal" href="../library/functions.html#slice" title="slice"><code class="xref py py-class docutils literal notranslate"><span class="pre">slice</span></code></a> (as discussed in the
following section). Examples of builtin sequence classes include the
<a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>, <a class="reference internal" href="../library/stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a> and <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> classes.</p></li>
</ol>
<p>The formal syntax makes no special provision for negative indices in
<a class="reference internal" href="../glossary.html#term-sequence"><span class="xref std std-term">sequences</span></a>. However, built-in sequences all provide a <a class="reference internal" href="datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>
method that interprets negative indices by adding the length of the sequence
to the index so that, for example, <code class="docutils literal notranslate"><span class="pre">x[-1]</span></code> selects the last item of <code class="docutils literal notranslate"><span class="pre">x</span></code>. The
resulting value must be a nonnegative integer less than the number of items in
the sequence, and the subscription selects the item whose index is that value
(counting from zero). Since the support for negative indices and slicing
occurs in the object's <a class="reference internal" href="datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> method, subclasses overriding
this method will need to explicitly add that support.</p>
<p id="index-44">A <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">string</span></code></a> is a special kind of sequence whose items are
<em>characters</em>. A character is not a separate data type but a
string of exactly one character.</p>
</section>
<section id="slicings">
<span id="id8"></span><h3><span class="section-number">6.3.3. </span>Slicings<a class="headerlink" href="#slicings" title="連結到這個標頭">¶</a></h3>
<p id="index-46"><span id="index-45"></span>A slicing selects a range of items in a sequence object (e.g., a string, tuple
or list). Slicings may be used as expressions or as targets in assignment or
<a class="reference internal" href="simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> statements. The syntax for a slicing:</p>
<pre>
<strong id="grammar-token-python-grammar-slicing">slicing</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a> "[" <a class="reference internal" href="#grammar-token-python-grammar-slice_list"><code class="xref docutils literal notranslate"><span class="pre">slice_list</span></code></a> "]"
<strong id="grammar-token-python-grammar-slice_list">slice_list</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-slice_item"><code class="xref docutils literal notranslate"><span class="pre">slice_item</span></code></a> ("," <a class="reference internal" href="#grammar-token-python-grammar-slice_item"><code class="xref docutils literal notranslate"><span class="pre">slice_item</span></code></a>)* [","]
<strong id="grammar-token-python-grammar-slice_item">slice_item</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-proper_slice"><code class="xref docutils literal notranslate"><span class="pre">proper_slice</span></code></a>
<strong id="grammar-token-python-grammar-proper_slice">proper_slice</strong> ::= [<a class="reference internal" href="#grammar-token-python-grammar-lower_bound"><code class="xref docutils literal notranslate"><span class="pre">lower_bound</span></code></a>] ":" [<a class="reference internal" href="#grammar-token-python-grammar-upper_bound"><code class="xref docutils literal notranslate"><span class="pre">upper_bound</span></code></a>] [ ":" [<a class="reference internal" href="#grammar-token-python-grammar-stride"><code class="xref docutils literal notranslate"><span class="pre">stride</span></code></a>] ]
<strong id="grammar-token-python-grammar-lower_bound">lower_bound</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
<strong id="grammar-token-python-grammar-upper_bound">upper_bound</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
<strong id="grammar-token-python-grammar-stride">stride</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
</pre>
<p>There is ambiguity in the formal syntax here: anything that looks like an
expression list also looks like a slice list, so any subscription can be
interpreted as a slicing. Rather than further complicating the syntax, this is
disambiguated by defining that in this case the interpretation as a subscription
takes priority over the interpretation as a slicing (this is the case if the
slice list contains no proper slice).</p>
<p id="index-47">The semantics for a slicing are as follows. The primary is indexed (using the
same <a class="reference internal" href="datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> method as
normal subscription) with a key that is constructed from the slice list, as
follows. If the slice list contains at least one comma, the key is a tuple
containing the conversion of the slice items; otherwise, the conversion of the
lone slice item is the key. The conversion of a slice item that is an
expression is that expression. The conversion of a proper slice is a slice
object (see section <a class="reference internal" href="datamodel.html#types"><span class="std std-ref">標準型別階層</span></a>) whose <a class="reference internal" href="../library/functions.html#slice.start" title="slice.start"><code class="xref py py-attr docutils literal notranslate"><span class="pre">start</span></code></a>,
<a class="reference internal" href="../library/functions.html#slice.stop" title="slice.stop"><code class="xref py py-attr docutils literal notranslate"><span class="pre">stop</span></code></a> and <a class="reference internal" href="../library/functions.html#slice.step" title="slice.step"><code class="xref py py-attr docutils literal notranslate"><span class="pre">step</span></code></a> attributes are the values of the
expressions given as lower bound, upper bound and stride, respectively,
substituting <code class="docutils literal notranslate"><span class="pre">None</span></code> for missing expressions.</p>
</section>
<section id="calls">
<span id="index-48"></span><span id="id9"></span><h3><span class="section-number">6.3.4. </span>Calls<a class="headerlink" href="#calls" title="連結到這個標頭">¶</a></h3>
<p>A call calls a callable object (e.g., a <a class="reference internal" href="../glossary.html#term-function"><span class="xref std std-term">function</span></a>) with a possibly empty
series of <a class="reference internal" href="../glossary.html#term-argument"><span class="xref std std-term">arguments</span></a>:</p>
<pre>
<strong id="grammar-token-python-grammar-call">call</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a> "(" [<a class="reference internal" href="#grammar-token-python-grammar-argument_list"><code class="xref docutils literal notranslate"><span class="pre">argument_list</span></code></a> [","] | <a class="reference internal" href="#grammar-token-python-grammar-comprehension"><code class="xref docutils literal notranslate"><span class="pre">comprehension</span></code></a>] ")"
<strong id="grammar-token-python-grammar-argument_list">argument_list</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-positional_arguments"><code class="xref docutils literal notranslate"><span class="pre">positional_arguments</span></code></a> ["," <a class="reference internal" href="#grammar-token-python-grammar-starred_and_keywords"><code class="xref docutils literal notranslate"><span class="pre">starred_and_keywords</span></code></a>]
["," <a class="reference internal" href="#grammar-token-python-grammar-keywords_arguments"><code class="xref docutils literal notranslate"><span class="pre">keywords_arguments</span></code></a>]
| <a class="reference internal" href="#grammar-token-python-grammar-starred_and_keywords"><code class="xref docutils literal notranslate"><span class="pre">starred_and_keywords</span></code></a> ["," <a class="reference internal" href="#grammar-token-python-grammar-keywords_arguments"><code class="xref docutils literal notranslate"><span class="pre">keywords_arguments</span></code></a>]
| <a class="reference internal" href="#grammar-token-python-grammar-keywords_arguments"><code class="xref docutils literal notranslate"><span class="pre">keywords_arguments</span></code></a>
<strong id="grammar-token-python-grammar-positional_arguments">positional_arguments</strong> ::= positional_item ("," positional_item)*
<strong id="grammar-token-python-grammar-positional_item">positional_item</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-assignment_expression"><code class="xref docutils literal notranslate"><span class="pre">assignment_expression</span></code></a> | "*" <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
<strong id="grammar-token-python-grammar-starred_and_keywords">starred_and_keywords</strong> ::= ("*" <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-keyword_item"><code class="xref docutils literal notranslate"><span class="pre">keyword_item</span></code></a>)
("," "*" <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> | "," <a class="reference internal" href="#grammar-token-python-grammar-keyword_item"><code class="xref docutils literal notranslate"><span class="pre">keyword_item</span></code></a>)*
<strong id="grammar-token-python-grammar-keywords_arguments">keywords_arguments</strong> ::= (<a class="reference internal" href="#grammar-token-python-grammar-keyword_item"><code class="xref docutils literal notranslate"><span class="pre">keyword_item</span></code></a> | "**" <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>)
("," <a class="reference internal" href="#grammar-token-python-grammar-keyword_item"><code class="xref docutils literal notranslate"><span class="pre">keyword_item</span></code></a> | "," "**" <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>)*
<strong id="grammar-token-python-grammar-keyword_item">keyword_item</strong> ::= <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> "=" <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
</pre>
<p>An optional trailing comma may be present after the positional and keyword arguments
but does not affect the semantics.</p>
<p id="index-49">The primary must evaluate to a callable object (user-defined functions, built-in
functions, methods of built-in objects, class objects, methods of class
instances, and all objects having a <a class="reference internal" href="datamodel.html#object.__call__" title="object.__call__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__call__()</span></code></a> method are callable). All
argument expressions are evaluated before the call is attempted. Please refer
to section <a class="reference internal" href="compound_stmts.html#function"><span class="std std-ref">函式定義</span></a> for the syntax of formal <a class="reference internal" href="../glossary.html#term-parameter"><span class="xref std std-term">parameter</span></a> lists.</p>
<p>If keyword arguments are present, they are first converted to positional
arguments, as follows. First, a list of unfilled slots is created for the
formal parameters. If there are N positional arguments, they are placed in the
first N slots. Next, for each keyword argument, the identifier is used to
determine the corresponding slot (if the identifier is the same as the first
formal parameter name, the first slot is used, and so on). If the slot is
already filled, a <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception is raised. Otherwise, the
argument is placed in the slot, filling it (even if the expression is
<code class="docutils literal notranslate"><span class="pre">None</span></code>, it fills the slot). When all arguments have been processed, the slots
that are still unfilled are filled with the corresponding default value from the
function definition. (Default values are calculated, once, when the function is
defined; thus, a mutable object such as a list or dictionary used as default
value will be shared by all calls that don't specify an argument value for the
corresponding slot; this should usually be avoided.) If there are any unfilled
slots for which no default value is specified, a <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception is
raised. Otherwise, the list of filled slots is used as the argument list for
the call.</p>
<div class="impl-detail compound">
<p><strong>CPython 實作細節:</strong> An implementation may provide built-in functions whose positional parameters
do not have names, even if they are 'named' for the purpose of documentation,
and which therefore cannot be supplied by keyword. In CPython, this is the
case for functions implemented in C that use <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> to
parse their arguments.</p>