-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpressions.html
More file actions
1569 lines (1539 loc) · 178 KB
/
expressions.html
File metadata and controls
1569 lines (1539 loc) · 178 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_TW">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>6. Expressions — Python 3.7.0 說明文件</title>
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/translations.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="在 Python 3.7.0 說明文件 中搜尋"
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="Copyright" href="../copyright.html" />
<link rel="next" title="7. Simple statements" href="simple_stmts.html" />
<link rel="prev" title="5. The import system" href="import.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/reference/expressions.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<h3>瀏覽</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
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. Simple statements"
accesskey="N">下一頁</a> |</li>
<li class="right" >
<a href="import.html" title="5. The import system"
accesskey="P">上一頁</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> »</li>
<li>
<span class="language_switcher_placeholder">zh_TW</span>
<span class="version_switcher_placeholder">3.7.0</span>
<a href="../index.html">Documentation </a> »
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> »</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="expressions">
<span id="id1"></span><h1>6. Expressions<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-name">name</strong> ::= <code class="xref docutils literal notranslate"><span class="pre">othername</span></code>
</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>
<div class="section" id="arithmetic-conversions">
<span id="conversions"></span><h2>6.1. 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>If either argument is a complex number, the other is converted to complex;</li>
<li>otherwise, if either argument is a floating point number, the other is
converted to floating point;</li>
<li>otherwise, both must be integers and no conversion is necessary.</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>
</div>
<div class="section" id="atoms">
<span id="id2"></span><h2>6.2. 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-atom">atom </strong> ::= <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> | <a class="reference internal" href="#grammar-token-literal"><code class="xref docutils literal notranslate"><span class="pre">literal</span></code></a> | <a class="reference internal" href="#grammar-token-enclosure"><code class="xref docutils literal notranslate"><span class="pre">enclosure</span></code></a>
<strong id="grammar-token-enclosure">enclosure</strong> ::= <a class="reference internal" href="#grammar-token-parenth_form"><code class="xref docutils literal notranslate"><span class="pre">parenth_form</span></code></a> | <a class="reference internal" href="#grammar-token-list_display"><code class="xref docutils literal notranslate"><span class="pre">list_display</span></code></a> | <a class="reference internal" href="#grammar-token-dict_display"><code class="xref docutils literal notranslate"><span class="pre">dict_display</span></code></a> | <a class="reference internal" href="#grammar-token-set_display"><code class="xref docutils literal notranslate"><span class="pre">set_display</span></code></a>
| <a class="reference internal" href="#grammar-token-generator_expression"><code class="xref docutils literal notranslate"><span class="pre">generator_expression</span></code></a> | <a class="reference internal" href="#grammar-token-yield_atom"><code class="xref docutils literal notranslate"><span class="pre">yield_atom</span></code></a>
</pre>
<div class="section" id="atom-identifiers">
<span id="identifiers-names"></span><h3>6.2.1. 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>
<p id="index-5"><strong>Private name mangling:</strong> 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.
Private names are transformed to a longer form before code is generated for
them. The transformation inserts the class name, with leading underscores
removed and a single underscore inserted, in front of the name. For example,
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">Ham</span></code> will be transformed
to <code class="docutils literal notranslate"><span class="pre">_Ham__spam</span></code>. This transformation is independent of the syntactical
context in which the identifier is used. If the transformed name is extremely
long (longer than 255 characters), implementation defined truncation may happen.
If the class name consists only of underscores, no transformation is done.</p>
</div>
<div class="section" id="literals">
<span id="atom-literals"></span><h3>6.2.2. 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-literal">literal</strong> ::= <a class="reference internal" href="lexical_analysis.html#grammar-token-stringliteral"><code class="xref docutils literal notranslate"><span class="pre">stringliteral</span></code></a> | <a class="reference internal" href="lexical_analysis.html#grammar-token-bytesliteral"><code class="xref docutils literal notranslate"><span class="pre">bytesliteral</span></code></a>
| <a class="reference internal" href="lexical_analysis.html#grammar-token-integer"><code class="xref docutils literal notranslate"><span class="pre">integer</span></code></a> | <a class="reference internal" href="lexical_analysis.html#grammar-token-floatnumber"><code class="xref docutils literal notranslate"><span class="pre">floatnumber</span></code></a> | <a class="reference internal" href="lexical_analysis.html#grammar-token-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>
</div>
<div class="section" id="parenthesized-forms">
<span id="parenthesized"></span><h3>6.2.3. 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-parenth_form">parenth_form</strong> ::= "(" [<a class="reference internal" href="#grammar-token-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 rules 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 operator. 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>
</div>
<div class="section" id="displays-for-lists-sets-and-dictionaries">
<span id="comprehensions"></span><h3>6.2.4. Displays for lists, sets and dictionaries<a class="headerlink" href="#displays-for-lists-sets-and-dictionaries" title="本標題的永久連結">¶</a></h3>
<p>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>either the container contents are listed explicitly, or</li>
<li>they are computed via a set of looping and filtering instructions, called a
<em class="dfn">comprehension</em>.</li>
</ul>
<p>Common syntax elements for comprehensions are:</p>
<pre>
<strong id="grammar-token-comprehension">comprehension</strong> ::= <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> <a class="reference internal" href="#grammar-token-comp_for"><code class="xref docutils literal notranslate"><span class="pre">comp_for</span></code></a>
<strong id="grammar-token-comp_for">comp_for </strong> ::= ["async"] "for" <a class="reference internal" href="simple_stmts.html#grammar-token-target_list"><code class="xref docutils literal notranslate"><span class="pre">target_list</span></code></a> "in" <a class="reference internal" href="#grammar-token-or_test"><code class="xref docutils literal notranslate"><span class="pre">or_test</span></code></a> [<a class="reference internal" href="#grammar-token-comp_iter"><code class="xref docutils literal notranslate"><span class="pre">comp_iter</span></code></a>]
<strong id="grammar-token-comp_iter">comp_iter </strong> ::= <a class="reference internal" href="#grammar-token-comp_for"><code class="xref docutils literal notranslate"><span class="pre">comp_for</span></code></a> | <a class="reference internal" href="#grammar-token-comp_if"><code class="xref docutils literal notranslate"><span class="pre">comp_if</span></code></a>
<strong id="grammar-token-comp_if">comp_if </strong> ::= "if" <a class="reference internal" href="#grammar-token-expression_nocond"><code class="xref docutils literal notranslate"><span class="pre">expression_nocond</span></code></a> [<a class="reference internal" href="#grammar-token-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
<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> clause and zero or more <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 <a class="reference internal" href="compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> clauses.
In this case, the elements of the new container are those that would be produced
by considering each of the <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 <a class="reference internal" href="compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> 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 <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> 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 <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> clause is evaluated
directly in the enclosing scope and then passed as an argument to the implictly
nested scope. Subsequent <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> clauses and any filter condition in the
leftmost <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> 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 (in Python 3.7, such expressions emit <a class="reference internal" href="../library/exceptions.html#DeprecationWarning" title="DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a>
when compiled, in Python 3.8+ they will emit <a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a>).</p>
<p>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 <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>
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 <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 may consist of 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 <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> clause following the leading
expression, may contain additional <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 <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>
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.
If a comprehension contains either <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> 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 comprehension</em>. An asynchronous comprehension may
suspend the execution of the coroutine function in which it appears.
See also <span class="target" id="index-11"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0530"><strong>PEP 530</strong></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">3.6 版新加入: </span>Asynchronous comprehensions were introduced.</p>
</div>
<div class="deprecated">
<p><span class="versionmodified">3.7 版後已棄用: </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> deprecated in the implicitly nested scope.</p>
</div>
</div>
<div class="section" id="list-displays">
<span id="lists"></span><h3>6.2.5. List displays<a class="headerlink" href="#list-displays" title="本標題的永久連結">¶</a></h3>
<p id="index-12">A list display is a possibly empty series of expressions enclosed in square
brackets:</p>
<pre>
<strong id="grammar-token-list_display">list_display</strong> ::= "[" [<a class="reference internal" href="#grammar-token-starred_list"><code class="xref docutils literal notranslate"><span class="pre">starred_list</span></code></a> | <a class="reference internal" href="#grammar-token-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>
</div>
<div class="section" id="set-displays">
<span id="set"></span><h3>6.2.6. Set displays<a class="headerlink" href="#set-displays" title="本標題的永久連結">¶</a></h3>
<p id="index-13">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-set_display">set_display</strong> ::= "{" (<a class="reference internal" href="#grammar-token-starred_list"><code class="xref docutils literal notranslate"><span class="pre">starred_list</span></code></a> | <a class="reference internal" href="#grammar-token-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>
</div>
<div class="section" id="dictionary-displays">
<span id="dict"></span><h3>6.2.7. Dictionary displays<a class="headerlink" href="#dictionary-displays" title="本標題的永久連結">¶</a></h3>
<p id="index-14">A dictionary display is a possibly empty series of key/datum pairs enclosed in
curly braces:</p>
<pre>
<strong id="grammar-token-dict_display">dict_display </strong> ::= "{" [<a class="reference internal" href="#grammar-token-key_datum_list"><code class="xref docutils literal notranslate"><span class="pre">key_datum_list</span></code></a> | <a class="reference internal" href="#grammar-token-dict_comprehension"><code class="xref docutils literal notranslate"><span class="pre">dict_comprehension</span></code></a>] "}"
<strong id="grammar-token-key_datum_list">key_datum_list </strong> ::= <a class="reference internal" href="#grammar-token-key_datum"><code class="xref docutils literal notranslate"><span class="pre">key_datum</span></code></a> ("," <a class="reference internal" href="#grammar-token-key_datum"><code class="xref docutils literal notranslate"><span class="pre">key_datum</span></code></a>)* [","]
<strong id="grammar-token-key_datum">key_datum </strong> ::= <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> ":" <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> | "**" <a class="reference internal" href="#grammar-token-or_expr"><code class="xref docutils literal notranslate"><span class="pre">or_expr</span></code></a>
<strong id="grammar-token-dict_comprehension">dict_comprehension</strong> ::= <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> ":" <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> <a class="reference internal" href="#grammar-token-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 key/datum pairs 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 datum. This means
that you can specify the same key multiple times in the key/datum list, and the
final dictionary’s value for that key will be the last one given.</p>
<p id="index-15">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 key/datum pairs and earlier dictionary unpackings.</p>
<div class="versionadded">
<p><span class="versionmodified">3.5 版新加入: </span>Unpacking into dictionary displays, originally proposed by <span class="target" id="index-16"></span><a class="pep reference external" href="https://www.python.org/dev/peps/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-17">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">The standard type hierarchy</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
datum (textually rightmost in the display) stored for a given key value
prevails.</p>
</div>
<div class="section" id="generator-expressions">
<span id="genexpr"></span><h3>6.2.8. Generator expressions<a class="headerlink" href="#generator-expressions" title="本標題的永久連結">¶</a></h3>
<p id="index-18">A generator expression is a compact generator notation in parentheses:</p>
<pre>
<strong id="grammar-token-generator_expression">generator_expression</strong> ::= "(" <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> <a class="reference internal" href="#grammar-token-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 <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> 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 <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> clauses and any filter condition in the leftmost
<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> 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 (in Python 3.7, such expressions emit
<a class="reference internal" href="../library/exceptions.html#DeprecationWarning" title="DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a> when compiled, in Python 3.8+ they will emit
<a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a>).</p>
<p>If a generator expression contains either <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>
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">3.6 版新加入: </span>Asynchronous generator expressions were introduced.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">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="deprecated">
<p><span class="versionmodified">3.7 版後已棄用: </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> deprecated in the implicitly nested scope.</p>
</div>
</div>
<div class="section" id="yield-expressions">
<span id="yieldexpr"></span><h3>6.2.9. Yield expressions<a class="headerlink" href="#yield-expressions" title="本標題的永久連結">¶</a></h3>
<pre id="index-19">
<strong id="grammar-token-yield_atom">yield_atom </strong> ::= "(" <a class="reference internal" href="#grammar-token-yield_expression"><code class="xref docutils literal notranslate"><span class="pre">yield_expression</span></code></a> ")"
<strong id="grammar-token-yield_expression">yield_expression</strong> ::= "yield" [<a class="reference internal" href="#grammar-token-expression_list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a> | "from" <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</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,
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. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</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="nf">agen</span><span class="p">():</span> <span class="c1"># defines an asynchronous generator function (PEP 525)</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 (in Python 3.7, such
expressions emit <a class="reference internal" href="../library/exceptions.html#DeprecationWarning" title="DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a> when compiled, in Python 3.8+
they will emit <a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a>)..</p>
<div class="deprecated">
<p><span class="versionmodified">3.7 版後已棄用: </span>Yield expressions deprecated 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">Asynchronous generator functions</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-expression_list"><code class="xref std std-token docutils literal notranslate"><span class="pre">expression_list</span></code></a> to the generator’s
caller. 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-20">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>When <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span> <span class="pre"><expr></span></code> is used, it treats the supplied expression as
a subiterator. All values produced by that subiterator 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 <code class="xref py py-attr docutils literal notranslate"><span class="pre">value</span></code>
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 sub-iterator is a generator
(by returning a value from the sub-generator).</p>
<blockquote>
<div><div class="versionchanged">
<p><span class="versionmodified">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>
</div></blockquote>
<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="first admonition-title">也參考</p>
<dl class="last docutils">
<dt><span class="target" id="index-21"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0255"><strong>PEP 255</strong></a> - Simple Generators</dt>
<dd>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.</dd>
<dt><span class="target" id="index-22"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0342"><strong>PEP 342</strong></a> - Coroutines via Enhanced Generators</dt>
<dd>The proposal to enhance the API and syntax of generators, making them
usable as simple coroutines.</dd>
<dt><span class="target" id="index-23"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0380"><strong>PEP 380</strong></a> - Syntax for Delegating to a Subgenerator</dt>
<dd>The proposal to introduce the <code class="xref std std-token docutils literal notranslate"><span class="pre">yield_from</span></code> syntax, making delegation
to sub-generators easy.</dd>
</dl>
</div>
<div class="section" id="generator-iterator-methods">
<span id="generator-methods"></span><span id="index-24"></span><h4>6.2.9.1. 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>
<span class="target" id="index-25"></span><dl class="method">
<dt id="generator.__next__">
<code class="descclassname">generator.</code><code class="descname">__next__</code><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-expression_list"><code class="xref std std-token docutils literal notranslate"><span class="pre">expression_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="method">
<dt id="generator.send">
<code class="descclassname">generator.</code><code class="descname">send</code><span class="sig-paren">(</span><em>value</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="method">
<dt id="generator.throw">
<code class="descclassname">generator.</code><code class="descname">throw</code><span class="sig-paren">(</span><em>type</em><span class="optional">[</span>, <em>value</em><span class="optional">[</span>, <em>traceback</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#generator.throw" title="本定義的永久連結">¶</a></dt>
<dd><p>Raises an exception of type <code class="docutils literal notranslate"><span class="pre">type</span></code> 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>
</dd></dl>
<span class="target" id="index-26"></span><dl class="method">
<dt id="generator.close">
<code class="descclassname">generator.</code><code class="descname">close</code><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 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), close
returns to its caller. 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. <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> does nothing if the generator
has already exited due to an exception or normal exit.</p>
</dd></dl>
</div>
<div class="section" id="examples">
<span id="index-27"></span><h4>6.2.9.2. Examples<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="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>
</div>
<div class="section" id="asynchronous-generator-functions">
<span id="id3"></span><h4>6.2.9.3. Asynchronous generator functions<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 a
<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-expression_list"><code class="xref std std-token docutils literal notranslate"><span class="pre">expression_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>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 <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 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 <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>To take care of finalization, 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="reference external" href="https://github.com/python/cpython/tree/3.7/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>
</div>
<div class="section" id="asynchronous-generator-iterator-methods">
<span id="asynchronous-generator-methods"></span><span id="index-28"></span><h4>6.2.9.4. 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>
<span class="target" id="index-29"></span><dl class="method">
<dt id="agen.__anext__">
<em class="property">coroutine </em><code class="descclassname">agen.</code><code class="descname">__anext__</code><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 a <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-expression_list"><code class="xref std std-token docutils literal notranslate"><span class="pre">expression_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 an
<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="method">
<dt id="agen.asend">
<em class="property">coroutine </em><code class="descclassname">agen.</code><code class="descname">asend</code><span class="sig-paren">(</span><em>value</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="method">
<dt id="agen.athrow">
<em class="property">coroutine </em><code class="descclassname">agen.</code><code class="descname">athrow</code><span class="sig-paren">(</span><em>type</em><span class="optional">[</span>, <em>value</em><span class="optional">[</span>, <em>traceback</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#agen.athrow" title="本定義的永久連結">¶</a></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, an <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>
</dd></dl>
<span class="target" id="index-30"></span><dl class="method">
<dt id="agen.aclose">
<em class="property">coroutine </em><code class="descclassname">agen.</code><code class="descname">aclose</code><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>
</div>
</div>
</div>
<div class="section" id="primaries">
<span id="id4"></span><h2>6.3. Primaries<a class="headerlink" href="#primaries" title="本標題的永久連結">¶</a></h2>
<p id="index-31">Primaries represent the most tightly bound operations of the language. Their
syntax is:</p>
<pre>
<strong id="grammar-token-primary">primary</strong> ::= <a class="reference internal" href="#grammar-token-atom"><code class="xref docutils literal notranslate"><span class="pre">atom</span></code></a> | <a class="reference internal" href="#grammar-token-attributeref"><code class="xref docutils literal notranslate"><span class="pre">attributeref</span></code></a> | <a class="reference internal" href="#grammar-token-subscription"><code class="xref docutils literal notranslate"><span class="pre">subscription</span></code></a> | <a class="reference internal" href="#grammar-token-slicing"><code class="xref docutils literal notranslate"><span class="pre">slicing</span></code></a> | <a class="reference internal" href="#grammar-token-call"><code class="xref docutils literal notranslate"><span class="pre">call</span></code></a>
</pre>
<div class="section" id="attribute-references">
<span id="id5"></span><h3>6.3.1. Attribute references<a class="headerlink" href="#attribute-references" title="本標題的永久連結">¶</a></h3>
<p id="index-32">An attribute reference is a primary followed by a period and a name:</p>
<pre>
<strong id="grammar-token-attributeref">attributeref</strong> ::= <a class="reference internal" href="#grammar-token-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a> "." <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>
</pre>
<p id="index-33">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. This production can be customized by
overriding 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. If this attribute is not available,
the exception <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. Otherwise, the type and value of
the object produced is determined by the object. Multiple evaluations of the
same attribute reference may yield different objects.</p>
</div>
<div class="section" id="subscriptions">
<span id="id6"></span><h3>6.3.2. Subscriptions<a class="headerlink" href="#subscriptions" title="本標題的永久連結">¶</a></h3>
<span class="target" id="index-34"></span><p id="index-35">A subscription selects an item of a sequence (string, tuple or list) or mapping
(dictionary) object:</p>
<pre>
<strong id="grammar-token-subscription">subscription</strong> ::= <a class="reference internal" href="#grammar-token-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a> "[" <a class="reference internal" href="#grammar-token-expression_list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a> "]"
</pre>
<p>The primary must evaluate to an object that supports subscription (lists or
dictionaries for example). User-defined objects can support subscription by
defining 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.</p>
<p>For built-in objects, there are two types of objects that support subscription:</p>
<p>If the primary is a mapping, 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. (The expression list is a
tuple except if it has exactly one item.)</p>
<p>If the primary is a sequence, the expression list must evaluate to an integer
or a slice (as discussed in the following section).</p>
<p>The formal syntax makes no special provision for negative indices in
sequences; 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 <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-36">A string’s items are characters. A character is not a separate data type but a
string of exactly one character.</p>
</div>
<div class="section" id="slicings">
<span id="id7"></span><h3>6.3.3. Slicings<a class="headerlink" href="#slicings" title="本標題的永久連結">¶</a></h3>
<span class="target" id="index-37"></span><p id="index-38">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-slicing">slicing </strong> ::= <a class="reference internal" href="#grammar-token-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a> "[" <a class="reference internal" href="#grammar-token-slice_list"><code class="xref docutils literal notranslate"><span class="pre">slice_list</span></code></a> "]"
<strong id="grammar-token-slice_list">slice_list </strong> ::= <a class="reference internal" href="#grammar-token-slice_item"><code class="xref docutils literal notranslate"><span class="pre">slice_item</span></code></a> ("," <a class="reference internal" href="#grammar-token-slice_item"><code class="xref docutils literal notranslate"><span class="pre">slice_item</span></code></a>)* [","]
<strong id="grammar-token-slice_item">slice_item </strong> ::= <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> | <a class="reference internal" href="#grammar-token-proper_slice"><code class="xref docutils literal notranslate"><span class="pre">proper_slice</span></code></a>
<strong id="grammar-token-proper_slice">proper_slice</strong> ::= [<a class="reference internal" href="#grammar-token-lower_bound"><code class="xref docutils literal notranslate"><span class="pre">lower_bound</span></code></a>] ":" [<a class="reference internal" href="#grammar-token-upper_bound"><code class="xref docutils literal notranslate"><span class="pre">upper_bound</span></code></a>] [ ":" [<a class="reference internal" href="#grammar-token-stride"><code class="xref docutils literal notranslate"><span class="pre">stride</span></code></a>] ]
<strong id="grammar-token-lower_bound">lower_bound </strong> ::= <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
<strong id="grammar-token-upper_bound">upper_bound </strong> ::= <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
<strong id="grammar-token-stride">stride </strong> ::= <a class="reference internal" href="#grammar-token-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-39">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">The standard type hierarchy</span></a>) whose <code class="xref py py-attr docutils literal notranslate"><span class="pre">start</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">stop</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">step</span></code> 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>
</div>
<div class="section" id="calls">
<span id="index-40"></span><span id="id8"></span><h3>6.3.4. 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-call">call </strong> ::= <a class="reference internal" href="#grammar-token-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a> "(" [<a class="reference internal" href="#grammar-token-argument_list"><code class="xref docutils literal notranslate"><span class="pre">argument_list</span></code></a> [","] | <a class="reference internal" href="#grammar-token-comprehension"><code class="xref docutils literal notranslate"><span class="pre">comprehension</span></code></a>] ")"
<strong id="grammar-token-argument_list">argument_list </strong> ::= <a class="reference internal" href="#grammar-token-positional_arguments"><code class="xref docutils literal notranslate"><span class="pre">positional_arguments</span></code></a> ["," <a class="reference internal" href="#grammar-token-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-keywords_arguments"><code class="xref docutils literal notranslate"><span class="pre">keywords_arguments</span></code></a>]
| <a class="reference internal" href="#grammar-token-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-keywords_arguments"><code class="xref docutils literal notranslate"><span class="pre">keywords_arguments</span></code></a>]
| <a class="reference internal" href="#grammar-token-keywords_arguments"><code class="xref docutils literal notranslate"><span class="pre">keywords_arguments</span></code></a>
<strong id="grammar-token-positional_arguments">positional_arguments</strong> ::= ["*"] <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> ("," ["*"] <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>)*
<strong id="grammar-token-starred_and_keywords">starred_and_keywords</strong> ::= ("*" <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> | <a class="reference internal" href="#grammar-token-keyword_item"><code class="xref docutils literal notranslate"><span class="pre">keyword_item</span></code></a>)
("," "*" <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> | "," <a class="reference internal" href="#grammar-token-keyword_item"><code class="xref docutils literal notranslate"><span class="pre">keyword_item</span></code></a>)*
<strong id="grammar-token-keywords_arguments">keywords_arguments </strong> ::= (<a class="reference internal" href="#grammar-token-keyword_item"><code class="xref docutils literal notranslate"><span class="pre">keyword_item</span></code></a> | "**" <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>)
("," <a class="reference internal" href="#grammar-token-keyword_item"><code class="xref docutils literal notranslate"><span class="pre">keyword_item</span></code></a> | "," "**" <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>)*
<strong id="grammar-token-keyword_item">keyword_item </strong> ::= <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> "=" <a class="reference internal" href="#grammar-token-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-41">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">Function definitions</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 value of
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 implementation detail:</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>
</div>
<p>If there are more positional arguments than there are formal parameter slots, 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, unless a formal parameter using the syntax
<code class="docutils literal notranslate"><span class="pre">*identifier</span></code> is present; in this case, that formal parameter receives a tuple
containing the excess positional arguments (or an empty tuple if there were no
excess positional arguments).</p>
<p>If any keyword argument does not correspond to a formal parameter name, 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, unless a formal parameter using the syntax
<code class="docutils literal notranslate"><span class="pre">**identifier</span></code> is present; in this case, that formal parameter receives a
dictionary containing the excess keyword arguments (using the keywords as keys
and the argument values as corresponding values), or a (new) empty dictionary if
there were no excess keyword arguments.</p>
<p id="index-42">If the syntax <code class="docutils literal notranslate"><span class="pre">*expression</span></code> appears in the function call, <code class="docutils literal notranslate"><span class="pre">expression</span></code> must
evaluate to an <a class="reference internal" href="../glossary.html#term-iterable"><span class="xref std std-term">iterable</span></a>. Elements from these iterables are
treated as if they were additional positional arguments. For the call
<code class="docutils literal notranslate"><span class="pre">f(x1,</span> <span class="pre">x2,</span> <span class="pre">*y,</span> <span class="pre">x3,</span> <span class="pre">x4)</span></code>, if <em>y</em> evaluates to a sequence <em>y1</em>, …, <em>yM</em>,
this is equivalent to a call with M+4 positional arguments <em>x1</em>, <em>x2</em>,
<em>y1</em>, …, <em>yM</em>, <em>x3</em>, <em>x4</em>.</p>
<p>A consequence of this is that although the <code class="docutils literal notranslate"><span class="pre">*expression</span></code> syntax may appear
<em>after</em> explicit keyword arguments, it is processed <em>before</em> the
keyword arguments (and any <code class="docutils literal notranslate"><span class="pre">**expression</span></code> arguments – see below). So:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">>>> </span><span class="n">f</span><span class="p">(</span><span class="n">b</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="o">*</span><span class="p">(</span><span class="mi">2</span><span class="p">,))</span>
<span class="go">2 1</span>
<span class="gp">>>> </span><span class="n">f</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="o">*</span><span class="p">(</span><span class="mi">2</span><span class="p">,))</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
<span class="gr">TypeError</span>: <span class="n">f() got multiple values for keyword argument 'a'</span>
<span class="gp">>>> </span><span class="n">f</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="o">*</span><span class="p">(</span><span class="mi">2</span><span class="p">,))</span>
<span class="go">1 2</span>
</pre></div>
</div>
<p>It is unusual for both keyword arguments and the <code class="docutils literal notranslate"><span class="pre">*expression</span></code> syntax to be
used in the same call, so in practice this confusion does not arise.</p>
<p id="index-43">If the syntax <code class="docutils literal notranslate"><span class="pre">**expression</span></code> appears in the function call, <code class="docutils literal notranslate"><span class="pre">expression</span></code> must
evaluate to a <a class="reference internal" href="../glossary.html#term-mapping"><span class="xref std std-term">mapping</span></a>, the contents of which are treated as
additional keyword arguments. If a keyword is already present
(as an explicit keyword argument, or from another unpacking),
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.</p>
<p>Formal parameters using the syntax <code class="docutils literal notranslate"><span class="pre">*identifier</span></code> or <code class="docutils literal notranslate"><span class="pre">**identifier</span></code> cannot be
used as positional argument slots or as keyword argument names.</p>
<div class="versionchanged">
<p><span class="versionmodified">3.5 版更變: </span>Function calls accept any number of <code class="docutils literal notranslate"><span class="pre">*</span></code> and <code class="docutils literal notranslate"><span class="pre">**</span></code> unpackings,
positional arguments may follow iterable unpackings (<code class="docutils literal notranslate"><span class="pre">*</span></code>),
and keyword arguments may follow dictionary unpackings (<code class="docutils literal notranslate"><span class="pre">**</span></code>).
Originally proposed by <span class="target" id="index-44"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0448"><strong>PEP 448</strong></a>.</p>
</div>
<p>A call always returns some value, possibly <code class="docutils literal notranslate"><span class="pre">None</span></code>, unless it raises an
exception. How this value is computed depends on the type of the callable
object.</p>
<p>If it is—</p>
<dl class="docutils">
<dt>a user-defined function:</dt>
<dd><p class="first last" id="index-45">The code block for the function is executed, passing it the argument list. The
first thing the code block will do is bind the formal parameters to the
arguments; this is described in section <a class="reference internal" href="compound_stmts.html#function"><span class="std std-ref">Function definitions</span></a>. When the code block
executes a <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement, this specifies the return value of the
function call.</p>
</dd>
<dt>a built-in function or method:</dt>
<dd><p class="first last" id="index-46">The result is up to the interpreter; see <a class="reference internal" href="../library/functions.html#built-in-funcs"><span class="std std-ref">內建函式</span></a> for the
descriptions of built-in functions and methods.</p>
</dd>
<dt>a class object:</dt>
<dd><p class="first last" id="index-47">A new instance of that class is returned.</p>
</dd>
<dt>a class instance method:</dt>
<dd><p class="first last" id="index-48">The corresponding user-defined function is called, with an argument list that is
one longer than the argument list of the call: the instance becomes the first
argument.</p>
</dd>
<dt>a class instance:</dt>
<dd><p class="first last" id="index-49">The class must define 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; the effect is then the same as
if that method was called.</p>
</dd>
</dl>
</div>
</div>
<div class="section" id="await-expression">
<span id="await"></span><h2>6.4. Await expression<a class="headerlink" href="#await-expression" title="本標題的永久連結">¶</a></h2>
<p>Suspend the execution of <a class="reference internal" href="../glossary.html#term-coroutine"><span class="xref std std-term">coroutine</span></a> on an <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> object.
Can only be used inside a <a class="reference internal" href="../glossary.html#term-coroutine-function"><span class="xref std std-term">coroutine function</span></a>.</p>
<pre>
<strong id="grammar-token-await_expr">await_expr</strong> ::= "await" <a class="reference internal" href="#grammar-token-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a>
</pre>
<div class="versionadded">
<p><span class="versionmodified">3.5 版新加入.</span></p>
</div>
</div>
<div class="section" id="the-power-operator">
<span id="power"></span><h2>6.5. The power operator<a class="headerlink" href="#the-power-operator" title="本標題的永久連結">¶</a></h2>
<p>The power operator binds more tightly than unary operators on its left; it binds
less tightly than unary operators on its right. The syntax is:</p>
<pre>
<strong id="grammar-token-power">power</strong> ::= (<a class="reference internal" href="#grammar-token-await_expr"><code class="xref docutils literal notranslate"><span class="pre">await_expr</span></code></a> | <a class="reference internal" href="#grammar-token-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a>) ["**" <a class="reference internal" href="#grammar-token-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a>]
</pre>
<p>Thus, in an unparenthesized sequence of power and unary operators, the operators
are evaluated from right to left (this does not constrain the evaluation order
for the operands): <code class="docutils literal notranslate"><span class="pre">-1**2</span></code> results in <code class="docutils literal notranslate"><span class="pre">-1</span></code>.</p>
<p>The power operator has the same semantics as the built-in <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal notranslate"><span class="pre">pow()</span></code></a> function,
when called with two arguments: it yields its left argument raised to the power
of its right argument. The numeric arguments are first converted to a common
type, and the result is of that type.</p>
<p>For int operands, the result has the same type as the operands unless the second
argument is negative; in that case, all arguments are converted to float and a
float result is delivered. For example, <code class="docutils literal notranslate"><span class="pre">10**2</span></code> returns <code class="docutils literal notranslate"><span class="pre">100</span></code>, but
<code class="docutils literal notranslate"><span class="pre">10**-2</span></code> returns <code class="docutils literal notranslate"><span class="pre">0.01</span></code>.</p>
<p>Raising <code class="docutils literal notranslate"><span class="pre">0.0</span></code> to a negative power results in a <a class="reference internal" href="../library/exceptions.html#ZeroDivisionError" title="ZeroDivisionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZeroDivisionError</span></code></a>.
Raising a negative number to a fractional power results in a <a class="reference internal" href="../library/functions.html#complex" title="complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">complex</span></code></a>
number. (In earlier versions it raised 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>.)</p>
</div>
<div class="section" id="unary-arithmetic-and-bitwise-operations">
<span id="unary"></span><h2>6.6. Unary arithmetic and bitwise operations<a class="headerlink" href="#unary-arithmetic-and-bitwise-operations" title="本標題的永久連結">¶</a></h2>
<p id="index-50">All unary arithmetic and bitwise operations have the same priority:</p>
<pre>
<strong id="grammar-token-u_expr">u_expr</strong> ::= <a class="reference internal" href="#grammar-token-power"><code class="xref docutils literal notranslate"><span class="pre">power</span></code></a> | "-" <a class="reference internal" href="#grammar-token-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a> | "+" <a class="reference internal" href="#grammar-token-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a> | "~" <a class="reference internal" href="#grammar-token-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a>
</pre>
<p id="index-51">The unary <code class="docutils literal notranslate"><span class="pre">-</span></code> (minus) operator yields the negation of its numeric argument.</p>
<p id="index-52">The unary <code class="docutils literal notranslate"><span class="pre">+</span></code> (plus) operator yields its numeric argument unchanged.</p>
<p id="index-53">The unary <code class="docutils literal notranslate"><span class="pre">~</span></code> (invert) operator yields the bitwise inversion of its integer
argument. The bitwise inversion of <code class="docutils literal notranslate"><span class="pre">x</span></code> is defined as <code class="docutils literal notranslate"><span class="pre">-(x+1)</span></code>. It only
applies to integral numbers.</p>
<p id="index-54">In all three cases, if the argument does not have the proper type, 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.</p>
</div>
<div class="section" id="binary-arithmetic-operations">
<span id="binary"></span><h2>6.7. Binary arithmetic operations<a class="headerlink" href="#binary-arithmetic-operations" title="本標題的永久連結">¶</a></h2>
<p id="index-55">The binary arithmetic operations have the conventional priority levels. Note
that some of these operations also apply to certain non-numeric types. Apart
from the power operator, there are only two levels, one for multiplicative
operators and one for additive operators:</p>
<pre>
<strong id="grammar-token-m_expr">m_expr</strong> ::= <a class="reference internal" href="#grammar-token-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a> | <a class="reference internal" href="#grammar-token-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> "*" <a class="reference internal" href="#grammar-token-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a> | <a class="reference internal" href="#grammar-token-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> "@" <a class="reference internal" href="#grammar-token-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> |
<a class="reference internal" href="#grammar-token-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> "//" <a class="reference internal" href="#grammar-token-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a> | <a class="reference internal" href="#grammar-token-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> "/" <a class="reference internal" href="#grammar-token-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a> |
<a class="reference internal" href="#grammar-token-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> "%" <a class="reference internal" href="#grammar-token-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a>
<strong id="grammar-token-a_expr">a_expr</strong> ::= <a class="reference internal" href="#grammar-token-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> | <a class="reference internal" href="#grammar-token-a_expr"><code class="xref docutils literal notranslate"><span class="pre">a_expr</span></code></a> "+" <a class="reference internal" href="#grammar-token-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> | <a class="reference internal" href="#grammar-token-a_expr"><code class="xref docutils literal notranslate"><span class="pre">a_expr</span></code></a> "-" <a class="reference internal" href="#grammar-token-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a>
</pre>
<p id="index-56">The <code class="docutils literal notranslate"><span class="pre">*</span></code> (multiplication) operator yields the product of its arguments. The
arguments must either both be numbers, or one argument must be an integer and
the other must be a sequence. In the former case, the numbers are converted to a
common type and then multiplied together. In the latter case, sequence
repetition is performed; a negative repetition factor yields an empty sequence.</p>
<p id="index-57">The <code class="docutils literal notranslate"><span class="pre">@</span></code> (at) operator is intended to be used for matrix multiplication. No
builtin Python types implement this operator.</p>
<div class="versionadded">
<p><span class="versionmodified">3.5 版新加入.</span></p>
</div>
<p id="index-58">The <code class="docutils literal notranslate"><span class="pre">/</span></code> (division) and <code class="docutils literal notranslate"><span class="pre">//</span></code> (floor division) operators yield the quotient of
their arguments. The numeric arguments are first converted to a common type.
Division of integers yields a float, while floor division of integers results in an
integer; the result is that of mathematical division with the 『floor』 function
applied to the result. Division by zero raises the <a class="reference internal" href="../library/exceptions.html#ZeroDivisionError" title="ZeroDivisionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZeroDivisionError</span></code></a>
exception.</p>
<p id="index-59">The <code class="docutils literal notranslate"><span class="pre">%</span></code> (modulo) operator yields the remainder from the division of the first
argument by the second. The numeric arguments are first converted to a common
type. A zero right argument raises the <a class="reference internal" href="../library/exceptions.html#ZeroDivisionError" title="ZeroDivisionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZeroDivisionError</span></code></a> exception. The
arguments may be floating point numbers, e.g., <code class="docutils literal notranslate"><span class="pre">3.14%0.7</span></code> equals <code class="docutils literal notranslate"><span class="pre">0.34</span></code>
(since <code class="docutils literal notranslate"><span class="pre">3.14</span></code> equals <code class="docutils literal notranslate"><span class="pre">4*0.7</span> <span class="pre">+</span> <span class="pre">0.34</span></code>.) The modulo operator always yields a
result with the same sign as its second operand (or zero); the absolute value of
the result is strictly smaller than the absolute value of the second operand
<a class="footnote-reference" href="#id17" id="id9">[1]</a>.</p>
<p>The floor division and modulo operators are connected by the following
identity: <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">(x//y)*y</span> <span class="pre">+</span> <span class="pre">(x%y)</span></code>. Floor division and modulo are also
connected with the built-in function <a class="reference internal" href="../library/functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">divmod()</span></code></a>: <code class="docutils literal notranslate"><span class="pre">divmod(x,</span> <span class="pre">y)</span> <span class="pre">==</span> <span class="pre">(x//y,</span>
<span class="pre">x%y)</span></code>. <a class="footnote-reference" href="#id18" id="id10">[2]</a>.</p>
<p>In addition to performing the modulo operation on numbers, the <code class="docutils literal notranslate"><span class="pre">%</span></code> operator is
also overloaded by string objects to perform old-style string formatting (also
known as interpolation). The syntax for string formatting is described in the
Python Library Reference, section <a class="reference internal" href="../library/stdtypes.html#old-string-formatting"><span class="std std-ref">printf-style String Formatting</span></a>.</p>
<p>The floor division operator, the modulo operator, and the <a class="reference internal" href="../library/functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">divmod()</span></code></a>
function are not defined for complex numbers. Instead, convert to a floating
point number using the <a class="reference internal" href="../library/functions.html#abs" title="abs"><code class="xref py py-func docutils literal notranslate"><span class="pre">abs()</span></code></a> function if appropriate.</p>
<p id="index-60">The <code class="docutils literal notranslate"><span class="pre">+</span></code> (addition) operator yields the sum of its arguments. The arguments
must either both be numbers or both be sequences of the same type. In the
former case, the numbers are converted to a common type and then added together.
In the latter case, the sequences are concatenated.</p>
<p id="index-61">The <code class="docutils literal notranslate"><span class="pre">-</span></code> (subtraction) operator yields the difference of its arguments. The
numeric arguments are first converted to a common type.</p>
</div>
<div class="section" id="shifting-operations">
<span id="shifting"></span><h2>6.8. Shifting operations<a class="headerlink" href="#shifting-operations" title="本標題的永久連結">¶</a></h2>
<p id="index-62">The shifting operations have lower priority than the arithmetic operations:</p>
<pre>
<strong id="grammar-token-shift_expr">shift_expr</strong> ::= <a class="reference internal" href="#grammar-token-a_expr"><code class="xref docutils literal notranslate"><span class="pre">a_expr</span></code></a> | <a class="reference internal" href="#grammar-token-shift_expr"><code class="xref docutils literal notranslate"><span class="pre">shift_expr</span></code></a> ("<<" | ">>") <a class="reference internal" href="#grammar-token-a_expr"><code class="xref docutils literal notranslate"><span class="pre">a_expr</span></code></a>
</pre>
<p>These operators accept integers as arguments. They shift the first argument to
the left or right by the number of bits given by the second argument.</p>
<p id="index-63">A right shift by <em>n</em> bits is defined as floor division by <code class="docutils literal notranslate"><span class="pre">pow(2,n)</span></code>. A left
shift by <em>n</em> bits is defined as multiplication with <code class="docutils literal notranslate"><span class="pre">pow(2,n)</span></code>.</p>
</div>
<div class="section" id="binary-bitwise-operations">
<span id="bitwise"></span><h2>6.9. Binary bitwise operations<a class="headerlink" href="#binary-bitwise-operations" title="本標題的永久連結">¶</a></h2>
<p id="index-64">Each of the three bitwise operations has a different priority level:</p>
<pre>
<strong id="grammar-token-and_expr">and_expr</strong> ::= <a class="reference internal" href="#grammar-token-shift_expr"><code class="xref docutils literal notranslate"><span class="pre">shift_expr</span></code></a> | <a class="reference internal" href="#grammar-token-and_expr"><code class="xref docutils literal notranslate"><span class="pre">and_expr</span></code></a> "&" <a class="reference internal" href="#grammar-token-shift_expr"><code class="xref docutils literal notranslate"><span class="pre">shift_expr</span></code></a>
<strong id="grammar-token-xor_expr">xor_expr</strong> ::= <a class="reference internal" href="#grammar-token-and_expr"><code class="xref docutils literal notranslate"><span class="pre">and_expr</span></code></a> | <a class="reference internal" href="#grammar-token-xor_expr"><code class="xref docutils literal notranslate"><span class="pre">xor_expr</span></code></a> "^" <a class="reference internal" href="#grammar-token-and_expr"><code class="xref docutils literal notranslate"><span class="pre">and_expr</span></code></a>
<strong id="grammar-token-or_expr">or_expr </strong> ::= <a class="reference internal" href="#grammar-token-xor_expr"><code class="xref docutils literal notranslate"><span class="pre">xor_expr</span></code></a> | <a class="reference internal" href="#grammar-token-or_expr"><code class="xref docutils literal notranslate"><span class="pre">or_expr</span></code></a> "|" <a class="reference internal" href="#grammar-token-xor_expr"><code class="xref docutils literal notranslate"><span class="pre">xor_expr</span></code></a>
</pre>
<p id="index-65">The <code class="docutils literal notranslate"><span class="pre">&</span></code> operator yields the bitwise AND of its arguments, which must be
integers.</p>
<p id="index-66">The <code class="docutils literal notranslate"><span class="pre">^</span></code> operator yields the bitwise XOR (exclusive OR) of its arguments, which
must be integers.</p>
<p id="index-67">The <code class="docutils literal notranslate"><span class="pre">|</span></code> operator yields the bitwise (inclusive) OR of its arguments, which
must be integers.</p>
</div>
<div class="section" id="comparisons">
<span id="id11"></span><h2>6.10. Comparisons<a class="headerlink" href="#comparisons" title="本標題的永久連結">¶</a></h2>
<span class="target" id="index-68"></span><p id="index-69">Unlike C, all comparison operations in Python have the same priority, which is
lower than that of any arithmetic, shifting or bitwise operation. Also unlike
C, expressions like <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre"><</span> <span class="pre">b</span> <span class="pre"><</span> <span class="pre">c</span></code> have the interpretation that is conventional
in mathematics:</p>
<pre>
<strong id="grammar-token-comparison">comparison </strong> ::= <a class="reference internal" href="#grammar-token-or_expr"><code class="xref docutils literal notranslate"><span class="pre">or_expr</span></code></a> (<a class="reference internal" href="#grammar-token-comp_operator"><code class="xref docutils literal notranslate"><span class="pre">comp_operator</span></code></a> <a class="reference internal" href="#grammar-token-or_expr"><code class="xref docutils literal notranslate"><span class="pre">or_expr</span></code></a>)*
<strong id="grammar-token-comp_operator">comp_operator</strong> ::= "<" | ">" | "==" | ">=" | "<=" | "!="
| "is" ["not"] | ["not"] "in"
</pre>
<p>Comparisons yield boolean values: <code class="docutils literal notranslate"><span class="pre">True</span></code> or <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
<p id="index-70">Comparisons can be chained arbitrarily, e.g., <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre"><</span> <span class="pre">y</span> <span class="pre"><=</span> <span class="pre">z</span></code> is equivalent to
<code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre"><</span> <span class="pre">y</span> <span class="pre">and</span> <span class="pre">y</span> <span class="pre"><=</span> <span class="pre">z</span></code>, except that <code class="docutils literal notranslate"><span class="pre">y</span></code> is evaluated only once (but in both
cases <code class="docutils literal notranslate"><span class="pre">z</span></code> is not evaluated at all when <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre"><</span> <span class="pre">y</span></code> is found to be false).</p>
<p>Formally, if <em>a</em>, <em>b</em>, <em>c</em>, …, <em>y</em>, <em>z</em> are expressions and <em>op1</em>, <em>op2</em>, …,
<em>opN</em> are comparison operators, then <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">op1</span> <span class="pre">b</span> <span class="pre">op2</span> <span class="pre">c</span> <span class="pre">...</span> <span class="pre">y</span> <span class="pre">opN</span> <span class="pre">z</span></code> is equivalent
to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">op1</span> <span class="pre">b</span> <span class="pre">and</span> <span class="pre">b</span> <span class="pre">op2</span> <span class="pre">c</span> <span class="pre">and</span> <span class="pre">...</span> <span class="pre">y</span> <span class="pre">opN</span> <span class="pre">z</span></code>, except that each expression is
evaluated at most once.</p>
<p>Note that <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">op1</span> <span class="pre">b</span> <span class="pre">op2</span> <span class="pre">c</span></code> doesn’t imply any kind of comparison between <em>a</em> and
<em>c</em>, so that, e.g., <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre"><</span> <span class="pre">y</span> <span class="pre">></span> <span class="pre">z</span></code> is perfectly legal (though perhaps not
pretty).</p>
<div class="section" id="value-comparisons">
<h3>6.10.1. Value comparisons<a class="headerlink" href="#value-comparisons" title="本標題的永久連結">¶</a></h3>
<p>The operators <code class="docutils literal notranslate"><span class="pre"><</span></code>, <code class="docutils literal notranslate"><span class="pre">></span></code>, <code class="docutils literal notranslate"><span class="pre">==</span></code>, <code class="docutils literal notranslate"><span class="pre">>=</span></code>, <code class="docutils literal notranslate"><span class="pre"><=</span></code>, and <code class="docutils literal notranslate"><span class="pre">!=</span></code> compare the
values of two objects. The objects do not need to have the same type.</p>
<p>Chapter <a class="reference internal" href="datamodel.html#objects"><span class="std std-ref">Objects, values and types</span></a> states that objects have a value (in addition to type
and identity). The value of an object is a rather abstract notion in Python:
For example, there is no canonical access method for an object’s value. Also,
there is no requirement that the value of an object should be constructed in a
particular way, e.g. comprised of all its data attributes. Comparison operators
implement a particular notion of what the value of an object is. One can think
of them as defining the value of an object indirectly, by means of their
comparison implementation.</p>
<p>Because all types are (direct or indirect) subtypes of <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>, they
inherit the default comparison behavior from <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>. Types can
customize their comparison behavior by implementing