forked from python/python-docs-zh-tw
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtyping.po
More file actions
6468 lines (5635 loc) · 210 KB
/
Copy pathtyping.po
File metadata and controls
6468 lines (5635 loc) · 210 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
# Copyright (C) 2001 Python Software Foundation
# This file is distributed under the same license as the Python package.
#
# Translators:
msgid ""
msgstr ""
"Project-Id-Version: Python 3.14\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-05-23 00:37+0000\n"
"PO-Revision-Date: 2024-07-11 11:12+0800\n"
"Last-Translator: Li-Hung Wang <therockleona@gmail.com>\n"
"Language-Team: Chinese - TAIWAN (https://github.com/python/python-docs-zh-"
"tw)\n"
"Language: zh_TW\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=1; plural=0;\n"
"X-Generator: Poedit 3.4.4\n"
#: ../../library/typing.rst:3
msgid ":mod:`!typing` --- Support for type hints"
msgstr ":mod:`!typing` --- 支援型別提示"
#: ../../library/typing.rst:16
msgid "**Source code:** :source:`Lib/typing.py`"
msgstr "**原始碼:**\\ :source:`Lib/typing.py`"
#: ../../library/typing.rst:20
msgid ""
"The Python runtime does not enforce function and variable type annotations. "
"They can be used by third party tools such as :term:`type checkers <static "
"type checker>`, IDEs, linters, etc."
msgstr ""
"Python runtime 不強制要求函式與變數的型別註釋。他們可以被第三方工具使用,如:"
"\\ :term:`型別檢查器 <static type checker>`、IDE、linter 等。"
#: ../../library/typing.rst:26
msgid "This module provides runtime support for type hints."
msgstr "此模組提供 runtime 型別提示支援。"
#: ../../library/typing.rst:28
msgid "Consider the function below::"
msgstr "動腦筋思考下面的函式: ::"
#: ../../library/typing.rst:30
msgid ""
"def surface_area_of_cube(edge_length: float) -> str:\n"
" return f\"The surface area of the cube is {6 * edge_length ** 2}.\""
msgstr ""
"def surface_area_of_cube(edge_length: float) -> str:\n"
" return f\"The surface area of the cube is {6 * edge_length ** 2}.\""
#: ../../library/typing.rst:33
msgid ""
"The function ``surface_area_of_cube`` takes an argument expected to be an "
"instance of :class:`float`, as indicated by the :term:`type hint` "
"``edge_length: float``. The function is expected to return an instance of :"
"class:`str`, as indicated by the ``-> str`` hint."
msgstr ""
"函式 ``surface_area_of_cube`` 需要一個引數且預期是一個 :class:`float` 的實"
"例,如 ``edge_length: float`` 所指出的\\ :term:`型別提示 <type hint>`。這個函"
"式預期會回傳一個 :class:`str` 的實例,如 ``-> str`` 所指出的提示。"
#: ../../library/typing.rst:38
msgid ""
"While type hints can be simple classes like :class:`float` or :class:`str`, "
"they can also be more complex. The :mod:`typing` module provides a "
"vocabulary of more advanced type hints."
msgstr ""
"儘管型別提示可以是簡單類別,像是 :class:`float` 或 :class:`str`,他們也可以變"
"得更為複雜。模組 :mod:`typing` 提供一組更高階的型別提示詞彙。"
#: ../../library/typing.rst:42
msgid ""
"New features are frequently added to the ``typing`` module. The :pypi:"
"`typing_extensions` package provides backports of these new features to "
"older versions of Python."
msgstr ""
"新功能會頻繁的新增至 ``typing`` 模組中。:pypi:`typing_extensions` 套件為這些"
"新功能提供了 backport(向後移植的)版本,提供給舊版本的 Python 使用。"
#: ../../library/typing.rst:48
msgid ""
"`Typing cheat sheet <https://mypy.readthedocs.io/en/stable/cheat_sheet_py3."
"html>`_"
msgstr ""
"`型別小抄 (Typing cheat sheet) <https://mypy.readthedocs.io/en/stable/"
"cheat_sheet_py3.html>`_"
#: ../../library/typing.rst:49
msgid "A quick overview of type hints (hosted at the mypy docs)"
msgstr "型別提示的快速預覽(發布於 mypy 的文件中)"
#: ../../library/typing.rst:51
msgid ""
"Type System Reference section of `the mypy docs <https://mypy.readthedocs.io/"
"en/stable/index.html>`_"
msgstr ""
"`mypy 文件 <https://mypy.readthedocs.io/en/stable/index.html>`_\\ 的 型別系統"
"參考資料 (Type System Reference) 章節"
#: ../../library/typing.rst:52
msgid ""
"The Python typing system is standardised via PEPs, so this reference should "
"broadly apply to most Python type checkers. (Some parts may still be "
"specific to mypy.)"
msgstr ""
"Python 的加註型別系統是基於 PEPs 進行標準化,所以這個參照 (reference) 應該在"
"多數 Python 型別檢查器中廣為使用。(某些部分依然是特定給 mypy 使用。)"
#: ../../library/typing.rst:56
msgid "`Static Typing with Python <https://typing.python.org/en/latest/>`_"
msgstr ""
"`Python 的靜態型別 (Static Typing) <https://typing.python.org/en/latest/>`_"
#: ../../library/typing.rst:57
msgid ""
"Type-checker-agnostic documentation written by the community detailing type "
"system features, useful typing related tools and typing best practices."
msgstr ""
"由社群編寫的跨平台型別檢查器文件 (type-checker-agnostic) 詳細描述加註型別系統"
"的功能、實用的加註型別衍伸工具、以及加註型別的最佳實踐 (best practice)。"
#: ../../library/typing.rst:64
msgid "Specification for the Python Type System"
msgstr "Python 型別系統的技術規範"
#: ../../library/typing.rst:66
msgid ""
"The canonical, up-to-date specification of the Python type system can be "
"found at `Specification for the Python type system <https://typing.python."
"org/en/latest/spec/index.html>`_."
msgstr ""
"關於 Python 型別系統標準的 (canonical)、最新的技術規範可以在\\ `Python 型別系"
"統的技術規範 <https://typing.python.org/en/latest/spec/index.html>`_\\ 找到。"
#: ../../library/typing.rst:72
msgid "Type aliases"
msgstr "型別別名"
#: ../../library/typing.rst:74
msgid ""
"A type alias is defined using the :keyword:`type` statement, which creates "
"an instance of :class:`TypeAliasType`. In this example, ``Vector`` and "
"``list[float]`` will be treated equivalently by static type checkers::"
msgstr ""
"一個型別別名被定義來使用 :keyword:`type` 陳述式,其建立了 :class:"
"`TypeAliasType` 的實例。在這個範例中,``Vector`` 及 ``list[float]`` 會被當作"
"和靜態型別檢查器一樣同等對待: ::"
#: ../../library/typing.rst:79
msgid ""
"type Vector = list[float]\n"
"\n"
"def scale(scalar: float, vector: Vector) -> Vector:\n"
" return [scalar * num for num in vector]\n"
"\n"
"# passes type checking; a list of floats qualifies as a Vector.\n"
"new_vector = scale(2.0, [1.0, -4.2, 5.4])"
msgstr ""
#: ../../library/typing.rst:87
msgid ""
"Type aliases are useful for simplifying complex type signatures. For "
"example::"
msgstr ""
"型別別名對於簡化複雜的型別簽名 (complex type signature) 非常好用。舉例來"
"說: ::"
#: ../../library/typing.rst:89
msgid ""
"from collections.abc import Sequence\n"
"\n"
"type ConnectionOptions = dict[str, str]\n"
"type Address = tuple[str, int]\n"
"type Server = tuple[Address, ConnectionOptions]\n"
"\n"
"def broadcast_message(message: str, servers: Sequence[Server]) -> None:\n"
" ...\n"
"\n"
"# The static type checker will treat the previous type signature as\n"
"# being exactly equivalent to this one.\n"
"def broadcast_message(\n"
" message: str,\n"
" servers: Sequence[tuple[tuple[str, int], dict[str, str]]]\n"
") -> None:\n"
" ..."
msgstr ""
#: ../../library/typing.rst:106
msgid ""
"The :keyword:`type` statement is new in Python 3.12. For backwards "
"compatibility, type aliases can also be created through simple assignment::"
msgstr ""
":keyword:`type` 陳述式是 Python 3.12 的新功能。為了向後相容性,型別別名可以透"
"過簡單的賦值來建立: ::"
#: ../../library/typing.rst:109
msgid "Vector = list[float]"
msgstr "Vector = list[float]"
#: ../../library/typing.rst:111
msgid ""
"Or marked with :data:`TypeAlias` to make it explicit that this is a type "
"alias, not a normal variable assignment::"
msgstr ""
"或是用 :data:`TypeAlias` 標記,讓它明確的表示這是一個型別別名,而非一般的變數"
"賦值: ::"
#: ../../library/typing.rst:114
msgid ""
"from typing import TypeAlias\n"
"\n"
"Vector: TypeAlias = list[float]"
msgstr ""
#: ../../library/typing.rst:121
msgid "NewType"
msgstr "NewType"
#: ../../library/typing.rst:123
msgid "Use the :class:`NewType` helper to create distinct types::"
msgstr "使用 :class:`NewType` 輔助工具 (helper) 建立獨特型別: ::"
#: ../../library/typing.rst:125
msgid ""
"from typing import NewType\n"
"\n"
"UserId = NewType('UserId', int)\n"
"some_id = UserId(524313)"
msgstr ""
#: ../../library/typing.rst:130
msgid ""
"The static type checker will treat the new type as if it were a subclass of "
"the original type. This is useful in helping catch logical errors::"
msgstr ""
"若它是原本型別的子類別,靜態型別檢查器會將其視為一個新的型別。這對於幫助擷取"
"邏輯性錯誤非常有用: ::"
#: ../../library/typing.rst:133
msgid ""
"def get_user_name(user_id: UserId) -> str:\n"
" ...\n"
"\n"
"# passes type checking\n"
"user_a = get_user_name(UserId(42351))\n"
"\n"
"# fails type checking; an int is not a UserId\n"
"user_b = get_user_name(-1)"
msgstr ""
#: ../../library/typing.rst:142
msgid ""
"You may still perform all ``int`` operations on a variable of type "
"``UserId``, but the result will always be of type ``int``. This lets you "
"pass in a ``UserId`` wherever an ``int`` might be expected, but will prevent "
"you from accidentally creating a ``UserId`` in an invalid way::"
msgstr ""
"你依然可以在對於型別 ``UserId`` 的變數中執行所有 ``int`` 的操作。這讓你可以在"
"預期接受 ``int`` 的地方傳遞一個 ``UserId``,還能預防你意外使用無效的方法建立"
"一個 ``UserId``: ::"
#: ../../library/typing.rst:147
msgid ""
"# 'output' is of type 'int', not 'UserId'\n"
"output = UserId(23413) + UserId(54341)"
msgstr ""
#: ../../library/typing.rst:150
msgid ""
"Note that these checks are enforced only by the static type checker. At "
"runtime, the statement ``Derived = NewType('Derived', Base)`` will make "
"``Derived`` a callable that immediately returns whatever parameter you pass "
"it. That means the expression ``Derived(some_value)`` does not create a new "
"class or introduce much overhead beyond that of a regular function call."
msgstr ""
"注意這只會透過靜態型別檢查器強制檢查。在 runtime 中,陳述式 (statement) "
"``Derived = NewType('Derived', Base)`` 會使 ``Derived`` 成為一個 callable(可"
"呼叫物件),會立即回傳任何你傳遞的引數。這意味著 expression (運算式)\\ "
"``Derived(some_value)`` 不會建立一個新的類別或過度引入原有的函式呼叫。"
#: ../../library/typing.rst:156
msgid ""
"More precisely, the expression ``some_value is Derived(some_value)`` is "
"always true at runtime."
msgstr ""
"更精確地說,expression ``some_value is Derived(some_value)`` 在 runtime 永遠"
"為 true。"
#: ../../library/typing.rst:159
msgid "It is invalid to create a subtype of ``Derived``::"
msgstr "這會無法建立一個 ``Derived`` 的子型別: ::"
#: ../../library/typing.rst:161
msgid ""
"from typing import NewType\n"
"\n"
"UserId = NewType('UserId', int)\n"
"\n"
"# Fails at runtime and does not pass type checking\n"
"class AdminUserId(UserId): pass"
msgstr ""
#: ../../library/typing.rst:168
msgid ""
"However, it is possible to create a :class:`NewType` based on a 'derived' "
"``NewType``::"
msgstr ""
"無論如何,這有辦法基於 '衍生的' ``NewType`` 建立一個 :class:`NewType`: ::"
#: ../../library/typing.rst:170
msgid ""
"from typing import NewType\n"
"\n"
"UserId = NewType('UserId', int)\n"
"\n"
"ProUserId = NewType('ProUserId', UserId)"
msgstr ""
"from typing import NewType\n"
"\n"
"UserId = NewType('UserId', int)\n"
"\n"
"ProUserId = NewType('ProUserId', UserId)"
#: ../../library/typing.rst:176
msgid "and typechecking for ``ProUserId`` will work as expected."
msgstr "以及針對 ``ProUserId`` 的型別檢查會如期運作。"
#: ../../library/typing.rst:178
msgid "See :pep:`484` for more details."
msgstr "更多細節請見 :pep:`484`。"
#: ../../library/typing.rst:182
msgid ""
"Recall that the use of a type alias declares two types to be *equivalent* to "
"one another. Doing ``type Alias = Original`` will make the static type "
"checker treat ``Alias`` as being *exactly equivalent* to ``Original`` in all "
"cases. This is useful when you want to simplify complex type signatures."
msgstr ""
"請記得使用型別別名是宣告兩種型別是互相\\ *相等*\\ 的。使用 ``type Alias = "
"Original`` 則會讓靜態型別檢查器在任何情況之下將 ``Alias`` 視為與 "
"``Original`` \\ *完全相等*。這當你想把複雜的型別簽名進行簡化時,非常好用。"
#: ../../library/typing.rst:187
msgid ""
"In contrast, ``NewType`` declares one type to be a *subtype* of another. "
"Doing ``Derived = NewType('Derived', Original)`` will make the static type "
"checker treat ``Derived`` as a *subclass* of ``Original``, which means a "
"value of type ``Original`` cannot be used in places where a value of type "
"``Derived`` is expected. This is useful when you want to prevent logic "
"errors with minimal runtime cost."
msgstr ""
"相反的,``NewType`` 宣告一個型別會是另外一種型別的子類別。使用 ``Derived = "
"NewType('Derived', Original)`` 會使靜態型別檢查器將 ``Derived`` 視為 "
"``Original`` 的子類別,也意味著一個型別為 ``Original`` 的值,不能被使用在任何"
"預期接收到型別 ``Derived`` 的值的區域。這當你想用最小的 runtime 成本預防邏輯"
"性錯誤而言,非常有用。"
#: ../../library/typing.rst:196
msgid ""
"``NewType`` is now a class rather than a function. As a result, there is "
"some additional runtime cost when calling ``NewType`` over a regular "
"function."
msgstr ""
"現在的 ``NewType`` 比起一個函式更像一個類別。因此,比起一般的函式,呼叫 "
"``NewType`` 需要額外的 runtime 成本。"
#: ../../library/typing.rst:201
msgid ""
"The performance of calling ``NewType`` has been restored to its level in "
"Python 3.9."
msgstr "呼叫 ``NewType`` 的效能已經恢復與 Python 3.9 相同的水準。"
#: ../../library/typing.rst:208
msgid "Annotating callable objects"
msgstr "註釋 callable 物件"
#: ../../library/typing.rst:210
msgid ""
"Functions -- or other :term:`callable` objects -- can be annotated using :"
"class:`collections.abc.Callable` or deprecated :data:`typing.Callable`. "
"``Callable[[int], str]`` signifies a function that takes a single parameter "
"of type :class:`int` and returns a :class:`str`."
msgstr ""
"函式,或者是其他 :term:`callable` 物件,可以使用 :class:`collections.abc."
"Callable` 或以棄用的 :data:`typing.Callable` 進行註釋。 ``Callable[[int], "
"str]`` 象徵為一個函式,可以接受一個型別為 :class:`int` 的引數,並回傳一個 :"
"class:`str`。"
#: ../../library/typing.rst:215 ../../library/typing.rst:3297
#: ../../library/typing.rst:3483 ../../library/typing.rst:3511
msgid "For example:"
msgstr "舉例來說:"
#: ../../library/typing.rst:217
msgid ""
"from collections.abc import Callable, Awaitable\n"
"\n"
"def feeder(get_next_item: Callable[[], str]) -> None:\n"
" ... # Body\n"
"\n"
"def async_query(on_success: Callable[[int], None],\n"
" on_error: Callable[[int, Exception], None]) -> None:\n"
" ... # Body\n"
"\n"
"async def on_update(value: str) -> None:\n"
" ... # Body\n"
"\n"
"callback: Callable[[str], Awaitable[None]] = on_update"
msgstr ""
"from collections.abc import Callable, Awaitable\n"
"\n"
"def feeder(get_next_item: Callable[[], str]) -> None:\n"
" ... # 主體\n"
"\n"
"def async_query(on_success: Callable[[int], None],\n"
" on_error: Callable[[int, Exception], None]) -> None:\n"
" ... # 主體\n"
"\n"
"async def on_update(value: str) -> None:\n"
" ... # 主體\n"
"\n"
"callback: Callable[[str], Awaitable[None]] = on_update"
#: ../../library/typing.rst:235
msgid ""
"The subscription syntax must always be used with exactly two values: the "
"argument list and the return type. The argument list must be a list of "
"types, a :class:`ParamSpec`, :data:`Concatenate`, or an ellipsis (``...``). "
"The return type must be a single type."
msgstr ""
"使用下標語法 (subscription syntax) 時,必須使用到兩個值,分別為引述串列以及回"
"傳類別。引數串列必須為一個型別串列::class:`ParamSpec`、:data:`Concatenate` "
"或是一個刪節號 (ellipsis, ``...``)。回傳類別必為一個單一類別。"
#: ../../library/typing.rst:240
msgid ""
"If a literal ellipsis ``...`` is given as the argument list, it indicates "
"that a callable with any arbitrary parameter list would be acceptable:"
msgstr ""
"若刪節號字面值 ``...`` 被當作引數串列給定,其指出一個具任何、任意參數列表的 "
"callable 會被接受: ::"
#: ../../library/typing.rst:243
msgid ""
"def concat(x: str, y: str) -> str:\n"
" return x + y\n"
"\n"
"x: Callable[..., str]\n"
"x = str # OK\n"
"x = concat # Also OK"
msgstr ""
"def concat(x: str, y: str) -> str:\n"
" return x + y\n"
"\n"
"x: Callable[..., str]\n"
"x = str # OK\n"
"x = concat # 也 OK"
#: ../../library/typing.rst:252
msgid ""
"``Callable`` cannot express complex signatures such as functions that take a "
"variadic number of arguments, :ref:`overloaded functions <overload>`, or "
"functions that have keyword-only parameters. However, these signatures can "
"be expressed by defining a :class:`Protocol` class with a :meth:`~object."
"__call__` method:"
msgstr ""
"``Callable`` 不如有可變數量引數的函式、:func:`overloaded functions "
"<overload>`、或是僅限關鍵字參數的函式,可以表示複雜簽名。然而,這些簽名可以透"
"過定義一個具有 :meth:`~object.__call__` 方法的 :class:`Protocol` 類別進行表"
"示:"
#: ../../library/typing.rst:258
msgid ""
"from collections.abc import Iterable\n"
"from typing import Protocol\n"
"\n"
"class Combiner(Protocol):\n"
" def __call__(self, *vals: bytes, maxlen: int | None = None) -> "
"list[bytes]: ...\n"
"\n"
"def batch_proc(data: Iterable[bytes], cb_results: Combiner) -> bytes:\n"
" for item in data:\n"
" ...\n"
"\n"
"def good_cb(*vals: bytes, maxlen: int | None = None) -> list[bytes]:\n"
" ...\n"
"def bad_cb(*vals: bytes, maxitems: int | None) -> list[bytes]:\n"
" ...\n"
"\n"
"batch_proc([], good_cb) # OK\n"
"batch_proc([], bad_cb) # Error! Argument 2 has incompatible type because "
"of\n"
" # different name and kind in the callback"
msgstr ""
#: ../../library/typing.rst:279
msgid ""
"Callables which take other callables as arguments may indicate that their "
"parameter types are dependent on each other using :class:`ParamSpec`. "
"Additionally, if that callable adds or removes arguments from other "
"callables, the :data:`Concatenate` operator may be used. They take the form "
"``Callable[ParamSpecVariable, ReturnType]`` and "
"``Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], "
"ReturnType]`` respectively."
msgstr ""
"Callable 物件可以取用其他 callable 當作引數使用,可以透過 :class:`ParamSpec` "
"指出他們的參數型別是個別獨立的。另外,如果這個 callable 從其他 callable 新增"
"或刪除引數時,將會使用到 :data:`Concatenate` 運算子。他們可以分別採用 "
"``Callable[ParamSpecVariable, ReturnType]`` 以及 "
"``Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], "
"ReturnType]`` 的形式。"
#: ../../library/typing.rst:287 ../../library/typing.rst:4053
msgid ""
"``Callable`` now supports :class:`ParamSpec` and :data:`Concatenate`. See :"
"pep:`612` for more details."
msgstr ""
"``Callable`` 現已支援 :class:`ParamSpec` 以及 :data:`Concatenate`。請參閱 :"
"pep:`612` 閱讀詳細內容。"
#: ../../library/typing.rst:292
msgid ""
"The documentation for :class:`ParamSpec` and :class:`Concatenate` provides "
"examples of usage in ``Callable``."
msgstr ""
":class:`ParamSpec` 以及 :class:`Concatenate` 的文件中,提供範例如何在 "
"``Callable`` 中使用。"
#: ../../library/typing.rst:298
msgid "Generics"
msgstr "泛型"
#: ../../library/typing.rst:300
msgid ""
"Since type information about objects kept in containers cannot be statically "
"inferred in a generic way, many container classes in the standard library "
"support subscription to denote the expected types of container elements."
msgstr ""
"因為關於物件的型別資訊留存在容器之內,且無法使用通用的方式進行靜態推論 "
"(statically inferred),許多標準函式庫的容器類別支援以下標來表示容器內預期的元"
"素。"
#: ../../library/typing.rst:304
msgid ""
"from collections.abc import Mapping, Sequence\n"
"\n"
"class Employee: ...\n"
"\n"
"# Sequence[Employee] indicates that all elements in the sequence\n"
"# must be instances of \"Employee\".\n"
"# Mapping[str, str] indicates that all keys and all values in the mapping\n"
"# must be strings.\n"
"def notify_by_email(employees: Sequence[Employee],\n"
" overrides: Mapping[str, str]) -> None: ..."
msgstr ""
#: ../../library/typing.rst:317
msgid ""
"Generic functions and classes can be parameterized by using :ref:`type "
"parameter syntax <type-params>`::"
msgstr ""
"泛型函式及類別可以使用\\ :ref:`型別參數語法 (type parameter syntax) <type-"
"params>` 進行參數化 (parameterize) : ::"
#: ../../library/typing.rst:320
msgid ""
"from collections.abc import Sequence\n"
"\n"
"def first[T](l: Sequence[T]) -> T: # Function is generic over the TypeVar "
"\"T\"\n"
" return l[0]"
msgstr ""
#: ../../library/typing.rst:325
msgid "Or by using the :class:`TypeVar` factory directly::"
msgstr "或是直接使用 :class:`TypeVar` 工廠 (factory): ::"
#: ../../library/typing.rst:327
msgid ""
"from collections.abc import Sequence\n"
"from typing import TypeVar\n"
"\n"
"U = TypeVar('U') # Declare type variable \"U\"\n"
"\n"
"def second(l: Sequence[U]) -> U: # Function is generic over the TypeVar "
"\"U\"\n"
" return l[1]"
msgstr ""
#: ../../library/typing.rst:335
msgid "Syntactic support for generics is new in Python 3.12."
msgstr "在 Python 3.12 中,泛型的語法支援是全新功能。"
#: ../../library/typing.rst:341
msgid "Annotating tuples"
msgstr "註釋元組 (tuple)"
#: ../../library/typing.rst:343
msgid ""
"For most containers in Python, the typing system assumes that all elements "
"in the container will be of the same type. For example::"
msgstr ""
"在 Python 大多數的容器當中,加註型別系統認為容器內的所有元素會是相同型別。舉"
"例來說: ::"
#: ../../library/typing.rst:346
msgid ""
"from collections.abc import Mapping\n"
"\n"
"# Type checker will infer that all elements in ``x`` are meant to be ints\n"
"x: list[int] = []\n"
"\n"
"# Type checker error: ``list`` only accepts a single type argument:\n"
"y: list[int, str] = [1, 'foo']\n"
"\n"
"# Type checker will infer that all keys in ``z`` are meant to be strings,\n"
"# and that all values in ``z`` are meant to be either strings or ints\n"
"z: Mapping[str, str | int] = {}"
msgstr ""
#: ../../library/typing.rst:358
msgid ""
":class:`list` only accepts one type argument, so a type checker would emit "
"an error on the ``y`` assignment above. Similarly, :class:`~collections.abc."
"Mapping` only accepts two type arguments: the first indicates the type of "
"the keys, and the second indicates the type of the values."
msgstr ""
":class:`list` 只接受一個型別引數,所以型別檢查器可能在上述 ``y`` 賦值 "
"(assignment) 觸發錯誤。類似的範例,:class:`~collections.abc.Mapping` 只接受兩"
"個型別引數:第一個引數指出 keys(鍵)的型別;第二個引數指出 values(值)的型"
"別。"
#: ../../library/typing.rst:364
msgid ""
"Unlike most other Python containers, however, it is common in idiomatic "
"Python code for tuples to have elements which are not all of the same type. "
"For this reason, tuples are special-cased in Python's typing system. :class:"
"`tuple` accepts *any number* of type arguments::"
msgstr ""
"然而,與其他多數的 Python 容器不同,在慣用的 (idiomatic) Python 程式碼中,元"
"組可以擁有不完全相同型別的元素是相當常見的。為此,元組在 Python 的加註型別系"
"統中是個特例 (special-cased)。:class:`tuple` 接受\\ *任何數量*\\ 的型別引"
"數: ::"
#: ../../library/typing.rst:369
msgid ""
"# OK: ``x`` is assigned to a tuple of length 1 where the sole element is an "
"int\n"
"x: tuple[int] = (5,)\n"
"\n"
"# OK: ``y`` is assigned to a tuple of length 2;\n"
"# element 1 is an int, element 2 is a str\n"
"y: tuple[int, str] = (5, \"foo\")\n"
"\n"
"# Error: the type annotation indicates a tuple of length 1,\n"
"# but ``z`` has been assigned to a tuple of length 3\n"
"z: tuple[int] = (1, 2, 3)"
msgstr ""
#: ../../library/typing.rst:382
msgid ""
"To denote a tuple which could be of *any* length, and in which all elements "
"are of the same type ``T``, use the literal ellipsis ``...``: "
"``tuple[T, ...]``. To denote an empty tuple, use ``tuple[()]``. Using plain "
"``tuple`` as an annotation is equivalent to using ``tuple[Any, ...]``::"
msgstr ""
"為了標示一個元組可以為\\ *任意*\\ 長度,且所有元素皆是相同型別 ``T``,請使用 "
"刪節號字面值 (literal ellipsis) ``...``:``tuple[T, ...]``。為了標示一個空元"
"組,請使用 ``tuple[()]``。單純使用 ``tuple`` 作為註釋會與使用 "
"``tuple[Any, ...]`` 相等: ::"
#: ../../library/typing.rst:388
msgid ""
"x: tuple[int, ...] = (1, 2)\n"
"# These reassignments are OK: ``tuple[int, ...]`` indicates x can be of any "
"length\n"
"x = (1, 2, 3)\n"
"x = ()\n"
"# This reassignment is an error: all elements in ``x`` must be ints\n"
"x = (\"foo\", \"bar\")\n"
"\n"
"# ``y`` can only ever be assigned to an empty tuple\n"
"y: tuple[()] = ()\n"
"\n"
"z: tuple = (\"foo\", \"bar\")\n"
"# These reassignments are OK: plain ``tuple`` is equivalent to "
"``tuple[Any, ...]``\n"
"z = (1, 2, 3)\n"
"z = ()"
msgstr ""
#: ../../library/typing.rst:406
msgid "The type of class objects"
msgstr "類別物件的型別"
#: ../../library/typing.rst:408
msgid ""
"A variable annotated with ``C`` may accept a value of type ``C``. In "
"contrast, a variable annotated with ``type[C]`` (or deprecated :class:"
"`typing.Type[C] <Type>`) may accept values that are classes themselves -- "
"specifically, it will accept the *class object* of ``C``. For example::"
msgstr ""
"一個變數被註釋為 ``C`` 可以接受一個型別為 ``C`` 的值。相對的,一個變數備註解"
"為 ``type[C]`` \\ (或已棄用的 :class:`typing.Type[C] <Type>`)\\ 可以接受本"
"身為該類別的值 -- 具體來說,他可能會接受 ``C`` 的\\ *類別物件*\\。舉例來"
"說: ::"
#: ../../library/typing.rst:414
msgid ""
"a = 3 # Has type ``int``\n"
"b = int # Has type ``type[int]``\n"
"c = type(a) # Also has type ``type[int]``"
msgstr ""
#: ../../library/typing.rst:418
msgid "Note that ``type[C]`` is covariant::"
msgstr "請記得 ``type[C]`` 是共變 (covariant) 的: ::"
#: ../../library/typing.rst:420
msgid ""
"class User: ...\n"
"class ProUser(User): ...\n"
"class TeamUser(User): ...\n"
"\n"
"def make_new_user(user_class: type[User]) -> User:\n"
" # ...\n"
" return user_class()\n"
"\n"
"make_new_user(User) # OK\n"
"make_new_user(ProUser) # Also OK: ``type[ProUser]`` is a subtype of "
"``type[User]``\n"
"make_new_user(TeamUser) # Still fine\n"
"make_new_user(User()) # Error: expected ``type[User]`` but got ``User``\n"
"make_new_user(int) # Error: ``type[int]`` is not a subtype of "
"``type[User]``"
msgstr ""
#: ../../library/typing.rst:434
msgid ""
"The only legal parameters for :class:`type` are classes, :data:`Any`, :ref:"
"`type variables <generics>`, and unions of any of these types. For example::"
msgstr ""
":class:`type` 僅有的合法參數是類別、:data:`Any`、:ref:`型別變數 "
"<generics>`\\ 以及這些型別任意組合成的聯集。舉例來說: ::"
#: ../../library/typing.rst:438
msgid ""
"def new_non_team_user(user_class: type[BasicUser | ProUser]): ...\n"
"\n"
"new_non_team_user(BasicUser) # OK\n"
"new_non_team_user(ProUser) # OK\n"
"new_non_team_user(TeamUser) # Error: ``type[TeamUser]`` is not a subtype\n"
" # of ``type[BasicUser | ProUser]``\n"
"new_non_team_user(User) # Also an error"
msgstr ""
#: ../../library/typing.rst:446
msgid ""
"``type[Any]`` is equivalent to :class:`type`, which is the root of Python's :"
"ref:`metaclass hierarchy <metaclasses>`."
msgstr ""
"``type[Any]`` 等價於 :class:`type` ,其為 Python :ref:`metaclass 階層結構 "
"(hierachy) <metaclasses>`。"
#: ../../library/typing.rst:453
msgid "Annotating generators and coroutines"
msgstr ""
#: ../../library/typing.rst:455
msgid ""
"A generator can be annotated using the generic type :class:"
"`Generator[YieldType, SendType, ReturnType] <collections.abc.Generator>`. "
"For example::"
msgstr ""
#: ../../library/typing.rst:459
msgid ""
"def echo_round() -> Generator[int, float, str]:\n"
" sent = yield 0\n"
" while sent >= 0:\n"
" sent = yield round(sent)\n"
" return 'Done'"
msgstr ""
"def echo_round() -> Generator[int, float, str]:\n"
" sent = yield 0\n"
" while sent >= 0:\n"
" sent = yield round(sent)\n"
" return 'Done'"
#: ../../library/typing.rst:465
msgid ""
"Note that unlike many other generic classes in the standard library, the "
"``SendType`` of :class:`~collections.abc.Generator` behaves contravariantly, "
"not covariantly or invariantly."
msgstr ""
#: ../../library/typing.rst:469
msgid ""
"The ``SendType`` and ``ReturnType`` parameters default to :const:`!None`::"
msgstr ""
#: ../../library/typing.rst:471
msgid ""
"def infinite_stream(start: int) -> Generator[int]:\n"
" while True:\n"
" yield start\n"
" start += 1"
msgstr ""
"def infinite_stream(start: int) -> Generator[int]:\n"
" while True:\n"
" yield start\n"
" start += 1"
#: ../../library/typing.rst:476
msgid "It is also possible to set these types explicitly::"
msgstr ""
#: ../../library/typing.rst:478
msgid ""
"def infinite_stream(start: int) -> Generator[int, None, None]:\n"
" while True:\n"
" yield start\n"
" start += 1"
msgstr ""
"def infinite_stream(start: int) -> Generator[int, None, None]:\n"
" while True:\n"
" yield start\n"
" start += 1"
#: ../../library/typing.rst:483
msgid ""
"Simple generators that only ever yield values can also be annotated as "
"having a return type of either :class:`Iterable[YieldType] <collections.abc."
"Iterable>` or :class:`Iterator[YieldType] <collections.abc.Iterator>`::"
msgstr ""
#: ../../library/typing.rst:488
msgid ""
"def infinite_stream(start: int) -> Iterator[int]:\n"
" while True:\n"
" yield start\n"
" start += 1"
msgstr ""
"def infinite_stream(start: int) -> Iterator[int]:\n"
" while True:\n"
" yield start\n"
" start += 1"
#: ../../library/typing.rst:493
msgid ""
"Async generators are handled in a similar fashion, but don't expect a "
"``ReturnType`` type argument (:class:`AsyncGenerator[YieldType, SendType] "
"<collections.abc.AsyncGenerator>`). The ``SendType`` argument defaults to :"
"const:`!None`, so the following definitions are equivalent::"
msgstr ""
#: ../../library/typing.rst:499
msgid ""
"async def infinite_stream(start: int) -> AsyncGenerator[int]:\n"
" while True:\n"
" yield start\n"
" start = await increment(start)\n"
"\n"
"async def infinite_stream(start: int) -> AsyncGenerator[int, None]:\n"
" while True:\n"
" yield start\n"
" start = await increment(start)"
msgstr ""
"async def infinite_stream(start: int) -> AsyncGenerator[int]:\n"
" while True:\n"
" yield start\n"
" start = await increment(start)\n"
"\n"
"async def infinite_stream(start: int) -> AsyncGenerator[int, None]:\n"
" while True:\n"
" yield start\n"
" start = await increment(start)"
#: ../../library/typing.rst:509
msgid ""
"As in the synchronous case, :class:`AsyncIterable[YieldType] <collections."
"abc.AsyncIterable>` and :class:`AsyncIterator[YieldType] <collections.abc."
"AsyncIterator>` are available as well::"
msgstr ""
#: ../../library/typing.rst:514
msgid ""
"async def infinite_stream(start: int) -> AsyncIterator[int]:\n"
" while True:\n"
" yield start\n"
" start = await increment(start)"
msgstr ""
"async def infinite_stream(start: int) -> AsyncIterator[int]:\n"
" while True:\n"
" yield start\n"
" start = await increment(start)"
#: ../../library/typing.rst:519
msgid ""
"Coroutines can be annotated using :class:`Coroutine[YieldType, SendType, "
"ReturnType] <collections.abc.Coroutine>`. Generic arguments correspond to "
"those of :class:`~collections.abc.Generator`, for example::"
msgstr ""
#: ../../library/typing.rst:524
msgid ""
"from collections.abc import Coroutine\n"
"c: Coroutine[list[str], str, int] # Some coroutine defined elsewhere\n"
"x = c.send('hi') # Inferred type of 'x' is list[str]\n"
"async def bar() -> None:\n"
" y = await c # Inferred type of 'y' is int"
msgstr ""
#: ../../library/typing.rst:533
msgid "User-defined generic types"
msgstr "使用者定義泛型型別"
#: ../../library/typing.rst:535
msgid "A user-defined class can be defined as a generic class."
msgstr "一個使用者定義的類別可以被定義成一個泛型類別。"
#: ../../library/typing.rst:539
msgid ""
"from logging import Logger\n"
"\n"
"class LoggedVar[T]:\n"
" def __init__(self, value: T, name: str, logger: Logger) -> None:\n"
" self.name = name\n"
" self.logger = logger\n"
" self.value = value\n"
"\n"
" def set(self, new: T) -> None:\n"
" self.log('Set ' + repr(self.value))\n"
" self.value = new\n"
"\n"
" def get(self) -> T:\n"
" self.log('Get ' + repr(self.value))\n"
" return self.value\n"
"\n"
" def log(self, message: str) -> None:\n"
" self.logger.info('%s: %s', self.name, message)"
msgstr ""
"from logging import Logger\n"
"\n"
"class LoggedVar[T]:\n"
" def __init__(self, value: T, name: str, logger: Logger) -> None:\n"
" self.name = name\n"
" self.logger = logger\n"
" self.value = value\n"
"\n"
" def set(self, new: T) -> None:\n"
" self.log('Set ' + repr(self.value))\n"
" self.value = new\n"
"\n"
" def get(self) -> T:\n"
" self.log('Get ' + repr(self.value))\n"
" return self.value\n"
"\n"
" def log(self, message: str) -> None:\n"
" self.logger.info('%s: %s', self.name, message)"
#: ../../library/typing.rst:558
msgid ""
"This syntax indicates that the class ``LoggedVar`` is parameterised around a "
"single :ref:`type variable <typevar>` ``T`` . This also makes ``T`` valid as "
"a type within the class body."
msgstr ""
"這個語法指出類別 ``LoggedVar`` 透過一個單一的 :ref:`型別變數 <typevar>` "
"``T`` 進行參數化 (parameterised)。這使得 ``T`` 在類別中有效的成為型別。"
#: ../../library/typing.rst:562
msgid ""
"Generic classes implicitly inherit from :class:`Generic`. For compatibility "
"with Python 3.11 and lower, it is also possible to inherit explicitly from :"
"class:`Generic` to indicate a generic class::"
msgstr ""
"泛型類別隱性繼承了 :class:`Generic`。為了相容 Python 3.11 及更早版本,也可以"
"明確的繼承 :class:`Generic` 並指出是一個泛型類別: ::"
#: ../../library/typing.rst:566
msgid ""
"from typing import TypeVar, Generic\n"
"\n"
"T = TypeVar('T')\n"
"\n"
"class LoggedVar(Generic[T]):\n"
" ..."
msgstr ""
"from typing import TypeVar, Generic\n"
"\n"
"T = TypeVar('T')\n"
"\n"
"class LoggedVar(Generic[T]):\n"
" ..."
#: ../../library/typing.rst:573
msgid ""