Debian Codegraph @

Lib/pydoc_data/topics.py

raw
1 # Autogenerated by Sphinx on Sun May 10 13:21:26 2026
2 # as part of the release process.
3
4 topics = {
5 'assert': r'''The "assert" statement
6 **********************
7
8 Assert statements are a convenient way to insert debugging assertions
9 into a program:
10
11 assert_stmt: "assert" expression ["," expression]
12
13 The simple form, "assert expression", is equivalent to
14
15 if __debug__:
16 if not expression: raise AssertionError
17
18 The extended form, "assert expression1, expression2", is equivalent to
19
20 if __debug__:
21 if not expression1: raise AssertionError(expression2)
22
23 These equivalences assume that "__debug__" and "AssertionError" refer
24 to the built-in variables with those names. In the current
25 implementation, the built-in variable "__debug__" is "True" under
26 normal circumstances, "False" when optimization is requested (command
27 line option "-O"). The current code generator emits no code for an
28 "assert" statement when optimization is requested at compile time.
29 Note that it is unnecessary to include the source code for the
30 expression that failed in the error message; it will be displayed as
31 part of the stack trace.
32
33 Assignments to "__debug__" are illegal. The value for the built-in
34 variable is determined when the interpreter starts.
35 ''',
36 'assignment': r'''Assignment statements
37 *********************
38
39 Assignment statements are used to (re)bind names to values and to
40 modify attributes or items of mutable objects:
41
42 assignment_stmt: (target_list "=")+ (starred_expression | yield_expression)
43 target_list: target ("," target)* [","]
44 target: identifier
45 | "(" [target_list] ")"
46 | "[" [target_list] "]"
47 | attributeref
48 | subscription
49 | "*" target
50
51 (See section Primaries for the syntax definitions for *attributeref*
52 and *subscription*.)
53
54 An assignment statement evaluates the expression list (remember that
55 this can be a single expression or a comma-separated list, the latter
56 yielding a tuple) and assigns the single resulting object to each of
57 the target lists, from left to right.
58
59 Assignment is defined recursively depending on the form of the target
60 (list). When a target is part of a mutable object (an attribute
61 reference or subscription), the mutable object must ultimately perform
62 the assignment and decide about its validity, and may raise an
63 exception if the assignment is unacceptable. The rules observed by
64 various types and the exceptions raised are given with the definition
65 of the object types (see section The standard type hierarchy).
66
67 Assignment of an object to a target list, optionally enclosed in
68 parentheses or square brackets, is recursively defined as follows.
69
70 * If the target list is a single target with no trailing comma,
71 optionally in parentheses, the object is assigned to that target.
72
73 * Else:
74
75 * If the target list contains one target prefixed with an asterisk,
76 called a “starred” target: The object must be an iterable with at
77 least as many items as there are targets in the target list, minus
78 one. The first items of the iterable are assigned, from left to
79 right, to the targets before the starred target. The final items
80 of the iterable are assigned to the targets after the starred
81 target. A list of the remaining items in the iterable is then
82 assigned to the starred target (the list can be empty).
83
84 * Else: The object must be an iterable with the same number of items
85 as there are targets in the target list, and the items are
86 assigned, from left to right, to the corresponding targets.
87
88 Assignment of an object to a single target is recursively defined as
89 follows.
90
91 * If the target is an identifier (name):
92
93 * If the name does not occur in a "global" or "nonlocal" statement
94 in the current code block: the name is bound to the object in the
95 current local namespace.
96
97 * Otherwise: the name is bound to the object in the global namespace
98 or the outer namespace determined by "nonlocal", respectively.
99
100 The name is rebound if it was already bound. This may cause the
101 reference count for the object previously bound to the name to reach
102 zero, causing the object to be deallocated and its destructor (if it
103 has one) to be called.
104
105 * If the target is an attribute reference: The primary expression in
106 the reference is evaluated. It should yield an object with
107 assignable attributes; if this is not the case, "TypeError" is
108 raised. That object is then asked to assign the assigned object to
109 the given attribute; if it cannot perform the assignment, it raises
110 an exception (usually but not necessarily "AttributeError").
111
112 Note: If the object is a class instance and the attribute reference
113 occurs on both sides of the assignment operator, the right-hand side
114 expression, "a.x" can access either an instance attribute or (if no
115 instance attribute exists) a class attribute. The left-hand side
116 target "a.x" is always set as an instance attribute, creating it if
117 necessary. Thus, the two occurrences of "a.x" do not necessarily
118 refer to the same attribute: if the right-hand side expression
119 refers to a class attribute, the left-hand side creates a new
120 instance attribute as the target of the assignment:
121
122 class Cls:
123 x = 3 # class variable
124 inst = Cls()
125 inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3
126
127 This description does not necessarily apply to descriptor
128 attributes, such as properties created with "property()".
129
130 * If the target is a subscription: The primary expression in the
131 reference is evaluated. Next, the subscript expression is evaluated.
132 Then, the primary’s "__setitem__()" method is called with two
133 arguments: the subscript and the assigned object.
134
135 Typically, "__setitem__()" is defined on mutable sequence objects
136 (such as lists) and mapping objects (such as dictionaries), and
137 behaves as follows.
138
139 If the primary is a mutable sequence object (such as a list), the
140 subscript must yield an integer. If it is negative, the sequence’s
141 length is added to it. The resulting value must be a nonnegative
142 integer less than the sequence’s length, and the sequence is asked
143 to assign the assigned object to its item with that index. If the
144 index is out of range, "IndexError" is raised (assignment to a
145 subscripted sequence cannot add new items to a list).
146
147 If the primary is a mapping object (such as a dictionary), the
148 subscript must have a type compatible with the mapping’s key type,
149 and the mapping is then asked to create a key/value pair which maps
150 the subscript to the assigned object. This can either replace an
151 existing key/value pair with the same key value, or insert a new
152 key/value pair (if no key with the same value existed).
153
154 If the target is a slicing: The primary expression should evaluate
155 to a mutable sequence object (such as a list). The assigned object
156 should be *iterable*. The slicing’s lower and upper bounds should be
157 integers; if they are "None" (or not present), the defaults are zero
158 and the sequence’s length. If either bound is negative, the
159 sequence’s length is added to it. The resulting bounds are clipped
160 to lie between zero and the sequence’s length, inclusive. Finally,
161 the sequence object is asked to replace the slice with the items of
162 the assigned sequence. The length of the slice may be different
163 from the length of the assigned sequence, thus changing the length
164 of the target sequence, if the target sequence allows it.
165
166 Although the definition of assignment implies that overlaps between
167 the left-hand side and the right-hand side are ‘simultaneous’ (for
168 example "a, b = b, a" swaps two variables), overlaps *within* the
169 collection of assigned-to variables occur left-to-right, sometimes
170 resulting in confusion. For instance, the following program prints
171 "[0, 2]":
172
173 x = [0, 1]
174 i = 0
175 i, x[i] = 1, 2 # i is updated, then x[i] is updated
176 print(x)
177
178 See also:
179
180 **PEP 3132** - Extended Iterable Unpacking
181 The specification for the "*target" feature.
182
183
184 Augmented assignment statements
185 ===============================
186
187 Augmented assignment is the combination, in a single statement, of a
188 binary operation and an assignment statement:
189
190 augmented_assignment_stmt: augtarget augop (expression_list | yield_expression)
191 augtarget: identifier | attributeref | subscription
192 augop: "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="
193 | ">>=" | "<<=" | "&=" | "^=" | "|="
194
195 (See section Primaries for the syntax definitions of the last three
196 symbols.)
197
198 An augmented assignment evaluates the target (which, unlike normal
199 assignment statements, cannot be an unpacking) and the expression
200 list, performs the binary operation specific to the type of assignment
201 on the two operands, and assigns the result to the original target.
202 The target is only evaluated once.
203
204 An augmented assignment statement like "x += 1" can be rewritten as "x
205 = x + 1" to achieve a similar, but not exactly equal effect. In the
206 augmented version, "x" is only evaluated once. Also, when possible,
207 the actual operation is performed *in-place*, meaning that rather than
208 creating a new object and assigning that to the target, the old object
209 is modified instead.
210
211 Unlike normal assignments, augmented assignments evaluate the left-
212 hand side *before* evaluating the right-hand side. For example, "a[i]
213 += f(x)" first looks-up "a[i]", then it evaluates "f(x)" and performs
214 the addition, and lastly, it writes the result back to "a[i]".
215
216 With the exception of assigning to tuples and multiple targets in a
217 single statement, the assignment done by augmented assignment
218 statements is handled the same way as normal assignments. Similarly,
219 with the exception of the possible *in-place* behavior, the binary
220 operation performed by augmented assignment is the same as the normal
221 binary operations.
222
223 For targets which are attribute references, the same caveat about
224 class and instance attributes applies as for regular assignments.
225
226
227 Annotated assignment statements
228 ===============================
229
230 *Annotation* assignment is the combination, in a single statement, of
231 a variable or attribute annotation and an optional assignment
232 statement:
233
234 annotated_assignment_stmt: augtarget ":" expression
235 ["=" (starred_expression | yield_expression)]
236
237 The difference from normal Assignment statements is that only a single
238 target is allowed.
239
240 The assignment target is considered “simple” if it consists of a
241 single name that is not enclosed in parentheses. For simple assignment
242 targets, if in class or module scope, the annotations are gathered in
243 a lazily evaluated annotation scope. The annotations can be evaluated
244 using the "__annotations__" attribute of a class or module, or using
245 the facilities in the "annotationlib" module.
246
247 If the assignment target is not simple (an attribute, subscript node,
248 or parenthesized name), the annotation is never evaluated.
249
250 If a name is annotated in a function scope, then this name is local
251 for that scope. Annotations are never evaluated and stored in function
252 scopes.
253
254 If the right hand side is present, an annotated assignment performs
255 the actual assignment as if there was no annotation present. If the
256 right hand side is not present for an expression target, then the
257 interpreter evaluates the target except for the last "__setitem__()"
258 or "__setattr__()" call.
259
260 See also:
261
262 **PEP 526** - Syntax for Variable Annotations
263 The proposal that added syntax for annotating the types of
264 variables (including class variables and instance variables),
265 instead of expressing them through comments.
266
267 **PEP 484** - Type hints
268 The proposal that added the "typing" module to provide a standard
269 syntax for type annotations that can be used in static analysis
270 tools and IDEs.
271
272 Changed in version 3.8: Now annotated assignments allow the same
273 expressions in the right hand side as regular assignments. Previously,
274 some expressions (like un-parenthesized tuple expressions) caused a
275 syntax error.
276
277 Changed in version 3.14: Annotations are now lazily evaluated in a
278 separate annotation scope. If the assignment target is not simple,
279 annotations are never evaluated.
280 ''',
281 'assignment-expressions': r'''Assignment expressions
282 **********************
283
284 assignment_expression: [identifier ":="] expression
285
286 An assignment expression (sometimes also called a “named expression”
287 or “walrus”) assigns an "expression" to an "identifier", while also
288 returning the value of the "expression".
289
290 One common use case is when handling matched regular expressions:
291
292 if matching := pattern.search(data):
293 do_something(matching)
294
295 Or, when processing a file stream in chunks:
296
297 while chunk := file.read(9000):
298 process(chunk)
299
300 Assignment expressions must be surrounded by parentheses when used as
301 expression statements and when used as sub-expressions in slicing,
302 conditional, lambda, keyword-argument, and comprehension-if
303 expressions and in "assert", "with", and "assignment" statements. In
304 all other places where they can be used, parentheses are not required,
305 including in "if" and "while" statements.
306
307 Added in version 3.8: See **PEP 572** for more details about
308 assignment expressions.
309 ''',
310 'async': r'''Coroutines
311 **********
312
313 Added in version 3.5.
314
315
316 Coroutine function definition
317 =============================
318
319 async_funcdef: [decorators] "async" "def" funcname "(" [parameter_list] ")"
320 ["->" expression] ":" suite
321
322 Execution of Python coroutines can be suspended and resumed at many
323 points (see *coroutine*). "await" expressions, "async for" and "async
324 with" can only be used in the body of a coroutine function.
325
326 Functions defined with "async def" syntax are always coroutine
327 functions, even if they do not contain "await" or "async" keywords.
328
329 It is a "SyntaxError" to use a "yield from" expression inside the body
330 of a coroutine function.
331
332 An example of a coroutine function:
333
334 async def func(param1, param2):
335 do_stuff()
336 await some_coroutine()
337
338 Changed in version 3.7: "await" and "async" are now keywords;
339 previously they were only treated as such inside the body of a
340 coroutine function.
341
342
343 The "async for" statement
344 =========================
345
346 async_for_stmt: "async" for_stmt
347
348 An *asynchronous iterable* provides an "__aiter__" method that
349 directly returns an *asynchronous iterator*, which can call
350 asynchronous code in its "__anext__" method.
351
352 The "async for" statement allows convenient iteration over
353 asynchronous iterables.
354
355 The following code:
356
357 async for TARGET in ITER:
358 SUITE
359 else:
360 SUITE2
361
362 Is semantically equivalent to:
363
364 iter = (ITER).__aiter__()
365 running = True
366
367 while running:
368 try:
369 TARGET = await iter.__anext__()
370 except StopAsyncIteration:
371 running = False
372 else:
373 SUITE
374 else:
375 SUITE2
376
377 except that implicit special method lookup is used for "__aiter__()"
378 and "__anext__()".
379
380 It is a "SyntaxError" to use an "async for" statement outside the body
381 of a coroutine function.
382
383
384 The "async with" statement
385 ==========================
386
387 async_with_stmt: "async" with_stmt
388
389 An *asynchronous context manager* is a *context manager* that is able
390 to suspend execution in its *enter* and *exit* methods.
391
392 The following code:
393
394 async with EXPRESSION as TARGET:
395 SUITE
396
397 is semantically equivalent to:
398
399 manager = (EXPRESSION)
400 aenter = manager.__aenter__
401 aexit = manager.__aexit__
402 value = await aenter()
403 hit_except = False
404
405 try:
406 TARGET = value
407 SUITE
408 except:
409 hit_except = True
410 if not await aexit(*sys.exc_info()):
411 raise
412 finally:
413 if not hit_except:
414 await aexit(None, None, None)
415
416 except that implicit special method lookup is used for "__aenter__()"
417 and "__aexit__()".
418
419 It is a "SyntaxError" to use an "async with" statement outside the
420 body of a coroutine function.
421
422 See also:
423
424 **PEP 492** - Coroutines with async and await syntax
425 The proposal that made coroutines a proper standalone concept in
426 Python, and added supporting syntax.
427 ''',
428 'atom-identifiers': r'''Identifiers (Names)
429 *******************
430
431 An identifier occurring as an atom is a name. See section Names
432 (identifiers and keywords) for lexical definition and section Naming
433 and binding for documentation of naming and binding.
434
435 When the name is bound to an object, evaluation of the atom yields
436 that object. When a name is not bound, an attempt to evaluate it
437 raises a "NameError" exception.
438
439
440 Private name mangling
441 =====================
442
443 When an identifier that textually occurs in a class definition begins
444 with two or more underscore characters and does not end in two or more
445 underscores, it is considered a *private name* of that class.
446
447 See also: The class specifications.
448
449 More precisely, private names are transformed to a longer form before
450 code is generated for them. If the transformed name is longer than
451 255 characters, implementation-defined truncation may happen.
452
453 The transformation is independent of the syntactical context in which
454 the identifier is used but only the following private identifiers are
455 mangled:
456
457 * Any name used as the name of a variable that is assigned or read or
458 any name of an attribute being accessed.
459
460 The "__name__" attribute of nested functions, classes, and type
461 aliases is however not mangled.
462
463 * The name of imported modules, e.g., "__spam" in "import __spam". If
464 the module is part of a package (i.e., its name contains a dot), the
465 name is *not* mangled, e.g., the "__foo" in "import __foo.bar" is
466 not mangled.
467
468 * The name of an imported member, e.g., "__f" in "from spam import
469 __f".
470
471 The transformation rule is defined as follows:
472
473 * The class name, with leading underscores removed and a single
474 leading underscore inserted, is inserted in front of the identifier,
475 e.g., the identifier "__spam" occurring in a class named "Foo",
476 "_Foo" or "__Foo" is transformed to "_Foo__spam".
477
478 * If the class name consists only of underscores, the transformation
479 is the identity, e.g., the identifier "__spam" occurring in a class
480 named "_" or "__" is left as is.
481 ''',
482 'atom-literals': r'''Literals
483 ********
484
485 A *literal* is a textual representation of a value. Python supports
486 numeric, string and bytes literals. Format strings and template
487 strings are treated as string literals.
488
489 Numeric literals consist of a single "NUMBER" token, which names an
490 integer, floating-point number, or an imaginary number. See the
491 Numeric literals section in Lexical analysis documentation for
492 details.
493
494 String and bytes literals may consist of several tokens. See section
495 String literal concatenation for details.
496
497 Note that negative and complex numbers, like "-3" or "3+4.2j", are
498 syntactically not literals, but unary or binary arithmetic operations
499 involving the "-" or "+" operator.
500
501 Evaluation of a literal yields an object of the given type ("int",
502 "float", "complex", "str", "bytes", or "Template") with the given
503 value. The value may be approximated in the case of floating-point and
504 imaginary literals.
505
506 The formal grammar for literals is:
507
508 literal: strings | NUMBER
509
510
511 Literals and object identity
512 ============================
513
514 All literals correspond to immutable data types, and hence the
515 object’s identity is less important than its value. Multiple
516 evaluations of literals with the same value (either the same
517 occurrence in the program text or a different occurrence) may obtain
518 the same object or a different object with the same value.
519
520 CPython implementation detail: For example, in CPython, *small*
521 integers with the same value evaluate to the same object:
522
523 >>> x = 7
524 >>> y = 7
525 >>> x is y
526 True
527
528 However, large integers evaluate to different objects:
529
530 >>> x = 123456789
531 >>> y = 123456789
532 >>> x is y
533 False
534
535 This behavior may change in future versions of CPython. In particular,
536 the boundary between “small” and “large” integers has already changed
537 in the past.CPython will emit a "SyntaxWarning" when you compare
538 literals using "is":
539
540 >>> x = 7
541 >>> x is 7
542 <input>:1: SyntaxWarning: "is" with 'int' literal. Did you mean "=="?
543 True
544
545 See When can I rely on identity tests with the is operator? for more
546 information.
547
548 Template strings are immutable but may reference mutable objects as
549 "Interpolation" values. For the purposes of this section, two
550 t-strings have the “same value” if both their structure and the
551 *identity* of the values match.
552
553 **CPython implementation detail:** Currently, each evaluation of a
554 template string results in a different object.
555
556
557 String literal concatenation
558 ============================
559
560 Multiple adjacent string or bytes literals, possibly using different
561 quoting conventions, are allowed, and their meaning is the same as
562 their concatenation:
563
564 >>> "hello" 'world'
565 "helloworld"
566
567 This feature is defined at the syntactical level, so it only works
568 with literals. To concatenate string expressions at run time, the ‘+’
569 operator may be used:
570
571 >>> greeting = "Hello"
572 >>> space = " "
573 >>> name = "Blaise"
574 >>> print(greeting + space + name) # not: print(greeting space name)
575 Hello Blaise
576
577 Literal concatenation can freely mix raw strings, triple-quoted
578 strings, and formatted string literals. For example:
579
580 >>> "Hello" r', ' f"{name}!"
581 "Hello, Blaise!"
582
583 This feature can be used to reduce the number of backslashes needed,
584 to split long strings conveniently across long lines, or even to add
585 comments to parts of strings. For example:
586
587 re.compile("[A-Za-z_]" # letter or underscore
588 "[A-Za-z0-9_]*" # letter, digit or underscore
589 )
590
591 However, bytes literals may only be combined with other byte literals;
592 not with string literals of any kind. Also, template string literals
593 may only be combined with other template string literals:
594
595 >>> t"Hello" t"{name}!"
596 Template(strings=('Hello', '!'), interpolations=(...))
597
598 Formally:
599
600 strings: (STRING | fstring)+ | tstring+
601 ''',
602 'attribute-access': r'''Customizing attribute access
603 ****************************
604
605 The following methods can be defined to customize the meaning of
606 attribute access (use of, assignment to, or deletion of "x.name") for
607 class instances.
608
609 object.__getattr__(self, name)
610
611 Called when the default attribute access fails with an
612 "AttributeError" (either "__getattribute__()" raises an
613 "AttributeError" because *name* is not an instance attribute or an
614 attribute in the class tree for "self"; or "__get__()" of a *name*
615 property raises "AttributeError"). This method should either
616 return the (computed) attribute value or raise an "AttributeError"
617 exception. The "object" class itself does not provide this method.
618
619 Note that if the attribute is found through the normal mechanism,
620 "__getattr__()" is not called. (This is an intentional asymmetry
621 between "__getattr__()" and "__setattr__()".) This is done both for
622 efficiency reasons and because otherwise "__getattr__()" would have
623 no way to access other attributes of the instance. Note that at
624 least for instance variables, you can take total control by not
625 inserting any values in the instance attribute dictionary (but
626 instead inserting them in another object). See the
627 "__getattribute__()" method below for a way to actually get total
628 control over attribute access.
629
630 object.__getattribute__(self, name)
631
632 Called unconditionally to implement attribute accesses for
633 instances of the class. If the class also defines "__getattr__()",
634 the latter will not be called unless "__getattribute__()" either
635 calls it explicitly or raises an "AttributeError". This method
636 should return the (computed) attribute value or raise an
637 "AttributeError" exception. In order to avoid infinite recursion in
638 this method, its implementation should always call the base class
639 method with the same name to access any attributes it needs, for
640 example, "object.__getattribute__(self, name)".
641
642 Note:
643
644 This method may still be bypassed when looking up special methods
645 as the result of implicit invocation via language syntax or
646 built-in functions. See Special method lookup.
647
648 For certain sensitive attribute accesses, raises an auditing event
649 "object.__getattr__" with arguments "obj" and "name".
650
651 object.__setattr__(self, name, value)
652
653 Called when an attribute assignment is attempted. This is called
654 instead of the normal mechanism (i.e. store the value in the
655 instance dictionary). *name* is the attribute name, *value* is the
656 value to be assigned to it.
657
658 If "__setattr__()" wants to assign to an instance attribute, it
659 should call the base class method with the same name, for example,
660 "object.__setattr__(self, name, value)".
661
662 For certain sensitive attribute assignments, raises an auditing
663 event "object.__setattr__" with arguments "obj", "name", "value".
664
665 object.__delattr__(self, name)
666
667 Like "__setattr__()" but for attribute deletion instead of
668 assignment. This should only be implemented if "del obj.name" is
669 meaningful for the object.
670
671 For certain sensitive attribute deletions, raises an auditing event
672 "object.__delattr__" with arguments "obj" and "name".
673
674 object.__dir__(self)
675
676 Called when "dir()" is called on the object. An iterable must be
677 returned. "dir()" converts the returned iterable to a list and
678 sorts it.
679
680
681 Customizing module attribute access
682 ===================================
683
684 module.__getattr__()
685 module.__dir__()
686
687 Special names "__getattr__" and "__dir__" can be also used to
688 customize access to module attributes. The "__getattr__" function at
689 the module level should accept one argument which is the name of an
690 attribute and return the computed value or raise an "AttributeError".
691 If an attribute is not found on a module object through the normal
692 lookup, i.e. "object.__getattribute__()", then "__getattr__" is
693 searched in the module "__dict__" before raising an "AttributeError".
694 If found, it is called with the attribute name and the result is
695 returned.
696
697 The "__dir__" function should accept no arguments, and return an
698 iterable of strings that represents the names accessible on module. If
699 present, this function overrides the standard "dir()" search on a
700 module.
701
702 module.__class__
703
704 For a more fine grained customization of the module behavior (setting
705 attributes, properties, etc.), one can set the "__class__" attribute
706 of a module object to a subclass of "types.ModuleType". For example:
707
708 import sys
709 from types import ModuleType
710
711 class VerboseModule(ModuleType):
712 def __repr__(self):
713 return f'Verbose {self.__name__}'
714
715 def __setattr__(self, attr, value):
716 print(f'Setting {attr}...')
717 super().__setattr__(attr, value)
718
719 sys.modules[__name__].__class__ = VerboseModule
720
721 Note:
722
723 Defining module "__getattr__" and setting module "__class__" only
724 affect lookups made using the attribute access syntax – directly
725 accessing the module globals (whether by code within the module, or
726 via a reference to the module’s globals dictionary) is unaffected.
727
728 Changed in version 3.5: "__class__" module attribute is now writable.
729
730 Added in version 3.7: "__getattr__" and "__dir__" module attributes.
731
732 See also:
733
734 **PEP 562** - Module __getattr__ and __dir__
735 Describes the "__getattr__" and "__dir__" functions on modules.
736
737
738 Implementing Descriptors
739 ========================
740
741 The following methods only apply when an instance of the class
742 containing the method (a so-called *descriptor* class) appears in an
743 *owner* class (the descriptor must be in either the owner’s class
744 dictionary or in the class dictionary for one of its parents). In the
745 examples below, “the attribute” refers to the attribute whose name is
746 the key of the property in the owner class’ "__dict__". The "object"
747 class itself does not implement any of these protocols.
748
749 object.__get__(self, instance, owner=None)
750
751 Called to get the attribute of the owner class (class attribute
752 access) or of an instance of that class (instance attribute
753 access). The optional *owner* argument is the owner class, while
754 *instance* is the instance that the attribute was accessed through,
755 or "None" when the attribute is accessed through the *owner*.
756
757 This method should return the computed attribute value or raise an
758 "AttributeError" exception.
759
760 **PEP 252** specifies that "__get__()" is callable with one or two
761 arguments. Python’s own built-in descriptors support this
762 specification; however, it is likely that some third-party tools
763 have descriptors that require both arguments. Python’s own
764 "__getattribute__()" implementation always passes in both arguments
765 whether they are required or not.
766
767 object.__set__(self, instance, value)
768
769 Called to set the attribute on an instance *instance* of the owner
770 class to a new value, *value*.
771
772 Note, adding "__set__()" or "__delete__()" changes the kind of
773 descriptor to a “data descriptor”. See Invoking Descriptors for
774 more details.
775
776 object.__delete__(self, instance)
777
778 Called to delete the attribute on an instance *instance* of the
779 owner class.
780
781 Instances of descriptors may also have the "__objclass__" attribute
782 present:
783
784 object.__objclass__
785
786 The attribute "__objclass__" is interpreted by the "inspect" module
787 as specifying the class where this object was defined (setting this
788 appropriately can assist in runtime introspection of dynamic class
789 attributes). For callables, it may indicate that an instance of the
790 given type (or a subclass) is expected or required as the first
791 positional argument (for example, CPython sets this attribute for
792 unbound methods that are implemented in C).
793
794
795 Invoking Descriptors
796 ====================
797
798 In general, a descriptor is an object attribute with “binding
799 behavior”, one whose attribute access has been overridden by methods
800 in the descriptor protocol: "__get__()", "__set__()", and
801 "__delete__()". If any of those methods are defined for an object, it
802 is said to be a descriptor.
803
804 The default behavior for attribute access is to get, set, or delete
805 the attribute from an object’s dictionary. For instance, "a.x" has a
806 lookup chain starting with "a.__dict__['x']", then
807 "type(a).__dict__['x']", and continuing through the base classes of
808 "type(a)" excluding metaclasses.
809
810 However, if the looked-up value is an object defining one of the
811 descriptor methods, then Python may override the default behavior and
812 invoke the descriptor method instead. Where this occurs in the
813 precedence chain depends on which descriptor methods were defined and
814 how they were called.
815
816 The starting point for descriptor invocation is a binding, "a.x". How
817 the arguments are assembled depends on "a":
818
819 Direct Call
820 The simplest and least common call is when user code directly
821 invokes a descriptor method: "x.__get__(a)".
822
823 Instance Binding
824 If binding to an object instance, "a.x" is transformed into the
825 call: "type(a).__dict__['x'].__get__(a, type(a))".
826
827 Class Binding
828 If binding to a class, "A.x" is transformed into the call:
829 "A.__dict__['x'].__get__(None, A)".
830
831 Super Binding
832 A dotted lookup such as "super(A, a).x" searches
833 "a.__class__.__mro__" for a base class "B" following "A" and then
834 returns "B.__dict__['x'].__get__(a, A)". If not a descriptor, "x"
835 is returned unchanged.
836
837 For instance bindings, the precedence of descriptor invocation depends
838 on which descriptor methods are defined. A descriptor can define any
839 combination of "__get__()", "__set__()" and "__delete__()". If it
840 does not define "__get__()", then accessing the attribute will return
841 the descriptor object itself unless there is a value in the object’s
842 instance dictionary. If the descriptor defines "__set__()" and/or
843 "__delete__()", it is a data descriptor; if it defines neither, it is
844 a non-data descriptor. Normally, data descriptors define both
845 "__get__()" and "__set__()", while non-data descriptors have just the
846 "__get__()" method. Data descriptors with "__get__()" and "__set__()"
847 (and/or "__delete__()") defined always override a redefinition in an
848 instance dictionary. In contrast, non-data descriptors can be
849 overridden by instances.
850
851 Python methods (including those decorated with "@staticmethod" and
852 "@classmethod") are implemented as non-data descriptors. Accordingly,
853 instances can redefine and override methods. This allows individual
854 instances to acquire behaviors that differ from other instances of the
855 same class.
856
857 The "property()" function is implemented as a data descriptor.
858 Accordingly, instances cannot override the behavior of a property.
859
860
861 __slots__
862 =========
863
864 *__slots__* allow us to explicitly declare data members (like
865 properties) and deny the creation of "__dict__" and *__weakref__*
866 (unless explicitly declared in *__slots__* or available in a parent.)
867
868 The space saved over using "__dict__" can be significant. Attribute
869 lookup speed can be significantly improved as well.
870
871 object.__slots__
872
873 This class variable can be assigned a string, iterable, or sequence
874 of strings with variable names used by instances. *__slots__*
875 reserves space for the declared variables and prevents the
876 automatic creation of "__dict__" and *__weakref__* for each
877 instance.
878
879 Notes on using *__slots__*:
880
881 * When inheriting from a class without *__slots__*, the "__dict__" and
882 *__weakref__* attribute of the instances will always be accessible.
883
884 * Without a "__dict__" variable, instances cannot be assigned new
885 variables not listed in the *__slots__* definition. Attempts to
886 assign to an unlisted variable name raises "AttributeError". If
887 dynamic assignment of new variables is desired, then add
888 "'__dict__'" to the sequence of strings in the *__slots__*
889 declaration.
890
891 * Without a *__weakref__* variable for each instance, classes defining
892 *__slots__* do not support "weak references" to its instances. If
893 weak reference support is needed, then add "'__weakref__'" to the
894 sequence of strings in the *__slots__* declaration.
895
896 * *__slots__* are implemented at the class level by creating
897 descriptors for each variable name. As a result, class attributes
898 cannot be used to set default values for instance variables defined
899 by *__slots__*; otherwise, the class attribute would overwrite the
900 descriptor assignment.
901
902 * The action of a *__slots__* declaration is not limited to the class
903 where it is defined. *__slots__* declared in parents are available
904 in child classes. However, instances of a child subclass will get a
905 "__dict__" and *__weakref__* unless the subclass also defines
906 *__slots__* (which should only contain names of any *additional*
907 slots).
908
909 * If a class defines a slot also defined in a base class, the instance
910 variable defined by the base class slot is inaccessible (except by
911 retrieving its descriptor directly from the base class). This
912 renders the meaning of the program undefined. In the future, a
913 check may be added to prevent this.
914
915 * "TypeError" will be raised if nonempty *__slots__* are defined for a
916 class derived from a ""variable-length" built-in type" such as
917 "int", "bytes", and "tuple".
918
919 * Any non-string *iterable* may be assigned to *__slots__*.
920
921 * If a "dictionary" is used to assign *__slots__*, the dictionary keys
922 will be used as the slot names. The values of the dictionary can be
923 used to provide per-attribute docstrings that will be recognised by
924 "inspect.getdoc()" and displayed in the output of "help()".
925
926 * "__class__" assignment works only if both classes have the same
927 *__slots__*.
928
929 * Multiple inheritance with multiple slotted parent classes can be
930 used, but only one parent is allowed to have attributes created by
931 slots (the other bases must have empty slot layouts) - violations
932 raise "TypeError".
933
934 * If an *iterator* is used for *__slots__* then a *descriptor* is
935 created for each of the iterator’s values. However, the *__slots__*
936 attribute will be an empty iterator.
937 ''',
938 'attribute-references': r'''Attribute references
939 ********************
940
941 An attribute reference is a primary followed by a period and a name:
942
943 attributeref: primary "." identifier
944
945 The primary must evaluate to an object of a type that supports
946 attribute references, which most objects do. This object is then
947 asked to produce the attribute whose name is the identifier. The type
948 and value produced is determined by the object. Multiple evaluations
949 of the same attribute reference may yield different objects.
950
951 This production can be customized by overriding the
952 "__getattribute__()" method or the "__getattr__()" method. The
953 "__getattribute__()" method is called first and either returns a value
954 or raises "AttributeError" if the attribute is not available.
955
956 If an "AttributeError" is raised and the object has a "__getattr__()"
957 method, that method is called as a fallback.
958 ''',
959 'augassign': r'''Augmented assignment statements
960 *******************************
961
962 Augmented assignment is the combination, in a single statement, of a
963 binary operation and an assignment statement:
964
965 augmented_assignment_stmt: augtarget augop (expression_list | yield_expression)
966 augtarget: identifier | attributeref | subscription
967 augop: "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="
968 | ">>=" | "<<=" | "&=" | "^=" | "|="
969
970 (See section Primaries for the syntax definitions of the last three
971 symbols.)
972
973 An augmented assignment evaluates the target (which, unlike normal
974 assignment statements, cannot be an unpacking) and the expression
975 list, performs the binary operation specific to the type of assignment
976 on the two operands, and assigns the result to the original target.
977 The target is only evaluated once.
978
979 An augmented assignment statement like "x += 1" can be rewritten as "x
980 = x + 1" to achieve a similar, but not exactly equal effect. In the
981 augmented version, "x" is only evaluated once. Also, when possible,
982 the actual operation is performed *in-place*, meaning that rather than
983 creating a new object and assigning that to the target, the old object
984 is modified instead.
985
986 Unlike normal assignments, augmented assignments evaluate the left-
987 hand side *before* evaluating the right-hand side. For example, "a[i]
988 += f(x)" first looks-up "a[i]", then it evaluates "f(x)" and performs
989 the addition, and lastly, it writes the result back to "a[i]".
990
991 With the exception of assigning to tuples and multiple targets in a
992 single statement, the assignment done by augmented assignment
993 statements is handled the same way as normal assignments. Similarly,
994 with the exception of the possible *in-place* behavior, the binary
995 operation performed by augmented assignment is the same as the normal
996 binary operations.
997
998 For targets which are attribute references, the same caveat about
999 class and instance attributes applies as for regular assignments.
1000 ''',
1001 'await': r'''Await expression
1002 ****************
1003
1004 Suspend the execution of *coroutine* on an *awaitable* object. Can
1005 only be used inside a *coroutine function*.
1006
1007 await_expr: "await" primary
1008
1009 Added in version 3.5.
1010 ''',
1011 'binary': r'''Binary arithmetic operations
1012 ****************************
1013
1014 The binary arithmetic operations have the conventional priority
1015 levels. Note that some of these operations also apply to certain non-
1016 numeric types. Apart from the power operator, there are only two
1017 levels, one for multiplicative operators and one for additive
1018 operators:
1019
1020 m_expr: u_expr | m_expr "*" u_expr | m_expr "@" m_expr |
1021 m_expr "//" u_expr | m_expr "/" u_expr |
1022 m_expr "%" u_expr
1023 a_expr: m_expr | a_expr "+" m_expr | a_expr "-" m_expr
1024
1025 The "*" (multiplication) operator yields the product of its arguments.
1026 The arguments must either both be numbers, or one argument must be an
1027 integer and the other must be a sequence. In the former case, the
1028 numbers are converted to a common real type and then multiplied
1029 together. In the latter case, sequence repetition is performed; a
1030 negative repetition factor yields an empty sequence.
1031
1032 This operation can be customized using the special "__mul__()" and
1033 "__rmul__()" methods.
1034
1035 Changed in version 3.14: If only one operand is a complex number, the
1036 other operand is converted to a floating-point number.
1037
1038 The "@" (at) operator is intended to be used for matrix
1039 multiplication. No builtin Python types implement this operator.
1040
1041 This operation can be customized using the special "__matmul__()" and
1042 "__rmatmul__()" methods.
1043
1044 Added in version 3.5.
1045
1046 The "/" (division) and "//" (floor division) operators yield the
1047 quotient of their arguments. The numeric arguments are first
1048 converted to a common type. Division of integers yields a float, while
1049 floor division of integers results in an integer; the result is that
1050 of mathematical division with the ‘floor’ function applied to the
1051 result. Division by zero raises the "ZeroDivisionError" exception.
1052
1053 The division operation can be customized using the special
1054 "__truediv__()" and "__rtruediv__()" methods. The floor division
1055 operation can be customized using the special "__floordiv__()" and
1056 "__rfloordiv__()" methods.
1057
1058 The "%" (modulo) operator yields the remainder from the division of
1059 the first argument by the second. The numeric arguments are first
1060 converted to a common type. A zero right argument raises the
1061 "ZeroDivisionError" exception. The arguments may be floating-point
1062 numbers, e.g., "3.14%0.7" equals "0.34" (since "3.14" equals "4*0.7 +
1063 0.34".) The modulo operator always yields a result with the same sign
1064 as its second operand (or zero); the absolute value of the result is
1065 strictly smaller than the absolute value of the second operand [1].
1066
1067 The floor division and modulo operators are connected by the following
1068 identity: "x == (x//y)*y + (x%y)". Floor division and modulo are also
1069 connected with the built-in function "divmod()": "divmod(x, y) ==
1070 (x//y, x%y)". [2].
1071
1072 In addition to performing the modulo operation on numbers, the "%"
1073 operator is also overloaded by string objects to perform old-style
1074 string formatting (also known as interpolation). The syntax for
1075 string formatting is described in the Python Library Reference,
1076 section printf-style String Formatting.
1077
1078 The *modulo* operation can be customized using the special "__mod__()"
1079 and "__rmod__()" methods.
1080
1081 The floor division operator, the modulo operator, and the "divmod()"
1082 function are not defined for complex numbers. Instead, convert to a
1083 floating-point number using the "abs()" function if appropriate.
1084
1085 The "+" (addition) operator yields the sum of its arguments. The
1086 arguments must either both be numbers or both be sequences of the same
1087 type. In the former case, the numbers are converted to a common real
1088 type and then added together. In the latter case, the sequences are
1089 concatenated.
1090
1091 This operation can be customized using the special "__add__()" and
1092 "__radd__()" methods.
1093
1094 Changed in version 3.14: If only one operand is a complex number, the
1095 other operand is converted to a floating-point number.
1096
1097 The "-" (subtraction) operator yields the difference of its arguments.
1098 The numeric arguments are first converted to a common real type.
1099
1100 This operation can be customized using the special "__sub__()" and
1101 "__rsub__()" methods.
1102
1103 Changed in version 3.14: If only one operand is a complex number, the
1104 other operand is converted to a floating-point number.
1105 ''',
1106 'bitwise': r'''Binary bitwise operations
1107 *************************
1108
1109 Each of the three bitwise operations has a different priority level:
1110
1111 and_expr: shift_expr | and_expr "&" shift_expr
1112 xor_expr: and_expr | xor_expr "^" and_expr
1113 or_expr: xor_expr | or_expr "|" xor_expr
1114
1115 The "&" operator yields the bitwise AND of its arguments, which must
1116 be integers or one of them must be a custom object overriding
1117 "__and__()" or "__rand__()" special methods.
1118
1119 The "^" operator yields the bitwise XOR (exclusive OR) of its
1120 arguments, which must be integers or one of them must be a custom
1121 object overriding "__xor__()" or "__rxor__()" special methods.
1122
1123 The "|" operator yields the bitwise (inclusive) OR of its arguments,
1124 which must be integers or one of them must be a custom object
1125 overriding "__or__()" or "__ror__()" special methods.
1126 ''',
1127 'bltin-code-objects': r'''Code Objects
1128 ************
1129
1130 Code objects are used by the implementation to represent “pseudo-
1131 compiled” executable Python code such as a function body. They differ
1132 from function objects because they don’t contain a reference to their
1133 global execution environment. Code objects are returned by the built-
1134 in "compile()" function and can be extracted from function objects
1135 through their "__code__" attribute. See also the "code" module.
1136
1137 Accessing "__code__" raises an auditing event "object.__getattr__"
1138 with arguments "obj" and ""__code__"".
1139
1140 A code object can be executed or evaluated by passing it (instead of a
1141 source string) to the "exec()" or "eval()" built-in functions.
1142
1143 See The standard type hierarchy for more information.
1144 ''',
1145 'bltin-ellipsis-object': r'''The Ellipsis Object
1146 *******************
1147
1148 This object is commonly used to indicate that something is omitted. It
1149 supports no special operations. There is exactly one ellipsis object,
1150 named "Ellipsis" (a built-in name). "type(Ellipsis)()" produces the
1151 "Ellipsis" singleton.
1152
1153 It is written as "Ellipsis" or "...".
1154
1155 In typical use, "..." as the "Ellipsis" object appears in a few
1156 different places, for instance:
1157
1158 * In type annotations, such as callable arguments or tuple elements.
1159
1160 * As the body of a function instead of a pass statement.
1161
1162 * In third-party libraries, such as Numpy’s slicing and striding.
1163
1164 Python also uses three dots in ways that are not "Ellipsis" objects,
1165 for instance:
1166
1167 * Doctest’s "ELLIPSIS", as a pattern for missing content.
1168
1169 * The default Python prompt of the *interactive* shell when partial
1170 input is incomplete.
1171
1172 Lastly, the Python documentation often uses three dots in conventional
1173 English usage to mean omitted content, even in code examples that also
1174 use them as the "Ellipsis".
1175 ''',
1176 'bltin-null-object': r'''The Null Object
1177 ***************
1178
1179 This object is returned by functions that don’t explicitly return a
1180 value. It supports no special operations. There is exactly one null
1181 object, named "None" (a built-in name). "type(None)()" produces the
1182 same singleton.
1183
1184 It is written as "None".
1185 ''',
1186 'bltin-type-objects': r'''Type Objects
1187 ************
1188
1189 Type objects represent the various object types. An object’s type is
1190 accessed by the built-in function "type()". There are no special
1191 operations on types. The standard module "types" defines names for
1192 all standard built-in types.
1193
1194 Types are written like this: "<class 'int'>".
1195 ''',
1196 'booleans': r'''Boolean operations
1197 ******************
1198
1199 or_test: and_test | or_test "or" and_test
1200 and_test: not_test | and_test "and" not_test
1201 not_test: comparison | "not" not_test
1202
1203 In the context of Boolean operations, and also when expressions are
1204 used by control flow statements, the following values are interpreted
1205 as false: "False", "None", numeric zero of all types, and empty
1206 strings and containers (including strings, tuples, lists,
1207 dictionaries, sets and frozensets). All other values are interpreted
1208 as true. User-defined objects can customize their truth value by
1209 providing a "__bool__()" method.
1210
1211 The operator "not" yields "True" if its argument is false, "False"
1212 otherwise.
1213
1214 The expression "x and y" first evaluates *x*; if *x* is false, its
1215 value is returned; otherwise, *y* is evaluated and the resulting value
1216 is returned.
1217
1218 The expression "x or y" first evaluates *x*; if *x* is true, its value
1219 is returned; otherwise, *y* is evaluated and the resulting value is
1220 returned.
1221
1222 Note that neither "and" nor "or" restrict the value and type they
1223 return to "False" and "True", but rather return the last evaluated
1224 argument. This is sometimes useful, e.g., if "s" is a string that
1225 should be replaced by a default value if it is empty, the expression
1226 "s or 'foo'" yields the desired value. Because "not" has to create a
1227 new value, it returns a boolean value regardless of the type of its
1228 argument (for example, "not 'foo'" produces "False" rather than "''".)
1229 ''',
1230 'break': r'''The "break" statement
1231 *********************
1232
1233 break_stmt: "break"
1234
1235 "break" may only occur syntactically nested in a "for" or "while"
1236 loop, but not nested in a function or class definition within that
1237 loop.
1238
1239 It terminates the nearest enclosing loop, skipping the optional "else"
1240 clause if the loop has one.
1241
1242 If a "for" loop is terminated by "break", the loop control target
1243 keeps its current value.
1244
1245 When "break" passes control out of a "try" statement with a "finally"
1246 clause, that "finally" clause is executed before really leaving the
1247 loop.
1248 ''',
1249 'callable-types': r'''Emulating callable objects
1250 **************************
1251
1252 object.__call__(self[, args...])
1253
1254 Called when the instance is “called” as a function; if this method
1255 is defined, "x(arg1, arg2, ...)" roughly translates to
1256 "type(x).__call__(x, arg1, ...)". The "object" class itself does
1257 not provide this method.
1258 ''',
1259 'calls': r'''Calls
1260 *****
1261
1262 A call calls a callable object (e.g., a *function*) with a possibly
1263 empty series of *arguments*:
1264
1265 call: primary "(" [argument_list [","] | comprehension] ")"
1266 argument_list: positional_arguments ["," starred_and_keywords]
1267 ["," keywords_arguments]
1268 | starred_and_keywords ["," keywords_arguments]
1269 | keywords_arguments
1270 positional_arguments: positional_item ("," positional_item)*
1271 positional_item: assignment_expression | "*" expression
1272 starred_and_keywords: ("*" expression | keyword_item)
1273 ("," "*" expression | "," keyword_item)*
1274 keywords_arguments: (keyword_item | "**" expression)
1275 ("," keyword_item | "," "**" expression)*
1276 keyword_item: identifier "=" expression
1277
1278 An optional trailing comma may be present after the positional and
1279 keyword arguments but does not affect the semantics.
1280
1281 The primary must evaluate to a callable object (user-defined
1282 functions, built-in functions, methods of built-in objects, class
1283 objects, methods of class instances, and all objects having a
1284 "__call__()" method are callable). All argument expressions are
1285 evaluated before the call is attempted. Please refer to section
1286 Function definitions for the syntax of formal *parameter* lists.
1287
1288 If keyword arguments are present, they are first converted to
1289 positional arguments, as follows. First, a list of unfilled slots is
1290 created for the formal parameters. If there are N positional
1291 arguments, they are placed in the first N slots. Next, for each
1292 keyword argument, the identifier is used to determine the
1293 corresponding slot (if the identifier is the same as the first formal
1294 parameter name, the first slot is used, and so on). If the slot is
1295 already filled, a "TypeError" exception is raised. Otherwise, the
1296 argument is placed in the slot, filling it (even if the expression is
1297 "None", it fills the slot). When all arguments have been processed,
1298 the slots that are still unfilled are filled with the corresponding
1299 default value from the function definition. (Default values are
1300 calculated, once, when the function is defined; thus, a mutable object
1301 such as a list or dictionary used as default value will be shared by
1302 all calls that don’t specify an argument value for the corresponding
1303 slot; this should usually be avoided.) If there are any unfilled
1304 slots for which no default value is specified, a "TypeError" exception
1305 is raised. Otherwise, the list of filled slots is used as the
1306 argument list for the call.
1307
1308 **CPython implementation detail:** An implementation may provide
1309 built-in functions whose positional parameters do not have names, even
1310 if they are ‘named’ for the purpose of documentation, and which
1311 therefore cannot be supplied by keyword. In CPython, this is the case
1312 for functions implemented in C that use "PyArg_ParseTuple()" to parse
1313 their arguments.
1314
1315 If there are more positional arguments than there are formal parameter
1316 slots, a "TypeError" exception is raised, unless a formal parameter
1317 using the syntax "*identifier" is present; in this case, that formal
1318 parameter receives a tuple containing the excess positional arguments
1319 (or an empty tuple if there were no excess positional arguments).
1320
1321 If any keyword argument does not correspond to a formal parameter
1322 name, a "TypeError" exception is raised, unless a formal parameter
1323 using the syntax "**identifier" is present; in this case, that formal
1324 parameter receives a dictionary containing the excess keyword
1325 arguments (using the keywords as keys and the argument values as
1326 corresponding values), or a (new) empty dictionary if there were no
1327 excess keyword arguments.
1328
1329 If the syntax "*expression" appears in the function call, "expression"
1330 must evaluate to an *iterable*. Elements from these iterables are
1331 treated as if they were additional positional arguments. For the call
1332 "f(x1, x2, *y, x3, x4)", if *y* evaluates to a sequence *y1*, …, *yM*,
1333 this is equivalent to a call with M+4 positional arguments *x1*, *x2*,
1334 *y1*, …, *yM*, *x3*, *x4*.
1335
1336 A consequence of this is that although the "*expression" syntax may
1337 appear *after* explicit keyword arguments, it is processed *before*
1338 the keyword arguments (and any "**expression" arguments – see below).
1339 So:
1340
1341 >>> def f(a, b):
1342 ... print(a, b)
1343 ...
1344 >>> f(b=1, *(2,))
1345 2 1
1346 >>> f(a=1, *(2,))
1347 Traceback (most recent call last):
1348 File "<stdin>", line 1, in <module>
1349 TypeError: f() got multiple values for keyword argument 'a'
1350 >>> f(1, *(2,))
1351 1 2
1352
1353 It is unusual for both keyword arguments and the "*expression" syntax
1354 to be used in the same call, so in practice this confusion does not
1355 often arise.
1356
1357 If the syntax "**expression" appears in the function call,
1358 "expression" must evaluate to a *mapping*, the contents of which are
1359 treated as additional keyword arguments. If a parameter matching a key
1360 has already been given a value (by an explicit keyword argument, or
1361 from another unpacking), a "TypeError" exception is raised.
1362
1363 When "**expression" is used, each key in this mapping must be a
1364 string. Each value from the mapping is assigned to the first formal
1365 parameter eligible for keyword assignment whose name is equal to the
1366 key. A key need not be a Python identifier (e.g. ""max-temp °F"" is
1367 acceptable, although it will not match any formal parameter that could
1368 be declared). If there is no match to a formal parameter the key-value
1369 pair is collected by the "**" parameter, if there is one, or if there
1370 is not, a "TypeError" exception is raised.
1371
1372 Formal parameters using the syntax "*identifier" or "**identifier"
1373 cannot be used as positional argument slots or as keyword argument
1374 names.
1375
1376 Changed in version 3.5: Function calls accept any number of "*" and
1377 "**" unpackings, positional arguments may follow iterable unpackings
1378 ("*"), and keyword arguments may follow dictionary unpackings ("**").
1379 Originally proposed by **PEP 448**.
1380
1381 A call always returns some value, possibly "None", unless it raises an
1382 exception. How this value is computed depends on the type of the
1383 callable object.
1384
1385 If it is—
1386
1387 a user-defined function:
1388 The code block for the function is executed, passing it the
1389 argument list. The first thing the code block will do is bind the
1390 formal parameters to the arguments; this is described in section
1391 Function definitions. When the code block executes a "return"
1392 statement, this specifies the return value of the function call.
1393 If execution reaches the end of the code block without executing a
1394 "return" statement, the return value is "None".
1395
1396 a built-in function or method:
1397 The result is up to the interpreter; see Built-in Functions for the
1398 descriptions of built-in functions and methods.
1399
1400 a class object:
1401 A new instance of that class is returned.
1402
1403 a class instance method:
1404 The corresponding user-defined function is called, with an argument
1405 list that is one longer than the argument list of the call: the
1406 instance becomes the first argument.
1407
1408 a class instance:
1409 The class must define a "__call__()" method; the effect is then the
1410 same as if that method was called.
1411 ''',
1412 'class': r'''Class definitions
1413 *****************
1414
1415 A class definition defines a class object (see section The standard
1416 type hierarchy):
1417
1418 classdef: [decorators] "class" classname [type_params] [inheritance] ":" suite
1419 inheritance: "(" [argument_list] ")"
1420 classname: identifier
1421
1422 A class definition is an executable statement. The inheritance list
1423 usually gives a list of base classes (see Metaclasses for more
1424 advanced uses), so each item in the list should evaluate to a class
1425 object which allows subclassing. Classes without an inheritance list
1426 inherit, by default, from the base class "object"; hence,
1427
1428 class Foo:
1429 pass
1430
1431 is equivalent to
1432
1433 class Foo(object):
1434 pass
1435
1436 The class’s suite is then executed in a new execution frame (see
1437 Naming and binding), using a newly created local namespace and the
1438 original global namespace. (Usually, the suite contains mostly
1439 function definitions.) When the class’s suite finishes execution, its
1440 execution frame is discarded but its local namespace is saved. [5] A
1441 class object is then created using the inheritance list for the base
1442 classes and the saved local namespace for the attribute dictionary.
1443 The class name is bound to this class object in the original local
1444 namespace.
1445
1446 The order in which attributes are defined in the class body is
1447 preserved in the new class’s "__dict__". Note that this is reliable
1448 only right after the class is created and only for classes that were
1449 defined using the definition syntax.
1450
1451 Class creation can be customized heavily using metaclasses.
1452
1453 Classes can also be decorated: just like when decorating functions,
1454
1455 @f1(arg)
1456 @f2
1457 class Foo: pass
1458
1459 is roughly equivalent to
1460
1461 class Foo: pass
1462 Foo = f1(arg)(f2(Foo))
1463
1464 The evaluation rules for the decorator expressions are the same as for
1465 function decorators. The result is then bound to the class name.
1466
1467 Changed in version 3.9: Classes may be decorated with any valid
1468 "assignment_expression". Previously, the grammar was much more
1469 restrictive; see **PEP 614** for details.
1470
1471 A list of type parameters may be given in square brackets immediately
1472 after the class’s name. This indicates to static type checkers that
1473 the class is generic. At runtime, the type parameters can be retrieved
1474 from the class’s "__type_params__" attribute. See Generic classes for
1475 more.
1476
1477 Changed in version 3.12: Type parameter lists are new in Python 3.12.
1478
1479 **Programmer’s note:** Variables defined in the class definition are
1480 class attributes; they are shared by instances. Instance attributes
1481 can be set in a method with "self.name = value". Both class and
1482 instance attributes are accessible through the notation “"self.name"”,
1483 and an instance attribute hides a class attribute with the same name
1484 when accessed in this way. Class attributes can be used as defaults
1485 for instance attributes, but using mutable values there can lead to
1486 unexpected results. Descriptors can be used to create instance
1487 variables with different implementation details.
1488
1489 See also:
1490
1491 **PEP 3115** - Metaclasses in Python 3000
1492 The proposal that changed the declaration of metaclasses to the
1493 current syntax, and the semantics for how classes with
1494 metaclasses are constructed.
1495
1496 **PEP 3129** - Class Decorators
1497 The proposal that added class decorators. Function and method
1498 decorators were introduced in **PEP 318**.
1499 ''',
1500 'comparisons': r'''Comparisons
1501 ***********
1502
1503 Unlike C, all comparison operations in Python have the same priority,
1504 which is lower than that of any arithmetic, shifting or bitwise
1505 operation. Also unlike C, expressions like "a < b < c" have the
1506 interpretation that is conventional in mathematics:
1507
1508 comparison: or_expr (comp_operator or_expr)*
1509 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
1510 | "is" ["not"] | ["not"] "in"
1511
1512 Comparisons yield boolean values: "True" or "False". Custom *rich
1513 comparison methods* may return non-boolean values. In this case Python
1514 will call "bool()" on such value in boolean contexts.
1515
1516 Comparisons can be chained arbitrarily, e.g., "x < y <= z" is
1517 equivalent to "x < y and y <= z", except that "y" is evaluated only
1518 once (but in both cases "z" is not evaluated at all when "x < y" is
1519 found to be false).
1520
1521 Formally, if *a*, *b*, *c*, …, *y*, *z* are expressions and *op1*,
1522 *op2*, …, *opN* are comparison operators, then "a op1 b op2 c ... y
1523 opN z" is equivalent to "a op1 b and b op2 c and ... y opN z", except
1524 that each expression is evaluated at most once.
1525
1526 Note that "a op1 b op2 c" doesn’t imply any kind of comparison between
1527 *a* and *c*, so that, e.g., "x < y > z" is perfectly legal (though
1528 perhaps not pretty).
1529
1530
1531 Value comparisons
1532 =================
1533
1534 The operators "<", ">", "==", ">=", "<=", and "!=" compare the values
1535 of two objects. The objects do not need to have the same type.
1536
1537 Chapter Objects, values and types states that objects have a value (in
1538 addition to type and identity). The value of an object is a rather
1539 abstract notion in Python: For example, there is no canonical access
1540 method for an object’s value. Also, there is no requirement that the
1541 value of an object should be constructed in a particular way, e.g.
1542 comprised of all its data attributes. Comparison operators implement a
1543 particular notion of what the value of an object is. One can think of
1544 them as defining the value of an object indirectly, by means of their
1545 comparison implementation.
1546
1547 Because all types are (direct or indirect) subtypes of "object", they
1548 inherit the default comparison behavior from "object". Types can
1549 customize their comparison behavior by implementing *rich comparison
1550 methods* like "__lt__()", described in Basic customization.
1551
1552 The default behavior for equality comparison ("==" and "!=") is based
1553 on the identity of the objects. Hence, equality comparison of
1554 instances with the same identity results in equality, and equality
1555 comparison of instances with different identities results in
1556 inequality. A motivation for this default behavior is the desire that
1557 all objects should be reflexive (i.e. "x is y" implies "x == y").
1558
1559 A default order comparison ("<", ">", "<=", and ">=") is not provided;
1560 an attempt raises "TypeError". A motivation for this default behavior
1561 is the lack of a similar invariant as for equality.
1562
1563 The behavior of the default equality comparison, that instances with
1564 different identities are always unequal, may be in contrast to what
1565 types will need that have a sensible definition of object value and
1566 value-based equality. Such types will need to customize their
1567 comparison behavior, and in fact, a number of built-in types have done
1568 that.
1569
1570 The following list describes the comparison behavior of the most
1571 important built-in types.
1572
1573 * Numbers of built-in numeric types (Numeric Types — int, float,
1574 complex) and of the standard library types "fractions.Fraction" and
1575 "decimal.Decimal" can be compared within and across their types,
1576 with the restriction that complex numbers do not support order
1577 comparison. Within the limits of the types involved, they compare
1578 mathematically (algorithmically) correct without loss of precision.
1579
1580 The not-a-number values "float('NaN')" and "decimal.Decimal('NaN')"
1581 are special. Any ordered comparison of a number to a not-a-number
1582 value is false. A counter-intuitive implication is that not-a-number
1583 values are not equal to themselves. For example, if "x =
1584 float('NaN')", "3 < x", "x < 3" and "x == x" are all false, while "x
1585 != x" is true. This behavior is compliant with IEEE 754.
1586
1587 * "None" and "NotImplemented" are singletons. **PEP 8** advises that
1588 comparisons for singletons should always be done with "is" or "is
1589 not", never the equality operators.
1590
1591 * Binary sequences (instances of "bytes" or "bytearray") can be
1592 compared within and across their types. They compare
1593 lexicographically using the numeric values of their elements.
1594
1595 * Strings (instances of "str") compare lexicographically using the
1596 numerical Unicode code points (the result of the built-in function
1597 "ord()") of their characters. [3]
1598
1599 Strings and binary sequences cannot be directly compared.
1600
1601 * Sequences (instances of "tuple", "list", or "range") can be compared
1602 only within each of their types, with the restriction that ranges do
1603 not support order comparison. Equality comparison across these
1604 types results in inequality, and ordering comparison across these
1605 types raises "TypeError".
1606
1607 Sequences compare lexicographically using comparison of
1608 corresponding elements. The built-in containers typically assume
1609 identical objects are equal to themselves. That lets them bypass
1610 equality tests for identical objects to improve performance and to
1611 maintain their internal invariants.
1612
1613 Lexicographical comparison between built-in collections works as
1614 follows:
1615
1616 * For two collections to compare equal, they must be of the same
1617 type, have the same length, and each pair of corresponding
1618 elements must compare equal (for example, "[1,2] == (1,2)" is
1619 false because the type is not the same).
1620
1621 * Collections that support order comparison are ordered the same as
1622 their first unequal elements (for example, "[1,2,x] <= [1,2,y]"
1623 has the same value as "x <= y"). If a corresponding element does
1624 not exist, the shorter collection is ordered first (for example,
1625 "[1,2] < [1,2,3]" is true).
1626
1627 * Mappings (instances of "dict") compare equal if and only if they
1628 have equal "(key, value)" pairs. Equality comparison of the keys and
1629 values enforces reflexivity.
1630
1631 Order comparisons ("<", ">", "<=", and ">=") raise "TypeError".
1632
1633 * Sets (instances of "set" or "frozenset") can be compared within and
1634 across their types.
1635
1636 They define order comparison operators to mean subset and superset
1637 tests. Those relations do not define total orderings (for example,
1638 the two sets "{1,2}" and "{2,3}" are not equal, nor subsets of one
1639 another, nor supersets of one another). Accordingly, sets are not
1640 appropriate arguments for functions which depend on total ordering
1641 (for example, "min()", "max()", and "sorted()" produce undefined
1642 results given a list of sets as inputs).
1643
1644 Comparison of sets enforces reflexivity of its elements.
1645
1646 * Most other built-in types have no comparison methods implemented, so
1647 they inherit the default comparison behavior.
1648
1649 User-defined classes that customize their comparison behavior should
1650 follow some consistency rules, if possible:
1651
1652 * Equality comparison should be reflexive. In other words, identical
1653 objects should compare equal:
1654
1655 "x is y" implies "x == y"
1656
1657 * Comparison should be symmetric. In other words, the following
1658 expressions should have the same result:
1659
1660 "x == y" and "y == x"
1661
1662 "x != y" and "y != x"
1663
1664 "x < y" and "y > x"
1665
1666 "x <= y" and "y >= x"
1667
1668 * Comparison should be transitive. The following (non-exhaustive)
1669 examples illustrate that:
1670
1671 "x > y and y > z" implies "x > z"
1672
1673 "x < y and y <= z" implies "x < z"
1674
1675 * Inverse comparison should result in the boolean negation. In other
1676 words, the following expressions should have the same result:
1677
1678 "x == y" and "not x != y"
1679
1680 "x < y" and "not x >= y" (for total ordering)
1681
1682 "x > y" and "not x <= y" (for total ordering)
1683
1684 The last two expressions apply to totally ordered collections (e.g.
1685 to sequences, but not to sets or mappings). See also the
1686 "total_ordering()" decorator.
1687
1688 * The "hash()" result should be consistent with equality. Objects that
1689 are equal should either have the same hash value, or be marked as
1690 unhashable.
1691
1692 Python does not enforce these consistency rules. In fact, the
1693 not-a-number values are an example for not following these rules.
1694
1695
1696 Membership test operations
1697 ==========================
1698
1699 The operators "in" and "not in" test for membership. "x in s"
1700 evaluates to "True" if *x* is a member of *s*, and "False" otherwise.
1701 "x not in s" returns the negation of "x in s". All built-in sequences
1702 and set types support this as well as dictionary, for which "in" tests
1703 whether the dictionary has a given key. For container types such as
1704 list, tuple, set, frozenset, dict, or collections.deque, the
1705 expression "x in y" is equivalent to "any(x is e or x == e for e in
1706 y)".
1707
1708 For the string and bytes types, "x in y" is "True" if and only if *x*
1709 is a substring of *y*. An equivalent test is "y.find(x) != -1".
1710 Empty strings are always considered to be a substring of any other
1711 string, so """ in "abc"" will return "True".
1712
1713 For user-defined classes which define the "__contains__()" method, "x
1714 in y" returns "True" if "y.__contains__(x)" returns a true value, and
1715 "False" otherwise.
1716
1717 For user-defined classes which do not define "__contains__()" but do
1718 define "__iter__()", "x in y" is "True" if some value "z", for which
1719 the expression "x is z or x == z" is true, is produced while iterating
1720 over "y". If an exception is raised during the iteration, it is as if
1721 "in" raised that exception.
1722
1723 Lastly, the old-style iteration protocol is tried: if a class defines
1724 "__getitem__()", "x in y" is "True" if and only if there is a non-
1725 negative integer index *i* such that "x is y[i] or x == y[i]", and no
1726 lower integer index raises the "IndexError" exception. (If any other
1727 exception is raised, it is as if "in" raised that exception).
1728
1729 The operator "not in" is defined to have the inverse truth value of
1730 "in".
1731
1732
1733 Identity comparisons
1734 ====================
1735
1736 The operators "is" and "is not" test for an object’s identity: "x is
1737 y" is true if and only if *x* and *y* are the same object. An
1738 Object’s identity is determined using the "id()" function. "x is not
1739 y" yields the inverse truth value. [4]
1740 ''',
1741 'compound': r'''Compound statements
1742 *******************
1743
1744 Compound statements contain (groups of) other statements; they affect
1745 or control the execution of those other statements in some way. In
1746 general, compound statements span multiple lines, although in simple
1747 incarnations a whole compound statement may be contained in one line.
1748
1749 The "if", "while" and "for" statements implement traditional control
1750 flow constructs. "try" specifies exception handlers and/or cleanup
1751 code for a group of statements, while the "with" statement allows the
1752 execution of initialization and finalization code around a block of
1753 code. Function and class definitions are also syntactically compound
1754 statements.
1755
1756 A compound statement consists of one or more ‘clauses.’ A clause
1757 consists of a header and a ‘suite.’ The clause headers of a
1758 particular compound statement are all at the same indentation level.
1759 Each clause header begins with a uniquely identifying keyword and ends
1760 with a colon. A suite is a group of statements controlled by a
1761 clause. A suite can be one or more semicolon-separated simple
1762 statements on the same line as the header, following the header’s
1763 colon, or it can be one or more indented statements on subsequent
1764 lines. Only the latter form of a suite can contain nested compound
1765 statements; the following is illegal, mostly because it wouldn’t be
1766 clear to which "if" clause a following "else" clause would belong:
1767
1768 if test1: if test2: print(x)
1769
1770 Also note that the semicolon binds tighter than the colon in this
1771 context, so that in the following example, either all or none of the
1772 "print()" calls are executed:
1773
1774 if x < y < z: print(x); print(y); print(z)
1775
1776 Summarizing:
1777
1778 compound_stmt: if_stmt
1779 | while_stmt
1780 | for_stmt
1781 | try_stmt
1782 | with_stmt
1783 | match_stmt
1784 | funcdef
1785 | classdef
1786 | async_with_stmt
1787 | async_for_stmt
1788 | async_funcdef
1789 suite: stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
1790 statement: stmt_list NEWLINE | compound_stmt
1791 stmt_list: simple_stmt (";" simple_stmt)* [";"]
1792
1793 Note that statements always end in a "NEWLINE" possibly followed by a
1794 "DEDENT". Also note that optional continuation clauses always begin
1795 with a keyword that cannot start a statement, thus there are no
1796 ambiguities (the ‘dangling "else"’ problem is solved in Python by
1797 requiring nested "if" statements to be indented).
1798
1799 The formatting of the grammar rules in the following sections places
1800 each clause on a separate line for clarity.
1801
1802
1803 The "if" statement
1804 ==================
1805
1806 The "if" statement is used for conditional execution:
1807
1808 if_stmt: "if" assignment_expression ":" suite
1809 ("elif" assignment_expression ":" suite)*
1810 ["else" ":" suite]
1811
1812 It selects exactly one of the suites by evaluating the expressions one
1813 by one until one is found to be true (see section Boolean operations
1814 for the definition of true and false); then that suite is executed
1815 (and no other part of the "if" statement is executed or evaluated).
1816 If all expressions are false, the suite of the "else" clause, if
1817 present, is executed.
1818
1819
1820 The "while" statement
1821 =====================
1822
1823 The "while" statement is used for repeated execution as long as an
1824 expression is true:
1825
1826 while_stmt: "while" assignment_expression ":" suite
1827 ["else" ":" suite]
1828
1829 This repeatedly tests the expression and, if it is true, executes the
1830 first suite; if the expression is false (which may be the first time
1831 it is tested) the suite of the "else" clause, if present, is executed
1832 and the loop terminates.
1833
1834 A "break" statement executed in the first suite terminates the loop
1835 without executing the "else" clause’s suite. A "continue" statement
1836 executed in the first suite skips the rest of the suite and goes back
1837 to testing the expression.
1838
1839
1840 The "for" statement
1841 ===================
1842
1843 The "for" statement is used to iterate over the elements of a sequence
1844 (such as a string, tuple or list) or other iterable object:
1845
1846 for_stmt: "for" target_list "in" starred_expression_list ":" suite
1847 ["else" ":" suite]
1848
1849 The "starred_expression_list" expression is evaluated once; it should
1850 yield an *iterable* object. An *iterator* is created for that
1851 iterable. The first item provided by the iterator is then assigned to
1852 the target list using the standard rules for assignments (see
1853 Assignment statements), and the suite is executed. This repeats for
1854 each item provided by the iterator. When the iterator is exhausted,
1855 the suite in the "else" clause, if present, is executed, and the loop
1856 terminates.
1857
1858 A "break" statement executed in the first suite terminates the loop
1859 without executing the "else" clause’s suite. A "continue" statement
1860 executed in the first suite skips the rest of the suite and continues
1861 with the next item, or with the "else" clause if there is no next
1862 item.
1863
1864 The for-loop makes assignments to the variables in the target list.
1865 This overwrites all previous assignments to those variables including
1866 those made in the suite of the for-loop:
1867
1868 for i in range(10):
1869 print(i)
1870 i = 5 # this will not affect the for-loop
1871 # because i will be overwritten with the next
1872 # index in the range
1873
1874 Names in the target list are not deleted when the loop is finished,
1875 but if the sequence is empty, they will not have been assigned to at
1876 all by the loop. Hint: the built-in type "range()" represents
1877 immutable arithmetic sequences of integers. For instance, iterating
1878 "range(3)" successively yields 0, 1, and then 2.
1879
1880 Changed in version 3.11: Starred elements are now allowed in the
1881 expression list.
1882
1883
1884 The "try" statement
1885 ===================
1886
1887 The "try" statement specifies exception handlers and/or cleanup code
1888 for a group of statements:
1889
1890 try_stmt: try1_stmt | try2_stmt | try3_stmt
1891 try1_stmt: "try" ":" suite
1892 ("except" [expression ["as" identifier]] ":" suite)+
1893 ["else" ":" suite]
1894 ["finally" ":" suite]
1895 try2_stmt: "try" ":" suite
1896 ("except" "*" expression ["as" identifier] ":" suite)+
1897 ["else" ":" suite]
1898 ["finally" ":" suite]
1899 try3_stmt: "try" ":" suite
1900 "finally" ":" suite
1901
1902 Additional information on exceptions can be found in section
1903 Exceptions, and information on using the "raise" statement to generate
1904 exceptions may be found in section The raise statement.
1905
1906 Changed in version 3.14: Support for optionally dropping grouping
1907 parentheses when using multiple exception types. See **PEP 758**.
1908
1909
1910 "except" clause
1911 ---------------
1912
1913 The "except" clause(s) specify one or more exception handlers. When no
1914 exception occurs in the "try" clause, no exception handler is
1915 executed. When an exception occurs in the "try" suite, a search for an
1916 exception handler is started. This search inspects the "except"
1917 clauses in turn until one is found that matches the exception. An
1918 expression-less "except" clause, if present, must be last; it matches
1919 any exception.
1920
1921 For an "except" clause with an expression, the expression must
1922 evaluate to an exception type or a tuple of exception types.
1923 Parentheses can be dropped if multiple exception types are provided
1924 and the "as" clause is not used. The raised exception matches an
1925 "except" clause whose expression evaluates to the class or a *non-
1926 virtual base class* of the exception object, or to a tuple that
1927 contains such a class.
1928
1929 If no "except" clause matches the exception, the search for an
1930 exception handler continues in the surrounding code and on the
1931 invocation stack. [1]
1932
1933 If the evaluation of an expression in the header of an "except" clause
1934 raises an exception, the original search for a handler is canceled and
1935 a search starts for the new exception in the surrounding code and on
1936 the call stack (it is treated as if the entire "try" statement raised
1937 the exception).
1938
1939 When a matching "except" clause is found, the exception is assigned to
1940 the target specified after the "as" keyword in that "except" clause,
1941 if present, and the "except" clause’s suite is executed. All "except"
1942 clauses must have an executable block. When the end of this block is
1943 reached, execution continues normally after the entire "try"
1944 statement. (This means that if two nested handlers exist for the same
1945 exception, and the exception occurs in the "try" clause of the inner
1946 handler, the outer handler will not handle the exception.)
1947
1948 When an exception has been assigned using "as target", it is cleared
1949 at the end of the "except" clause. This is as if
1950
1951 except E as N:
1952 foo
1953
1954 was translated to
1955
1956 except E as N:
1957 try:
1958 foo
1959 finally:
1960 del N
1961
1962 This means the exception must be assigned to a different name to be
1963 able to refer to it after the "except" clause. Exceptions are cleared
1964 because with the traceback attached to them, they form a reference
1965 cycle with the stack frame, keeping all locals in that frame alive
1966 until the next garbage collection occurs.
1967
1968 Before an "except" clause’s suite is executed, the exception is stored
1969 in the "sys" module, where it can be accessed from within the body of
1970 the "except" clause by calling "sys.exception()". When leaving an
1971 exception handler, the exception stored in the "sys" module is reset
1972 to its previous value:
1973
1974 >>> print(sys.exception())
1975 None
1976 >>> try:
1977 ... raise TypeError
1978 ... except:
1979 ... print(repr(sys.exception()))
1980 ... try:
1981 ... raise ValueError
1982 ... except:
1983 ... print(repr(sys.exception()))
1984 ... print(repr(sys.exception()))
1985 ...
1986 TypeError()
1987 ValueError()
1988 TypeError()
1989 >>> print(sys.exception())
1990 None
1991
1992
1993 "except*" clause
1994 ----------------
1995
1996 The "except*" clause(s) specify one or more handlers for groups of
1997 exceptions ("BaseExceptionGroup" instances). A "try" statement can
1998 have either "except" or "except*" clauses, but not both. The exception
1999 type for matching is mandatory in the case of "except*", so "except*:"
2000 is a syntax error. The type is interpreted as in the case of "except",
2001 but matching is performed on the exceptions contained in the group
2002 that is being handled. An "TypeError" is raised if a matching type is
2003 a subclass of "BaseExceptionGroup", because that would have ambiguous
2004 semantics.
2005
2006 When an exception group is raised in the try block, each "except*"
2007 clause splits (see "split()") it into the subgroups of matching and
2008 non-matching exceptions. If the matching subgroup is not empty, it
2009 becomes the handled exception (the value returned from
2010 "sys.exception()") and assigned to the target of the "except*" clause
2011 (if there is one). Then, the body of the "except*" clause executes. If
2012 the non-matching subgroup is not empty, it is processed by the next
2013 "except*" in the same manner. This continues until all exceptions in
2014 the group have been matched, or the last "except*" clause has run.
2015
2016 After all "except*" clauses execute, the group of unhandled exceptions
2017 is merged with any exceptions that were raised or re-raised from
2018 within "except*" clauses. This merged exception group propagates on.:
2019
2020 >>> try:
2021 ... raise ExceptionGroup("eg",
2022 ... [ValueError(1), TypeError(2), OSError(3), OSError(4)])
2023 ... except* TypeError as e:
2024 ... print(f'caught {type(e)} with nested {e.exceptions}')
2025 ... except* OSError as e:
2026 ... print(f'caught {type(e)} with nested {e.exceptions}')
2027 ...
2028 caught <class 'ExceptionGroup'> with nested (TypeError(2),)
2029 caught <class 'ExceptionGroup'> with nested (OSError(3), OSError(4))
2030 + Exception Group Traceback (most recent call last):
2031 | File "<doctest default[0]>", line 2, in <module>
2032 | raise ExceptionGroup("eg",
2033 | [ValueError(1), TypeError(2), OSError(3), OSError(4)])
2034 | ExceptionGroup: eg (1 sub-exception)
2035 +-+---------------- 1 ----------------
2036 | ValueError: 1
2037 +------------------------------------
2038
2039 If the exception raised from the "try" block is not an exception group
2040 and its type matches one of the "except*" clauses, it is caught and
2041 wrapped by an exception group with an empty message string. This
2042 ensures that the type of the target "e" is consistently
2043 "BaseExceptionGroup":
2044
2045 >>> try:
2046 ... raise BlockingIOError
2047 ... except* BlockingIOError as e:
2048 ... print(repr(e))
2049 ...
2050 ExceptionGroup('', (BlockingIOError(),))
2051
2052 "break", "continue" and "return" cannot appear in an "except*" clause.
2053
2054
2055 "else" clause
2056 -------------
2057
2058 The optional "else" clause is executed if the control flow leaves the
2059 "try" suite, no exception was raised, and no "return", "continue", or
2060 "break" statement was executed. Exceptions in the "else" clause are
2061 not handled by the preceding "except" clauses.
2062
2063
2064 "finally" clause
2065 ----------------
2066
2067 If "finally" is present, it specifies a ‘cleanup’ handler. The "try"
2068 clause is executed, including any "except" and "else" clauses. If an
2069 exception occurs in any of the clauses and is not handled, the
2070 exception is temporarily saved. The "finally" clause is executed. If
2071 there is a saved exception it is re-raised at the end of the "finally"
2072 clause. If the "finally" clause raises another exception, the saved
2073 exception is set as the context of the new exception. If the "finally"
2074 clause executes a "return", "break" or "continue" statement, the saved
2075 exception is discarded. For example, this function returns 42.
2076
2077 def f():
2078 try:
2079 1/0
2080 finally:
2081 return 42
2082
2083 The exception information is not available to the program during
2084 execution of the "finally" clause.
2085
2086 When a "return", "break" or "continue" statement is executed in the
2087 "try" suite of a "try"…"finally" statement, the "finally" clause is
2088 also executed ‘on the way out.’
2089
2090 The return value of a function is determined by the last "return"
2091 statement executed. Since the "finally" clause always executes, a
2092 "return" statement executed in the "finally" clause will always be the
2093 last one executed. The following function returns ‘finally’.
2094
2095 def foo():
2096 try:
2097 return 'try'
2098 finally:
2099 return 'finally'
2100
2101 Changed in version 3.8: Prior to Python 3.8, a "continue" statement
2102 was illegal in the "finally" clause due to a problem with the
2103 implementation.
2104
2105 Changed in version 3.14: The compiler emits a "SyntaxWarning" when a
2106 "return", "break" or "continue" appears in a "finally" block (see
2107 **PEP 765**).
2108
2109
2110 The "with" statement
2111 ====================
2112
2113 The "with" statement is used to wrap the execution of a block with
2114 methods defined by a context manager (see section With Statement
2115 Context Managers). This allows common "try"…"except"…"finally" usage
2116 patterns to be encapsulated for convenient reuse.
2117
2118 with_stmt: "with" ( "(" with_stmt_contents ","? ")" | with_stmt_contents ) ":" suite
2119 with_stmt_contents: with_item ("," with_item)*
2120 with_item: expression ["as" target]
2121
2122 The execution of the "with" statement with one “item” proceeds as
2123 follows:
2124
2125 1. The context expression (the expression given in the "with_item") is
2126 evaluated to obtain a context manager.
2127
2128 2. The context manager’s "__enter__()" is loaded for later use.
2129
2130 3. The context manager’s "__exit__()" is loaded for later use.
2131
2132 4. The context manager’s "__enter__()" method is invoked.
2133
2134 5. If a target was included in the "with" statement, the return value
2135 from "__enter__()" is assigned to it.
2136
2137 Note:
2138
2139 The "with" statement guarantees that if the "__enter__()" method
2140 returns without an error, then "__exit__()" will always be
2141 called. Thus, if an error occurs during the assignment to the
2142 target list, it will be treated the same as an error occurring
2143 within the suite would be. See step 7 below.
2144
2145 6. The suite is executed.
2146
2147 7. The context manager’s "__exit__()" method is invoked. If an
2148 exception caused the suite to be exited, its type, value, and
2149 traceback are passed as arguments to "__exit__()". Otherwise, three
2150 "None" arguments are supplied.
2151
2152 If the suite was exited due to an exception, and the return value
2153 from the "__exit__()" method was false, the exception is reraised.
2154 If the return value was true, the exception is suppressed, and
2155 execution continues with the statement following the "with"
2156 statement.
2157
2158 If the suite was exited for any reason other than an exception, the
2159 return value from "__exit__()" is ignored, and execution proceeds
2160 at the normal location for the kind of exit that was taken.
2161
2162 The following code:
2163
2164 with EXPRESSION as TARGET:
2165 SUITE
2166
2167 is semantically equivalent to:
2168
2169 manager = (EXPRESSION)
2170 enter = manager.__enter__
2171 exit = manager.__exit__
2172 value = enter()
2173 hit_except = False
2174
2175 try:
2176 TARGET = value
2177 SUITE
2178 except:
2179 hit_except = True
2180 if not exit(*sys.exc_info()):
2181 raise
2182 finally:
2183 if not hit_except:
2184 exit(None, None, None)
2185
2186 except that implicit special method lookup is used for "__enter__()"
2187 and "__exit__()".
2188
2189 With more than one item, the context managers are processed as if
2190 multiple "with" statements were nested:
2191
2192 with A() as a, B() as b:
2193 SUITE
2194
2195 is semantically equivalent to:
2196
2197 with A() as a:
2198 with B() as b:
2199 SUITE
2200
2201 You can also write multi-item context managers in multiple lines if
2202 the items are surrounded by parentheses. For example:
2203
2204 with (
2205 A() as a,
2206 B() as b,
2207 ):
2208 SUITE
2209
2210 Changed in version 3.1: Support for multiple context expressions.
2211
2212 Changed in version 3.10: Support for using grouping parentheses to
2213 break the statement in multiple lines.
2214
2215 See also:
2216
2217 **PEP 343** - The “with” statement
2218 The specification, background, and examples for the Python "with"
2219 statement.
2220
2221
2222 The "match" statement
2223 =====================
2224
2225 Added in version 3.10.
2226
2227 The match statement is used for pattern matching. Syntax:
2228
2229 match_stmt: 'match' subject_expr ":" NEWLINE INDENT case_block+ DEDENT
2230 subject_expr: `!star_named_expression` "," `!star_named_expressions`?
2231 | `!named_expression`
2232 case_block: 'case' patterns [guard] ":" `!block`
2233
2234 Note:
2235
2236 This section uses single quotes to denote soft keywords.
2237
2238 Pattern matching takes a pattern as input (following "case") and a
2239 subject value (following "match"). The pattern (which may contain
2240 subpatterns) is matched against the subject value. The outcomes are:
2241
2242 * A match success or failure (also termed a pattern success or
2243 failure).
2244
2245 * Possible binding of matched values to a name. The prerequisites for
2246 this are further discussed below.
2247
2248 The "match" and "case" keywords are soft keywords.
2249
2250 See also:
2251
2252 * **PEP 634** – Structural Pattern Matching: Specification
2253
2254 * **PEP 636** – Structural Pattern Matching: Tutorial
2255
2256
2257 Overview
2258 --------
2259
2260 Here’s an overview of the logical flow of a match statement:
2261
2262 1. The subject expression "subject_expr" is evaluated and a resulting
2263 subject value obtained. If the subject expression contains a comma,
2264 a tuple is constructed using the standard rules.
2265
2266 2. Each pattern in a "case_block" is attempted to match with the
2267 subject value. The specific rules for success or failure are
2268 described below. The match attempt can also bind some or all of the
2269 standalone names within the pattern. The precise pattern binding
2270 rules vary per pattern type and are specified below. **Name
2271 bindings made during a successful pattern match outlive the
2272 executed block and can be used after the match statement**.
2273
2274 Note:
2275
2276 During failed pattern matches, some subpatterns may succeed. Do
2277 not rely on bindings being made for a failed match. Conversely,
2278 do not rely on variables remaining unchanged after a failed
2279 match. The exact behavior is dependent on implementation and may
2280 vary. This is an intentional decision made to allow different
2281 implementations to add optimizations.
2282
2283 3. If the pattern succeeds, the corresponding guard (if present) is
2284 evaluated. In this case all name bindings are guaranteed to have
2285 happened.
2286
2287 * If the guard evaluates as true or is missing, the "block" inside
2288 "case_block" is executed.
2289
2290 * Otherwise, the next "case_block" is attempted as described above.
2291
2292 * If there are no further case blocks, the match statement is
2293 completed.
2294
2295 Note:
2296
2297 Users should generally never rely on a pattern being evaluated.
2298 Depending on implementation, the interpreter may cache values or use
2299 other optimizations which skip repeated evaluations.
2300
2301 A sample match statement:
2302
2303 >>> flag = False
2304 >>> match (100, 200):
2305 ... case (100, 300): # Mismatch: 200 != 300
2306 ... print('Case 1')
2307 ... case (100, 200) if flag: # Successful match, but guard fails
2308 ... print('Case 2')
2309 ... case (100, y): # Matches and binds y to 200
2310 ... print(f'Case 3, y: {y}')
2311 ... case _: # Pattern not attempted
2312 ... print('Case 4, I match anything!')
2313 ...
2314 Case 3, y: 200
2315
2316 In this case, "if flag" is a guard. Read more about that in the next
2317 section.
2318
2319
2320 Guards
2321 ------
2322
2323 guard: "if" `!named_expression`
2324
2325 A "guard" (which is part of the "case") must succeed for code inside
2326 the "case" block to execute. It takes the form: "if" followed by an
2327 expression.
2328
2329 The logical flow of a "case" block with a "guard" follows:
2330
2331 1. Check that the pattern in the "case" block succeeded. If the
2332 pattern failed, the "guard" is not evaluated and the next "case"
2333 block is checked.
2334
2335 2. If the pattern succeeded, evaluate the "guard".
2336
2337 * If the "guard" condition evaluates as true, the case block is
2338 selected.
2339
2340 * If the "guard" condition evaluates as false, the case block is
2341 not selected.
2342
2343 * If the "guard" raises an exception during evaluation, the
2344 exception bubbles up.
2345
2346 Guards are allowed to have side effects as they are expressions.
2347 Guard evaluation must proceed from the first to the last case block,
2348 one at a time, skipping case blocks whose pattern(s) don’t all
2349 succeed. (I.e., guard evaluation must happen in order.) Guard
2350 evaluation must stop once a case block is selected.
2351
2352
2353 Irrefutable Case Blocks
2354 -----------------------
2355
2356 An irrefutable case block is a match-all case block. A match
2357 statement may have at most one irrefutable case block, and it must be
2358 last.
2359
2360 A case block is considered irrefutable if it has no guard and its
2361 pattern is irrefutable. A pattern is considered irrefutable if we can
2362 prove from its syntax alone that it will always succeed. Only the
2363 following patterns are irrefutable:
2364
2365 * AS Patterns whose left-hand side is irrefutable
2366
2367 * OR Patterns containing at least one irrefutable pattern
2368
2369 * Capture Patterns
2370
2371 * Wildcard Patterns
2372
2373 * parenthesized irrefutable patterns
2374
2375
2376 Patterns
2377 --------
2378
2379 Note:
2380
2381 This section uses grammar notations beyond standard EBNF:
2382
2383 * the notation "SEP.RULE+" is shorthand for "RULE (SEP RULE)*"
2384
2385 * the notation "!RULE" is shorthand for a negative lookahead
2386 assertion
2387
2388 The top-level syntax for "patterns" is:
2389
2390 patterns: open_sequence_pattern | pattern
2391 pattern: as_pattern | or_pattern
2392 closed_pattern: | literal_pattern
2393 | capture_pattern
2394 | wildcard_pattern
2395 | value_pattern
2396 | group_pattern
2397 | sequence_pattern
2398 | mapping_pattern
2399 | class_pattern
2400
2401 The descriptions below will include a description “in simple terms” of
2402 what a pattern does for illustration purposes (credits to Raymond
2403 Hettinger for a document that inspired most of the descriptions). Note
2404 that these descriptions are purely for illustration purposes and **may
2405 not** reflect the underlying implementation. Furthermore, they do not
2406 cover all valid forms.
2407
2408
2409 OR Patterns
2410 ~~~~~~~~~~~
2411
2412 An OR pattern is two or more patterns separated by vertical bars "|".
2413 Syntax:
2414
2415 or_pattern: "|".closed_pattern+
2416
2417 Only the final subpattern may be irrefutable, and each subpattern must
2418 bind the same set of names to avoid ambiguity.
2419
2420 An OR pattern matches each of its subpatterns in turn to the subject
2421 value, until one succeeds. The OR pattern is then considered
2422 successful. Otherwise, if none of the subpatterns succeed, the OR
2423 pattern fails.
2424
2425 In simple terms, "P1 | P2 | ..." will try to match "P1", if it fails
2426 it will try to match "P2", succeeding immediately if any succeeds,
2427 failing otherwise.
2428
2429
2430 AS Patterns
2431 ~~~~~~~~~~~
2432
2433 An AS pattern matches an OR pattern on the left of the "as" keyword
2434 against a subject. Syntax:
2435
2436 as_pattern: or_pattern "as" capture_pattern
2437
2438 If the OR pattern fails, the AS pattern fails. Otherwise, the AS
2439 pattern binds the subject to the name on the right of the as keyword
2440 and succeeds. "capture_pattern" cannot be a "_".
2441
2442 In simple terms "P as NAME" will match with "P", and on success it
2443 will set "NAME = <subject>".
2444
2445
2446 Literal Patterns
2447 ~~~~~~~~~~~~~~~~
2448
2449 A literal pattern corresponds to most literals in Python. Syntax:
2450
2451 literal_pattern: signed_number
2452 | signed_number "+" NUMBER
2453 | signed_number "-" NUMBER
2454 | strings
2455 | "None"
2456 | "True"
2457 | "False"
2458 signed_number: ["-"] NUMBER
2459
2460 The rule "strings" and the token "NUMBER" are defined in the standard
2461 Python grammar. Triple-quoted strings are supported. Raw strings and
2462 byte strings are supported. f-strings and t-strings are not
2463 supported.
2464
2465 The forms "signed_number '+' NUMBER" and "signed_number '-' NUMBER"
2466 are for expressing complex numbers; they require a real number on the
2467 left and an imaginary number on the right. E.g. "3 + 4j".
2468
2469 In simple terms, "LITERAL" will succeed only if "<subject> ==
2470 LITERAL". For the singletons "None", "True" and "False", the "is"
2471 operator is used.
2472
2473
2474 Capture Patterns
2475 ~~~~~~~~~~~~~~~~
2476
2477 A capture pattern binds the subject value to a name. Syntax:
2478
2479 capture_pattern: !'_' NAME
2480
2481 A single underscore "_" is not a capture pattern (this is what "!'_'"
2482 expresses). It is instead treated as a "wildcard_pattern".
2483
2484 In a given pattern, a given name can only be bound once. E.g. "case
2485 x, x: ..." is invalid while "case [x] | x: ..." is allowed.
2486
2487 Capture patterns always succeed. The binding follows scoping rules
2488 established by the assignment expression operator in **PEP 572**; the
2489 name becomes a local variable in the closest containing function scope
2490 unless there’s an applicable "global" or "nonlocal" statement.
2491
2492 In simple terms "NAME" will always succeed and it will set "NAME =
2493 <subject>".
2494
2495
2496 Wildcard Patterns
2497 ~~~~~~~~~~~~~~~~~
2498
2499 A wildcard pattern always succeeds (matches anything) and binds no
2500 name. Syntax:
2501
2502 wildcard_pattern: '_'
2503
2504 "_" is a soft keyword within any pattern, but only within patterns.
2505 It is an identifier, as usual, even within "match" subject
2506 expressions, "guard"s, and "case" blocks.
2507
2508 In simple terms, "_" will always succeed.
2509
2510
2511 Value Patterns
2512 ~~~~~~~~~~~~~~
2513
2514 A value pattern represents a named value in Python. Syntax:
2515
2516 value_pattern: attr
2517 attr: name_or_attr "." NAME
2518 name_or_attr: attr | NAME
2519
2520 The dotted name in the pattern is looked up using standard Python name
2521 resolution rules. The pattern succeeds if the value found compares
2522 equal to the subject value (using the "==" equality operator).
2523
2524 In simple terms "NAME1.NAME2" will succeed only if "<subject> ==
2525 NAME1.NAME2"
2526
2527 Note:
2528
2529 If the same value occurs multiple times in the same match statement,
2530 the interpreter may cache the first value found and reuse it rather
2531 than repeat the same lookup. This cache is strictly tied to a given
2532 execution of a given match statement.
2533
2534
2535 Group Patterns
2536 ~~~~~~~~~~~~~~
2537
2538 A group pattern allows users to add parentheses around patterns to
2539 emphasize the intended grouping. Otherwise, it has no additional
2540 syntax. Syntax:
2541
2542 group_pattern: "(" pattern ")"
2543
2544 In simple terms "(P)" has the same effect as "P".
2545
2546
2547 Sequence Patterns
2548 ~~~~~~~~~~~~~~~~~
2549
2550 A sequence pattern contains several subpatterns to be matched against
2551 sequence elements. The syntax is similar to the unpacking of a list or
2552 tuple.
2553
2554 sequence_pattern: "[" [maybe_sequence_pattern] "]"
2555 | "(" [open_sequence_pattern] ")"
2556 open_sequence_pattern: maybe_star_pattern "," [maybe_sequence_pattern]
2557 maybe_sequence_pattern: ",".maybe_star_pattern+ ","?
2558 maybe_star_pattern: star_pattern | pattern
2559 star_pattern: "*" (capture_pattern | wildcard_pattern)
2560
2561 There is no difference if parentheses or square brackets are used for
2562 sequence patterns (i.e. "(...)" vs "[...]" ).
2563
2564 Note:
2565
2566 A single pattern enclosed in parentheses without a trailing comma
2567 (e.g. "(3 | 4)") is a group pattern. While a single pattern enclosed
2568 in square brackets (e.g. "[3 | 4]") is still a sequence pattern.
2569
2570 At most one star subpattern may be in a sequence pattern. The star
2571 subpattern may occur in any position. If no star subpattern is
2572 present, the sequence pattern is a fixed-length sequence pattern;
2573 otherwise it is a variable-length sequence pattern.
2574
2575 The following is the logical flow for matching a sequence pattern
2576 against a subject value:
2577
2578 1. If the subject value is not a sequence [2], the sequence pattern
2579 fails.
2580
2581 2. If the subject value is an instance of "str", "bytes" or
2582 "bytearray" the sequence pattern fails.
2583
2584 3. The subsequent steps depend on whether the sequence pattern is
2585 fixed or variable-length.
2586
2587 If the sequence pattern is fixed-length:
2588
2589 1. If the length of the subject sequence is not equal to the number
2590 of subpatterns, the sequence pattern fails
2591
2592 2. Subpatterns in the sequence pattern are matched to their
2593 corresponding items in the subject sequence from left to right.
2594 Matching stops as soon as a subpattern fails. If all
2595 subpatterns succeed in matching their corresponding item, the
2596 sequence pattern succeeds.
2597
2598 Otherwise, if the sequence pattern is variable-length:
2599
2600 1. If the length of the subject sequence is less than the number of
2601 non-star subpatterns, the sequence pattern fails.
2602
2603 2. The leading non-star subpatterns are matched to their
2604 corresponding items as for fixed-length sequences.
2605
2606 3. If the previous step succeeds, the star subpattern matches a
2607 list formed of the remaining subject items, excluding the
2608 remaining items corresponding to non-star subpatterns following
2609 the star subpattern.
2610
2611 4. Remaining non-star subpatterns are matched to their
2612 corresponding subject items, as for a fixed-length sequence.
2613
2614 Note:
2615
2616 The length of the subject sequence is obtained via "len()" (i.e.
2617 via the "__len__()" protocol). This length may be cached by the
2618 interpreter in a similar manner as value patterns.
2619
2620 In simple terms "[P1, P2, P3," … ", P<N>]" matches only if all the
2621 following happens:
2622
2623 * check "<subject>" is a sequence
2624
2625 * "len(subject) == <N>"
2626
2627 * "P1" matches "<subject>[0]" (note that this match can also bind
2628 names)
2629
2630 * "P2" matches "<subject>[1]" (note that this match can also bind
2631 names)
2632
2633 * … and so on for the corresponding pattern/element.
2634
2635
2636 Mapping Patterns
2637 ~~~~~~~~~~~~~~~~
2638
2639 A mapping pattern contains one or more key-value patterns. The syntax
2640 is similar to the construction of a dictionary. Syntax:
2641
2642 mapping_pattern: "{" [items_pattern] "}"
2643 items_pattern: ",".key_value_pattern+ ","?
2644 key_value_pattern: (literal_pattern | value_pattern) ":" pattern
2645 | double_star_pattern
2646 double_star_pattern: "**" capture_pattern
2647
2648 At most one double star pattern may be in a mapping pattern. The
2649 double star pattern must be the last subpattern in the mapping
2650 pattern.
2651
2652 Duplicate keys in mapping patterns are disallowed. Duplicate literal
2653 keys will raise a "SyntaxError". Two keys that otherwise have the same
2654 value will raise a "ValueError" at runtime.
2655
2656 The following is the logical flow for matching a mapping pattern
2657 against a subject value:
2658
2659 1. If the subject value is not a mapping [3],the mapping pattern
2660 fails.
2661
2662 2. If every key given in the mapping pattern is present in the subject
2663 mapping, and the pattern for each key matches the corresponding
2664 item of the subject mapping, the mapping pattern succeeds.
2665
2666 3. If duplicate keys are detected in the mapping pattern, the pattern
2667 is considered invalid. A "SyntaxError" is raised for duplicate
2668 literal values; or a "ValueError" for named keys of the same value.
2669
2670 Note:
2671
2672 Key-value pairs are matched using the two-argument form of the
2673 mapping subject’s "get()" method. Matched key-value pairs must
2674 already be present in the mapping, and not created on-the-fly via
2675 "__missing__()" or "__getitem__()".
2676
2677 In simple terms "{KEY1: P1, KEY2: P2, ... }" matches only if all the
2678 following happens:
2679
2680 * check "<subject>" is a mapping
2681
2682 * "KEY1 in <subject>"
2683
2684 * "P1" matches "<subject>[KEY1]"
2685
2686 * … and so on for the corresponding KEY/pattern pair.
2687
2688
2689 Class Patterns
2690 ~~~~~~~~~~~~~~
2691
2692 A class pattern represents a class and its positional and keyword
2693 arguments (if any). Syntax:
2694
2695 class_pattern: name_or_attr "(" [pattern_arguments ","?] ")"
2696 pattern_arguments: positional_patterns ["," keyword_patterns]
2697 | keyword_patterns
2698 positional_patterns: ",".pattern+
2699 keyword_patterns: ",".keyword_pattern+
2700 keyword_pattern: NAME "=" pattern
2701
2702 The same keyword should not be repeated in class patterns.
2703
2704 The following is the logical flow for matching a class pattern against
2705 a subject value:
2706
2707 1. If "name_or_attr" is not an instance of the builtin "type" , raise
2708 "TypeError".
2709
2710 2. If the subject value is not an instance of "name_or_attr" (tested
2711 via "isinstance()"), the class pattern fails.
2712
2713 3. If no pattern arguments are present, the pattern succeeds.
2714 Otherwise, the subsequent steps depend on whether keyword or
2715 positional argument patterns are present.
2716
2717 For a number of built-in types (specified below), a single
2718 positional subpattern is accepted which will match the entire
2719 subject; for these types keyword patterns also work as for other
2720 types.
2721
2722 If only keyword patterns are present, they are processed as
2723 follows, one by one:
2724
2725 1. The keyword is looked up as an attribute on the subject.
2726
2727 * If this raises an exception other than "AttributeError", the
2728 exception bubbles up.
2729
2730 * If this raises "AttributeError", the class pattern has failed.
2731
2732 * Else, the subpattern associated with the keyword pattern is
2733 matched against the subject’s attribute value. If this fails,
2734 the class pattern fails; if this succeeds, the match proceeds
2735 to the next keyword.
2736
2737 2. If all keyword patterns succeed, the class pattern succeeds.
2738
2739 If any positional patterns are present, they are converted to
2740 keyword patterns using the "__match_args__" attribute on the class
2741 "name_or_attr" before matching:
2742
2743 1. The equivalent of "getattr(cls, "__match_args__", ())" is
2744 called.
2745
2746 * If this raises an exception, the exception bubbles up.
2747
2748 * If the returned value is not a tuple, the conversion fails and
2749 "TypeError" is raised.
2750
2751 * If there are more positional patterns than
2752 "len(cls.__match_args__)", "TypeError" is raised.
2753
2754 * Otherwise, positional pattern "i" is converted to a keyword
2755 pattern using "__match_args__[i]" as the keyword.
2756 "__match_args__[i]" must be a string; if not "TypeError" is
2757 raised.
2758
2759 * If there are duplicate keywords, "TypeError" is raised.
2760
2761 See also:
2762
2763 Customizing positional arguments in class pattern matching
2764
2765 2. Once all positional patterns have been converted to keyword
2766 patterns, the match proceeds as if there were only keyword
2767 patterns.
2768
2769 For the following built-in types the handling of positional
2770 subpatterns is different:
2771
2772 * "bool"
2773
2774 * "bytearray"
2775
2776 * "bytes"
2777
2778 * "dict"
2779
2780 * "float"
2781
2782 * "frozenset"
2783
2784 * "int"
2785
2786 * "list"
2787
2788 * "set"
2789
2790 * "str"
2791
2792 * "tuple"
2793
2794 These classes accept a single positional argument, and the pattern
2795 there is matched against the whole object rather than an attribute.
2796 For example "int(0|1)" matches the value "0", but not the value
2797 "0.0".
2798
2799 In simple terms "CLS(P1, attr=P2)" matches only if the following
2800 happens:
2801
2802 * "isinstance(<subject>, CLS)"
2803
2804 * convert "P1" to a keyword pattern using "CLS.__match_args__"
2805
2806 * For each keyword argument "attr=P2":
2807
2808 * "hasattr(<subject>, "attr")"
2809
2810 * "P2" matches "<subject>.attr"
2811
2812 * … and so on for the corresponding keyword argument/pattern pair.
2813
2814 See also:
2815
2816 * **PEP 634** – Structural Pattern Matching: Specification
2817
2818 * **PEP 636** – Structural Pattern Matching: Tutorial
2819
2820
2821 Function definitions
2822 ====================
2823
2824 A function definition defines a user-defined function object (see
2825 section The standard type hierarchy):
2826
2827 funcdef: [decorators] "def" funcname [type_params] "(" [parameter_list] ")"
2828 ["->" expression] ":" suite
2829 decorators: decorator+
2830 decorator: "@" assignment_expression NEWLINE
2831 parameter_list: defparameter ("," defparameter)* "," "/" ["," [parameter_list_no_posonly]]
2832 | parameter_list_no_posonly
2833 parameter_list_no_posonly: defparameter ("," defparameter)* ["," [parameter_list_starargs]]
2834 | parameter_list_starargs
2835 parameter_list_starargs: "*" [star_parameter] ("," defparameter)* ["," [parameter_star_kwargs]]
2836 | "*" ("," defparameter)+ ["," [parameter_star_kwargs]]
2837 | parameter_star_kwargs
2838 parameter_star_kwargs: "**" parameter [","]
2839 parameter: identifier [":" expression]
2840 star_parameter: identifier [":" ["*"] expression]
2841 defparameter: parameter ["=" expression]
2842 funcname: identifier
2843
2844 A function definition is an executable statement. Its execution binds
2845 the function name in the current local namespace to a function object
2846 (a wrapper around the executable code for the function). This
2847 function object contains a reference to the current global namespace
2848 as the global namespace to be used when the function is called.
2849
2850 The function definition does not execute the function body; this gets
2851 executed only when the function is called. [4]
2852
2853 A function definition may be wrapped by one or more *decorator*
2854 expressions. Decorator expressions are evaluated when the function is
2855 defined, in the scope that contains the function definition. The
2856 result must be a callable, which is invoked with the function object
2857 as the only argument. The returned value is bound to the function name
2858 instead of the function object. Multiple decorators are applied in
2859 nested fashion. For example, the following code
2860
2861 @f1(arg)
2862 @f2
2863 def func(): pass
2864
2865 is roughly equivalent to
2866
2867 def func(): pass
2868 func = f1(arg)(f2(func))
2869
2870 except that the original function is not temporarily bound to the name
2871 "func".
2872
2873 Changed in version 3.9: Functions may be decorated with any valid
2874 "assignment_expression". Previously, the grammar was much more
2875 restrictive; see **PEP 614** for details.
2876
2877 A list of type parameters may be given in square brackets between the
2878 function’s name and the opening parenthesis for its parameter list.
2879 This indicates to static type checkers that the function is generic.
2880 At runtime, the type parameters can be retrieved from the function’s
2881 "__type_params__" attribute. See Generic functions for more.
2882
2883 Changed in version 3.12: Type parameter lists are new in Python 3.12.
2884
2885 When one or more *parameters* have the form *parameter* "="
2886 *expression*, the function is said to have “default parameter values.”
2887 For a parameter with a default value, the corresponding *argument* may
2888 be omitted from a call, in which case the parameter’s default value is
2889 substituted. If a parameter has a default value, all following
2890 parameters up until the “"*"” must also have a default value — this is
2891 a syntactic restriction that is not expressed by the grammar.
2892
2893 **Default parameter values are evaluated from left to right when the
2894 function definition is executed.** This means that the expression is
2895 evaluated once, when the function is defined, and that the same “pre-
2896 computed” value is used for each call. This is especially important
2897 to understand when a default parameter value is a mutable object, such
2898 as a list or a dictionary: if the function modifies the object (e.g.
2899 by appending an item to a list), the default parameter value is in
2900 effect modified. This is generally not what was intended. A way
2901 around this is to use "None" as the default, and explicitly test for
2902 it in the body of the function, e.g.:
2903
2904 def whats_on_the_telly(penguin=None):
2905 if penguin is None:
2906 penguin = []
2907 penguin.append("property of the zoo")
2908 return penguin
2909
2910 Function call semantics are described in more detail in section Calls.
2911 A function call always assigns values to all parameters mentioned in
2912 the parameter list, either from positional arguments, from keyword
2913 arguments, or from default values. If the form “"*identifier"” is
2914 present, it is initialized to a tuple receiving any excess positional
2915 parameters, defaulting to the empty tuple. If the form
2916 “"**identifier"” is present, it is initialized to a new ordered
2917 mapping receiving any excess keyword arguments, defaulting to a new
2918 empty mapping of the same type. Parameters after “"*"” or
2919 “"*identifier"” are keyword-only parameters and may only be passed by
2920 keyword arguments. Parameters before “"/"” are positional-only
2921 parameters and may only be passed by positional arguments.
2922
2923 Changed in version 3.8: The "/" function parameter syntax may be used
2924 to indicate positional-only parameters. See **PEP 570** for details.
2925
2926 Parameters may have an *annotation* of the form “": expression"”
2927 following the parameter name. Any parameter may have an annotation,
2928 even those of the form "*identifier" or "**identifier". (As a special
2929 case, parameters of the form "*identifier" may have an annotation “":
2930 *expression"”.) Functions may have “return” annotation of the form
2931 “"-> expression"” after the parameter list. These annotations can be
2932 any valid Python expression. The presence of annotations does not
2933 change the semantics of a function. See Annotations for more
2934 information on annotations.
2935
2936 Changed in version 3.11: Parameters of the form “"*identifier"” may
2937 have an annotation “": *expression"”. See **PEP 646**.
2938
2939 It is also possible to create anonymous functions (functions not bound
2940 to a name), for immediate use in expressions. This uses lambda
2941 expressions, described in section Lambdas. Note that the lambda
2942 expression is merely a shorthand for a simplified function definition;
2943 a function defined in a “"def"” statement can be passed around or
2944 assigned to another name just like a function defined by a lambda
2945 expression. The “"def"” form is actually more powerful since it
2946 allows the execution of multiple statements and annotations.
2947
2948 **Programmer’s note:** Functions are first-class objects. A “"def"”
2949 statement executed inside a function definition defines a local
2950 function that can be returned or passed around. Free variables used
2951 in the nested function can access the local variables of the function
2952 containing the def. See section Naming and binding for details.
2953
2954 See also:
2955
2956 **PEP 3107** - Function Annotations
2957 The original specification for function annotations.
2958
2959 **PEP 484** - Type Hints
2960 Definition of a standard meaning for annotations: type hints.
2961
2962 **PEP 526** - Syntax for Variable Annotations
2963 Ability to type hint variable declarations, including class
2964 variables and instance variables.
2965
2966 **PEP 563** - Postponed Evaluation of Annotations
2967 Support for forward references within annotations by preserving
2968 annotations in a string form at runtime instead of eager
2969 evaluation.
2970
2971 **PEP 318** - Decorators for Functions and Methods
2972 Function and method decorators were introduced. Class decorators
2973 were introduced in **PEP 3129**.
2974
2975
2976 Class definitions
2977 =================
2978
2979 A class definition defines a class object (see section The standard
2980 type hierarchy):
2981
2982 classdef: [decorators] "class" classname [type_params] [inheritance] ":" suite
2983 inheritance: "(" [argument_list] ")"
2984 classname: identifier
2985
2986 A class definition is an executable statement. The inheritance list
2987 usually gives a list of base classes (see Metaclasses for more
2988 advanced uses), so each item in the list should evaluate to a class
2989 object which allows subclassing. Classes without an inheritance list
2990 inherit, by default, from the base class "object"; hence,
2991
2992 class Foo:
2993 pass
2994
2995 is equivalent to
2996
2997 class Foo(object):
2998 pass
2999
3000 The class’s suite is then executed in a new execution frame (see
3001 Naming and binding), using a newly created local namespace and the
3002 original global namespace. (Usually, the suite contains mostly
3003 function definitions.) When the class’s suite finishes execution, its
3004 execution frame is discarded but its local namespace is saved. [5] A
3005 class object is then created using the inheritance list for the base
3006 classes and the saved local namespace for the attribute dictionary.
3007 The class name is bound to this class object in the original local
3008 namespace.
3009
3010 The order in which attributes are defined in the class body is
3011 preserved in the new class’s "__dict__". Note that this is reliable
3012 only right after the class is created and only for classes that were
3013 defined using the definition syntax.
3014
3015 Class creation can be customized heavily using metaclasses.
3016
3017 Classes can also be decorated: just like when decorating functions,
3018
3019 @f1(arg)
3020 @f2
3021 class Foo: pass
3022
3023 is roughly equivalent to
3024
3025 class Foo: pass
3026 Foo = f1(arg)(f2(Foo))
3027
3028 The evaluation rules for the decorator expressions are the same as for
3029 function decorators. The result is then bound to the class name.
3030
3031 Changed in version 3.9: Classes may be decorated with any valid
3032 "assignment_expression". Previously, the grammar was much more
3033 restrictive; see **PEP 614** for details.
3034
3035 A list of type parameters may be given in square brackets immediately
3036 after the class’s name. This indicates to static type checkers that
3037 the class is generic. At runtime, the type parameters can be retrieved
3038 from the class’s "__type_params__" attribute. See Generic classes for
3039 more.
3040
3041 Changed in version 3.12: Type parameter lists are new in Python 3.12.
3042
3043 **Programmer’s note:** Variables defined in the class definition are
3044 class attributes; they are shared by instances. Instance attributes
3045 can be set in a method with "self.name = value". Both class and
3046 instance attributes are accessible through the notation “"self.name"”,
3047 and an instance attribute hides a class attribute with the same name
3048 when accessed in this way. Class attributes can be used as defaults
3049 for instance attributes, but using mutable values there can lead to
3050 unexpected results. Descriptors can be used to create instance
3051 variables with different implementation details.
3052
3053 See also:
3054
3055 **PEP 3115** - Metaclasses in Python 3000
3056 The proposal that changed the declaration of metaclasses to the
3057 current syntax, and the semantics for how classes with
3058 metaclasses are constructed.
3059
3060 **PEP 3129** - Class Decorators
3061 The proposal that added class decorators. Function and method
3062 decorators were introduced in **PEP 318**.
3063
3064
3065 Coroutines
3066 ==========
3067
3068 Added in version 3.5.
3069
3070
3071 Coroutine function definition
3072 -----------------------------
3073
3074 async_funcdef: [decorators] "async" "def" funcname "(" [parameter_list] ")"
3075 ["->" expression] ":" suite
3076
3077 Execution of Python coroutines can be suspended and resumed at many
3078 points (see *coroutine*). "await" expressions, "async for" and "async
3079 with" can only be used in the body of a coroutine function.
3080
3081 Functions defined with "async def" syntax are always coroutine
3082 functions, even if they do not contain "await" or "async" keywords.
3083
3084 It is a "SyntaxError" to use a "yield from" expression inside the body
3085 of a coroutine function.
3086
3087 An example of a coroutine function:
3088
3089 async def func(param1, param2):
3090 do_stuff()
3091 await some_coroutine()
3092
3093 Changed in version 3.7: "await" and "async" are now keywords;
3094 previously they were only treated as such inside the body of a
3095 coroutine function.
3096
3097
3098 The "async for" statement
3099 -------------------------
3100
3101 async_for_stmt: "async" for_stmt
3102
3103 An *asynchronous iterable* provides an "__aiter__" method that
3104 directly returns an *asynchronous iterator*, which can call
3105 asynchronous code in its "__anext__" method.
3106
3107 The "async for" statement allows convenient iteration over
3108 asynchronous iterables.
3109
3110 The following code:
3111
3112 async for TARGET in ITER:
3113 SUITE
3114 else:
3115 SUITE2
3116
3117 Is semantically equivalent to:
3118
3119 iter = (ITER).__aiter__()
3120 running = True
3121
3122 while running:
3123 try:
3124 TARGET = await iter.__anext__()
3125 except StopAsyncIteration:
3126 running = False
3127 else:
3128 SUITE
3129 else:
3130 SUITE2
3131
3132 except that implicit special method lookup is used for "__aiter__()"
3133 and "__anext__()".
3134
3135 It is a "SyntaxError" to use an "async for" statement outside the body
3136 of a coroutine function.
3137
3138
3139 The "async with" statement
3140 --------------------------
3141
3142 async_with_stmt: "async" with_stmt
3143
3144 An *asynchronous context manager* is a *context manager* that is able
3145 to suspend execution in its *enter* and *exit* methods.
3146
3147 The following code:
3148
3149 async with EXPRESSION as TARGET:
3150 SUITE
3151
3152 is semantically equivalent to:
3153
3154 manager = (EXPRESSION)
3155 aenter = manager.__aenter__
3156 aexit = manager.__aexit__
3157 value = await aenter()
3158 hit_except = False
3159
3160 try:
3161 TARGET = value
3162 SUITE
3163 except:
3164 hit_except = True
3165 if not await aexit(*sys.exc_info()):
3166 raise
3167 finally:
3168 if not hit_except:
3169 await aexit(None, None, None)
3170
3171 except that implicit special method lookup is used for "__aenter__()"
3172 and "__aexit__()".
3173
3174 It is a "SyntaxError" to use an "async with" statement outside the
3175 body of a coroutine function.
3176
3177 See also:
3178
3179 **PEP 492** - Coroutines with async and await syntax
3180 The proposal that made coroutines a proper standalone concept in
3181 Python, and added supporting syntax.
3182
3183
3184 Type parameter lists
3185 ====================
3186
3187 Added in version 3.12.
3188
3189 Changed in version 3.13: Support for default values was added (see
3190 **PEP 696**).
3191
3192 type_params: "[" type_param ("," type_param)* "]"
3193 type_param: typevar | typevartuple | paramspec
3194 typevar: identifier (":" expression)? ("=" expression)?
3195 typevartuple: "*" identifier ("=" expression)?
3196 paramspec: "**" identifier ("=" expression)?
3197
3198 Functions (including coroutines), classes and type aliases may contain
3199 a type parameter list:
3200
3201 def max[T](args: list[T]) -> T:
3202 ...
3203
3204 async def amax[T](args: list[T]) -> T:
3205 ...
3206
3207 class Bag[T]:
3208 def __iter__(self) -> Iterator[T]:
3209 ...
3210
3211 def add(self, arg: T) -> None:
3212 ...
3213
3214 type ListOrSet[T] = list[T] | set[T]
3215
3216 Semantically, this indicates that the function, class, or type alias
3217 is generic over a type variable. This information is primarily used by
3218 static type checkers, and at runtime, generic objects behave much like
3219 their non-generic counterparts.
3220
3221 Type parameters are declared in square brackets ("[]") immediately
3222 after the name of the function, class, or type alias. The type
3223 parameters are accessible within the scope of the generic object, but
3224 not elsewhere. Thus, after a declaration "def func[T](): pass", the
3225 name "T" is not available in the module scope. Below, the semantics of
3226 generic objects are described with more precision. The scope of type
3227 parameters is modeled with a special function (technically, an
3228 annotation scope) that wraps the creation of the generic object.
3229
3230 Generic functions, classes, and type aliases have a "__type_params__"
3231 attribute listing their type parameters.
3232
3233 Type parameters come in three kinds:
3234
3235 * "typing.TypeVar", introduced by a plain name (e.g., "T").
3236 Semantically, this represents a single type to a type checker.
3237
3238 * "typing.TypeVarTuple", introduced by a name prefixed with a single
3239 asterisk (e.g., "*Ts"). Semantically, this stands for a tuple of any
3240 number of types.
3241
3242 * "typing.ParamSpec", introduced by a name prefixed with two asterisks
3243 (e.g., "**P"). Semantically, this stands for the parameters of a
3244 callable.
3245
3246 "typing.TypeVar" declarations can define *bounds* and *constraints*
3247 with a colon (":") followed by an expression. A single expression
3248 after the colon indicates a bound (e.g. "T: int"). Semantically, this
3249 means that the "typing.TypeVar" can only represent types that are a
3250 subtype of this bound. A parenthesized tuple of expressions after the
3251 colon indicates a set of constraints (e.g. "T: (str, bytes)"). Each
3252 member of the tuple should be a type (again, this is not enforced at
3253 runtime). Constrained type variables can only take on one of the types
3254 in the list of constraints.
3255
3256 For "typing.TypeVar"s declared using the type parameter list syntax,
3257 the bound and constraints are not evaluated when the generic object is
3258 created, but only when the value is explicitly accessed through the
3259 attributes "__bound__" and "__constraints__". To accomplish this, the
3260 bounds or constraints are evaluated in a separate annotation scope.
3261
3262 "typing.TypeVarTuple"s and "typing.ParamSpec"s cannot have bounds or
3263 constraints.
3264
3265 All three flavors of type parameters can also have a *default value*,
3266 which is used when the type parameter is not explicitly provided. This
3267 is added by appending a single equals sign ("=") followed by an
3268 expression. Like the bounds and constraints of type variables, the
3269 default value is not evaluated when the object is created, but only
3270 when the type parameter’s "__default__" attribute is accessed. To this
3271 end, the default value is evaluated in a separate annotation scope. If
3272 no default value is specified for a type parameter, the "__default__"
3273 attribute is set to the special sentinel object "typing.NoDefault".
3274
3275 The following example indicates the full set of allowed type parameter
3276 declarations:
3277
3278 def overly_generic[
3279 SimpleTypeVar,
3280 TypeVarWithDefault = int,
3281 TypeVarWithBound: int,
3282 TypeVarWithConstraints: (str, bytes),
3283 *SimpleTypeVarTuple = (int, float),
3284 **SimpleParamSpec = (str, bytearray),
3285 ](
3286 a: SimpleTypeVar,
3287 b: TypeVarWithDefault,
3288 c: TypeVarWithBound,
3289 d: Callable[SimpleParamSpec, TypeVarWithConstraints],
3290 *e: SimpleTypeVarTuple,
3291 ): ...
3292
3293
3294 Generic functions
3295 -----------------
3296
3297 Generic functions are declared as follows:
3298
3299 def func[T](arg: T): ...
3300
3301 This syntax is equivalent to:
3302
3303 annotation-def TYPE_PARAMS_OF_func():
3304 T = typing.TypeVar("T")
3305 def func(arg: T): ...
3306 func.__type_params__ = (T,)
3307 return func
3308 func = TYPE_PARAMS_OF_func()
3309
3310 Here "annotation-def" indicates an annotation scope, which is not
3311 actually bound to any name at runtime. (One other liberty is taken in
3312 the translation: the syntax does not go through attribute access on
3313 the "typing" module, but creates an instance of "typing.TypeVar"
3314 directly.)
3315
3316 The annotations of generic functions are evaluated within the
3317 annotation scope used for declaring the type parameters, but the
3318 function’s defaults and decorators are not.
3319
3320 The following example illustrates the scoping rules for these cases,
3321 as well as for additional flavors of type parameters:
3322
3323 @decorator
3324 def func[T: int, *Ts, **P](*args: *Ts, arg: Callable[P, T] = some_default):
3325 ...
3326
3327 Except for the lazy evaluation of the "TypeVar" bound, this is
3328 equivalent to:
3329
3330 DEFAULT_OF_arg = some_default
3331
3332 annotation-def TYPE_PARAMS_OF_func():
3333
3334 annotation-def BOUND_OF_T():
3335 return int
3336 # In reality, BOUND_OF_T() is evaluated only on demand.
3337 T = typing.TypeVar("T", bound=BOUND_OF_T())
3338
3339 Ts = typing.TypeVarTuple("Ts")
3340 P = typing.ParamSpec("P")
3341
3342 def func(*args: *Ts, arg: Callable[P, T] = DEFAULT_OF_arg):
3343 ...
3344
3345 func.__type_params__ = (T, Ts, P)
3346 return func
3347 func = decorator(TYPE_PARAMS_OF_func())
3348
3349 The capitalized names like "DEFAULT_OF_arg" are not actually bound at
3350 runtime.
3351
3352
3353 Generic classes
3354 ---------------
3355
3356 Generic classes are declared as follows:
3357
3358 class Bag[T]: ...
3359
3360 This syntax is equivalent to:
3361
3362 annotation-def TYPE_PARAMS_OF_Bag():
3363 T = typing.TypeVar("T")
3364 class Bag(typing.Generic[T]):
3365 __type_params__ = (T,)
3366 ...
3367 return Bag
3368 Bag = TYPE_PARAMS_OF_Bag()
3369
3370 Here again "annotation-def" (not a real keyword) indicates an
3371 annotation scope, and the name "TYPE_PARAMS_OF_Bag" is not actually
3372 bound at runtime.
3373
3374 Generic classes implicitly inherit from "typing.Generic". The base
3375 classes and keyword arguments of generic classes are evaluated within
3376 the type scope for the type parameters, and decorators are evaluated
3377 outside that scope. This is illustrated by this example:
3378
3379 @decorator
3380 class Bag(Base[T], arg=T): ...
3381
3382 This is equivalent to:
3383
3384 annotation-def TYPE_PARAMS_OF_Bag():
3385 T = typing.TypeVar("T")
3386 class Bag(Base[T], typing.Generic[T], arg=T):
3387 __type_params__ = (T,)
3388 ...
3389 return Bag
3390 Bag = decorator(TYPE_PARAMS_OF_Bag())
3391
3392
3393 Generic type aliases
3394 --------------------
3395
3396 The "type" statement can also be used to create a generic type alias:
3397
3398 type ListOrSet[T] = list[T] | set[T]
3399
3400 Except for the lazy evaluation of the value, this is equivalent to:
3401
3402 annotation-def TYPE_PARAMS_OF_ListOrSet():
3403 T = typing.TypeVar("T")
3404
3405 annotation-def VALUE_OF_ListOrSet():
3406 return list[T] | set[T]
3407 # In reality, the value is lazily evaluated
3408 return typing.TypeAliasType("ListOrSet", VALUE_OF_ListOrSet(), type_params=(T,))
3409 ListOrSet = TYPE_PARAMS_OF_ListOrSet()
3410
3411 Here, "annotation-def" (not a real keyword) indicates an annotation
3412 scope. The capitalized names like "TYPE_PARAMS_OF_ListOrSet" are not
3413 actually bound at runtime.
3414
3415
3416 Annotations
3417 ===========
3418
3419 Changed in version 3.14: Annotations are now lazily evaluated by
3420 default.
3421
3422 Variables and function parameters may carry *annotations*, created by
3423 adding a colon after the name, followed by an expression:
3424
3425 x: annotation = 1
3426 def f(param: annotation): ...
3427
3428 Functions may also carry a return annotation following an arrow:
3429
3430 def f() -> annotation: ...
3431
3432 Annotations are conventionally used for *type hints*, but this is not
3433 enforced by the language, and in general annotations may contain
3434 arbitrary expressions. The presence of annotations does not change the
3435 runtime semantics of the code, except if some mechanism is used that
3436 introspects and uses the annotations (such as "dataclasses" or
3437 "functools.singledispatch()").
3438
3439 By default, annotations are lazily evaluated in an annotation scope.
3440 This means that they are not evaluated when the code containing the
3441 annotation is evaluated. Instead, the interpreter saves information
3442 that can be used to evaluate the annotation later if requested. The
3443 "annotationlib" module provides tools for evaluating annotations.
3444
3445 If the future statement "from __future__ import annotations" is
3446 present, all annotations are instead stored as strings:
3447
3448 >>> from __future__ import annotations
3449 >>> def f(param: annotation): ...
3450 >>> f.__annotations__
3451 {'param': 'annotation'}
3452
3453 This future statement will be deprecated and removed in a future
3454 version of Python, but not before Python 3.13 reaches its end of life
3455 (see **PEP 749**). When it is used, introspection tools like
3456 "annotationlib.get_annotations()" and "typing.get_type_hints()" are
3457 less likely to be able to resolve annotations at runtime.
3458
3459 -[ Footnotes ]-
3460
3461 [1] The exception is propagated to the invocation stack unless there
3462 is a "finally" clause which happens to raise another exception.
3463 That new exception causes the old one to be lost.
3464
3465 [2] In pattern matching, a sequence is defined as one of the
3466 following:
3467
3468 * a class that inherits from "collections.abc.Sequence"
3469
3470 * a Python class that has been registered as
3471 "collections.abc.Sequence"
3472
3473 * a builtin class that has its (CPython) "Py_TPFLAGS_SEQUENCE" bit
3474 set
3475
3476 * a class that inherits from any of the above
3477
3478 The following standard library classes are sequences:
3479
3480 * "array.array"
3481
3482 * "collections.deque"
3483
3484 * "list"
3485
3486 * "memoryview"
3487
3488 * "range"
3489
3490 * "tuple"
3491
3492 Note:
3493
3494 Subject values of type "str", "bytes", and "bytearray" do not
3495 match sequence patterns.
3496
3497 [3] In pattern matching, a mapping is defined as one of the following:
3498
3499 * a class that inherits from "collections.abc.Mapping"
3500
3501 * a Python class that has been registered as
3502 "collections.abc.Mapping"
3503
3504 * a builtin class that has its (CPython) "Py_TPFLAGS_MAPPING" bit
3505 set
3506
3507 * a class that inherits from any of the above
3508
3509 The standard library classes "dict" and "types.MappingProxyType"
3510 are mappings.
3511
3512 [4] A string literal appearing as the first statement in the function
3513 body is transformed into the function’s "__doc__" attribute and
3514 therefore the function’s *docstring*.
3515
3516 [5] A string literal appearing as the first statement in the class
3517 body is transformed into the namespace’s "__doc__" item and
3518 therefore the class’s *docstring*.
3519 ''',
3520 'context-managers': r'''With Statement Context Managers
3521 *******************************
3522
3523 A *context manager* is an object that defines the runtime context to
3524 be established when executing a "with" statement. The context manager
3525 handles the entry into, and the exit from, the desired runtime context
3526 for the execution of the block of code. Context managers are normally
3527 invoked using the "with" statement (described in section The with
3528 statement), but can also be used by directly invoking their methods.
3529
3530 Typical uses of context managers include saving and restoring various
3531 kinds of global state, locking and unlocking resources, closing opened
3532 files, etc.
3533
3534 For more information on context managers, see Context Manager Types.
3535 The "object" class itself does not provide the context manager
3536 methods.
3537
3538 object.__enter__(self)
3539
3540 Enter the runtime context related to this object. The "with"
3541 statement will bind this method’s return value to the target(s)
3542 specified in the "as" clause of the statement, if any.
3543
3544 object.__exit__(self, exc_type, exc_value, traceback)
3545
3546 Exit the runtime context related to this object. The parameters
3547 describe the exception that caused the context to be exited. If the
3548 context was exited without an exception, all three arguments will
3549 be "None".
3550
3551 If an exception is supplied, and the method wishes to suppress the
3552 exception (i.e., prevent it from being propagated), it should
3553 return a true value. Otherwise, the exception will be processed
3554 normally upon exit from this method.
3555
3556 Note that "__exit__()" methods should not reraise the passed-in
3557 exception; this is the caller’s responsibility.
3558
3559 See also:
3560
3561 **PEP 343** - The “with” statement
3562 The specification, background, and examples for the Python "with"
3563 statement.
3564 ''',
3565 'continue': r'''The "continue" statement
3566 ************************
3567
3568 continue_stmt: "continue"
3569
3570 "continue" may only occur syntactically nested in a "for" or "while"
3571 loop, but not nested in a function or class definition within that
3572 loop. It continues with the next cycle of the nearest enclosing loop.
3573
3574 When "continue" passes control out of a "try" statement with a
3575 "finally" clause, that "finally" clause is executed before really
3576 starting the next loop cycle.
3577 ''',
3578 'conversions': r'''Arithmetic conversions
3579 **********************
3580
3581 When a description of an arithmetic operator below uses the phrase
3582 “the numeric arguments are converted to a common real type”, this
3583 means that the operator implementation for built-in numeric types
3584 works as described in the Numeric Types section of the standard
3585 library documentation.
3586
3587 Some additional rules apply for certain operators and non-numeric
3588 operands (for example, a string as a left argument to the "%"
3589 operator). Extensions must define their own conversion behavior.
3590 ''',
3591 'customization': r'''Basic customization
3592 *******************
3593
3594 object.__new__(cls[, ...])
3595
3596 Called to create a new instance of class *cls*. "__new__()" is a
3597 static method (special-cased so you need not declare it as such)
3598 that takes the class of which an instance was requested as its
3599 first argument. The remaining arguments are those passed to the
3600 object constructor expression (the call to the class). The return
3601 value of "__new__()" should be the new object instance (usually an
3602 instance of *cls*).
3603
3604 Typical implementations create a new instance of the class by
3605 invoking the superclass’s "__new__()" method using
3606 "super().__new__(cls[, ...])" with appropriate arguments and then
3607 modifying the newly created instance as necessary before returning
3608 it.
3609
3610 If "__new__()" is invoked during object construction and it returns
3611 an instance of *cls*, then the new instance’s "__init__()" method
3612 will be invoked like "__init__(self[, ...])", where *self* is the
3613 new instance and the remaining arguments are the same as were
3614 passed to the object constructor.
3615
3616 If "__new__()" does not return an instance of *cls*, then the new
3617 instance’s "__init__()" method will not be invoked.
3618
3619 "__new__()" is intended mainly to allow subclasses of immutable
3620 types (like int, str, or tuple) to customize instance creation. It
3621 is also commonly overridden in custom metaclasses in order to
3622 customize class creation.
3623
3624 object.__init__(self[, ...])
3625
3626 Called after the instance has been created (by "__new__()"), but
3627 before it is returned to the caller. The arguments are those
3628 passed to the class constructor expression. If a base class has an
3629 "__init__()" method, the derived class’s "__init__()" method, if
3630 any, must explicitly call it to ensure proper initialization of the
3631 base class part of the instance; for example:
3632 "super().__init__([args...])".
3633
3634 Because "__new__()" and "__init__()" work together in constructing
3635 objects ("__new__()" to create it, and "__init__()" to customize
3636 it), no non-"None" value may be returned by "__init__()"; doing so
3637 will cause a "TypeError" to be raised at runtime.
3638
3639 object.__del__(self)
3640
3641 Called when the instance is about to be destroyed. This is also
3642 called a finalizer or (improperly) a destructor. If a base class
3643 has a "__del__()" method, the derived class’s "__del__()" method,
3644 if any, must explicitly call it to ensure proper deletion of the
3645 base class part of the instance.
3646
3647 It is possible (though not recommended!) for the "__del__()" method
3648 to postpone destruction of the instance by creating a new reference
3649 to it. This is called object *resurrection*. It is
3650 implementation-dependent whether "__del__()" is called a second
3651 time when a resurrected object is about to be destroyed; the
3652 current *CPython* implementation only calls it once.
3653
3654 It is not guaranteed that "__del__()" methods are called for
3655 objects that still exist when the interpreter exits.
3656 "weakref.finalize" provides a straightforward way to register a
3657 cleanup function to be called when an object is garbage collected.
3658
3659 Note:
3660
3661 "del x" doesn’t directly call "x.__del__()" — the former
3662 decrements the reference count for "x" by one, and the latter is
3663 only called when "x"’s reference count reaches zero.
3664
3665 **CPython implementation detail:** It is possible for a reference
3666 cycle to prevent the reference count of an object from going to
3667 zero. In this case, the cycle will be later detected and deleted
3668 by the *cyclic garbage collector*. A common cause of reference
3669 cycles is when an exception has been caught in a local variable.
3670 The frame’s locals then reference the exception, which references
3671 its own traceback, which references the locals of all frames caught
3672 in the traceback.
3673
3674 See also: Documentation for the "gc" module.
3675
3676 Warning:
3677
3678 Due to the precarious circumstances under which "__del__()"
3679 methods are invoked, exceptions that occur during their execution
3680 are ignored, and a warning is printed to "sys.stderr" instead.
3681 In particular:
3682
3683 * "__del__()" can be invoked when arbitrary code is being
3684 executed, including from any arbitrary thread. If "__del__()"
3685 needs to take a lock or invoke any other blocking resource, it
3686 may deadlock as the resource may already be taken by the code
3687 that gets interrupted to execute "__del__()".
3688
3689 * "__del__()" can be executed during interpreter shutdown. As a
3690 consequence, the global variables it needs to access (including
3691 other modules) may already have been deleted or set to "None".
3692 Python guarantees that globals whose name begins with a single
3693 underscore are deleted from their module before other globals
3694 are deleted; if no other references to such globals exist, this
3695 may help in assuring that imported modules are still available
3696 at the time when the "__del__()" method is called.
3697
3698 object.__repr__(self)
3699
3700 Called by the "repr()" built-in function to compute the “official”
3701 string representation of an object. If at all possible, this
3702 should look like a valid Python expression that could be used to
3703 recreate an object with the same value (given an appropriate
3704 environment). If this is not possible, a string of the form
3705 "<...some useful description...>" should be returned. The return
3706 value must be a string object. If a class defines "__repr__()" but
3707 not "__str__()", then "__repr__()" is also used when an “informal”
3708 string representation of instances of that class is required.
3709
3710 This is typically used for debugging, so it is important that the
3711 representation is information-rich and unambiguous. A default
3712 implementation is provided by the "object" class itself.
3713
3714 object.__str__(self)
3715
3716 Called by "str(object)", the default "__format__()" implementation,
3717 and the built-in function "print()", to compute the “informal” or
3718 nicely printable string representation of an object. The return
3719 value must be a str object.
3720
3721 This method differs from "object.__repr__()" in that there is no
3722 expectation that "__str__()" return a valid Python expression: a
3723 more convenient or concise representation can be used.
3724
3725 The default implementation defined by the built-in type "object"
3726 calls "object.__repr__()".
3727
3728 object.__bytes__(self)
3729
3730 Called by bytes to compute a byte-string representation of an
3731 object. This should return a "bytes" object. The "object" class
3732 itself does not provide this method.
3733
3734 object.__format__(self, format_spec)
3735
3736 Called by the "format()" built-in function, and by extension,
3737 evaluation of formatted string literals and the "str.format()"
3738 method, to produce a “formatted” string representation of an
3739 object. The *format_spec* argument is a string that contains a
3740 description of the formatting options desired. The interpretation
3741 of the *format_spec* argument is up to the type implementing
3742 "__format__()", however most classes will either delegate
3743 formatting to one of the built-in types, or use a similar
3744 formatting option syntax.
3745
3746 See Format specification mini-language for a description of the
3747 standard formatting syntax.
3748
3749 The return value must be a string object.
3750
3751 The default implementation by the "object" class should be given an
3752 empty *format_spec* string. It delegates to "__str__()".
3753
3754 Changed in version 3.4: The __format__ method of "object" itself
3755 raises a "TypeError" if passed any non-empty string.
3756
3757 Changed in version 3.7: "object.__format__(x, '')" is now
3758 equivalent to "str(x)" rather than "format(str(x), '')".
3759
3760 object.__lt__(self, other)
3761 object.__le__(self, other)
3762 object.__eq__(self, other)
3763 object.__ne__(self, other)
3764 object.__gt__(self, other)
3765 object.__ge__(self, other)
3766
3767 These are the so-called “rich comparison” methods. The
3768 correspondence between operator symbols and method names is as
3769 follows: "x<y" calls "x.__lt__(y)", "x<=y" calls "x.__le__(y)",
3770 "x==y" calls "x.__eq__(y)", "x!=y" calls "x.__ne__(y)", "x>y" calls
3771 "x.__gt__(y)", and "x>=y" calls "x.__ge__(y)".
3772
3773 A rich comparison method may return the singleton "NotImplemented"
3774 if it does not implement the operation for a given pair of
3775 arguments. By convention, "False" and "True" are returned for a
3776 successful comparison. However, these methods can return any value,
3777 so if the comparison operator is used in a Boolean context (e.g.,
3778 in the condition of an "if" statement), Python will call "bool()"
3779 on the value to determine if the result is true or false.
3780
3781 By default, "object" implements "__eq__()" by using "is", returning
3782 "NotImplemented" in the case of a false comparison: "True if x is y
3783 else NotImplemented". For "__ne__()", by default it delegates to
3784 "__eq__()" and inverts the result unless it is "NotImplemented".
3785 There are no other implied relationships among the comparison
3786 operators or default implementations; for example, the truth of
3787 "(x<y or x==y)" does not imply "x<=y". To automatically generate
3788 ordering operations from a single root operation, see
3789 "functools.total_ordering()".
3790
3791 By default, the "object" class provides implementations consistent
3792 with Value comparisons: equality compares according to object
3793 identity, and order comparisons raise "TypeError". Each default
3794 method may generate these results directly, but may also return
3795 "NotImplemented".
3796
3797 See the paragraph on "__hash__()" for some important notes on
3798 creating *hashable* objects which support custom comparison
3799 operations and are usable as dictionary keys.
3800
3801 There are no swapped-argument versions of these methods (to be used
3802 when the left argument does not support the operation but the right
3803 argument does); rather, "__lt__()" and "__gt__()" are each other’s
3804 reflection, "__le__()" and "__ge__()" are each other’s reflection,
3805 and "__eq__()" and "__ne__()" are their own reflection. If the
3806 operands are of different types, and the right operand’s type is a
3807 direct or indirect subclass of the left operand’s type, the
3808 reflected method of the right operand has priority, otherwise the
3809 left operand’s method has priority. Virtual subclassing is not
3810 considered.
3811
3812 When no appropriate method returns any value other than
3813 "NotImplemented", the "==" and "!=" operators will fall back to
3814 "is" and "is not", respectively.
3815
3816 object.__hash__(self)
3817
3818 Called by built-in function "hash()" and for operations on members
3819 of hashed collections including "set", "frozenset", and "dict".
3820 The "__hash__()" method should return an integer. The only required
3821 property is that objects which compare equal have the same hash
3822 value; it is advised to mix together the hash values of the
3823 components of the object that also play a part in comparison of
3824 objects by packing them into a tuple and hashing the tuple.
3825 Example:
3826
3827 def __hash__(self):
3828 return hash((self.name, self.nick, self.color))
3829
3830 Note:
3831
3832 "hash()" truncates the value returned from an object’s custom
3833 "__hash__()" method to the size of a "Py_ssize_t". This is
3834 typically 8 bytes on 64-bit builds and 4 bytes on 32-bit builds.
3835 If an object’s "__hash__()" must interoperate on builds of
3836 different bit sizes, be sure to check the width on all supported
3837 builds. An easy way to do this is with "python -c "import sys;
3838 print(sys.hash_info.width)"".
3839
3840 If a class does not define an "__eq__()" method it should not
3841 define a "__hash__()" operation either; if it defines "__eq__()"
3842 but not "__hash__()", its instances will not be usable as items in
3843 hashable collections. If a class defines mutable objects and
3844 implements an "__eq__()" method, it should not implement
3845 "__hash__()", since the implementation of *hashable* collections
3846 requires that a key’s hash value is immutable (if the object’s hash
3847 value changes, it will be in the wrong hash bucket).
3848
3849 User-defined classes have "__eq__()" and "__hash__()" methods by
3850 default (inherited from the "object" class); with them, all objects
3851 compare unequal (except with themselves) and "x.__hash__()" returns
3852 an appropriate value such that "x == y" implies both that "x is y"
3853 and "hash(x) == hash(y)".
3854
3855 A class that overrides "__eq__()" and does not define "__hash__()"
3856 will have its "__hash__()" implicitly set to "None". When the
3857 "__hash__()" method of a class is "None", instances of the class
3858 will raise an appropriate "TypeError" when a program attempts to
3859 retrieve their hash value, and will also be correctly identified as
3860 unhashable when checking "isinstance(obj,
3861 collections.abc.Hashable)".
3862
3863 If a class that overrides "__eq__()" needs to retain the
3864 implementation of "__hash__()" from a parent class, the interpreter
3865 must be told this explicitly by setting "__hash__ =
3866 <ParentClass>.__hash__".
3867
3868 If a class that does not override "__eq__()" wishes to suppress
3869 hash support, it should include "__hash__ = None" in the class
3870 definition. A class which defines its own "__hash__()" that
3871 explicitly raises a "TypeError" would be incorrectly identified as
3872 hashable by an "isinstance(obj, collections.abc.Hashable)" call.
3873
3874 Note:
3875
3876 By default, the "__hash__()" values of str and bytes objects are
3877 “salted” with an unpredictable random value. Although they
3878 remain constant within an individual Python process, they are not
3879 predictable between repeated invocations of Python.This is
3880 intended to provide protection against a denial-of-service caused
3881 by carefully chosen inputs that exploit the worst case
3882 performance of a dict insertion, *O*(*n*^2) complexity. See
3883 https://ocert.org/advisories/ocert-2011-003.html for
3884 details.Changing hash values affects the iteration order of sets.
3885 Python has never made guarantees about this ordering (and it
3886 typically varies between 32-bit and 64-bit builds).See also
3887 "PYTHONHASHSEED".
3888
3889 Changed in version 3.3: Hash randomization is enabled by default.
3890
3891 object.__bool__(self)
3892
3893 Called to implement truth value testing and the built-in operation
3894 "bool()"; should return "False" or "True". When this method is not
3895 defined, "__len__()" is called, if it is defined, and the object is
3896 considered true if its result is nonzero. If a class defines
3897 neither "__len__()" nor "__bool__()" (which is true of the "object"
3898 class itself), all its instances are considered true.
3899 ''',
3900 'debugger': r'''"pdb" — The Python Debugger
3901 ***************************
3902
3903 **Source code:** Lib/pdb.py
3904
3905 ======================================================================
3906
3907 The module "pdb" defines an interactive source code debugger for
3908 Python programs. It supports setting (conditional) breakpoints and
3909 single stepping at the source line level, inspection of stack frames,
3910 source code listing, and evaluation of arbitrary Python code in the
3911 context of any stack frame. It also supports post-mortem debugging
3912 and can be called under program control.
3913
3914 The debugger is extensible – it is actually defined as the class
3915 "Pdb". This is currently undocumented but easily understood by reading
3916 the source. The extension interface uses the modules "bdb" and "cmd".
3917
3918 See also:
3919
3920 Module "faulthandler"
3921 Used to dump Python tracebacks explicitly, on a fault, after a
3922 timeout, or on a user signal.
3923
3924 Module "traceback"
3925 Standard interface to extract, format and print stack traces of
3926 Python programs.
3927
3928 The typical usage to break into the debugger is to insert:
3929
3930 import pdb; pdb.set_trace()
3931
3932 Or:
3933
3934 breakpoint()
3935
3936 at the location you want to break into the debugger, and then run the
3937 program. You can then step through the code following this statement,
3938 and continue running without the debugger using the "continue"
3939 command.
3940
3941 Changed in version 3.7: The built-in "breakpoint()", when called with
3942 defaults, can be used instead of "import pdb; pdb.set_trace()".
3943
3944 def double(x):
3945 breakpoint()
3946 return x * 2
3947 val = 3
3948 print(f"{val} * 2 is {double(val)}")
3949
3950 The debugger’s prompt is "(Pdb)", which is the indicator that you are
3951 in debug mode:
3952
3953 > ...(2)double()
3954 -> breakpoint()
3955 (Pdb) p x
3956 3
3957 (Pdb) continue
3958 3 * 2 is 6
3959
3960 Changed in version 3.3: Tab-completion via the "readline" module is
3961 available for commands and command arguments, e.g. the current global
3962 and local names are offered as arguments of the "p" command.
3963
3964
3965 Command-line interface
3966 ======================
3967
3968 You can also invoke "pdb" from the command line to debug other
3969 scripts. For example:
3970
3971 python -m pdb [-c command] (-m module | -p pid | pyfile) [args ...]
3972
3973 When invoked as a module, pdb will automatically enter post-mortem
3974 debugging if the program being debugged exits abnormally. After post-
3975 mortem debugging (or after normal exit of the program), pdb will
3976 restart the program. Automatic restarting preserves pdb’s state (such
3977 as breakpoints) and in most cases is more useful than quitting the
3978 debugger upon program’s exit.
3979
3980 -c, --command <command>
3981
3982 To execute commands as if given in a ".pdbrc" file; see Debugger
3983 commands.
3984
3985 Changed in version 3.2: Added the "-c" option.
3986
3987 -m <module>
3988
3989 To execute modules similar to the way "python -m" does. As with a
3990 script, the debugger will pause execution just before the first
3991 line of the module.
3992
3993 Changed in version 3.7: Added the "-m" option.
3994
3995 -p, --pid <pid>
3996
3997 Attach to the process with the specified PID.
3998
3999 Added in version 3.14.
4000
4001 To attach to a running Python process for remote debugging, use the
4002 "-p" or "--pid" option with the target process’s PID:
4003
4004 python -m pdb -p 1234
4005
4006 Note:
4007
4008 Attaching to a process that is blocked in a system call or waiting
4009 for I/O will only work once the next bytecode instruction is
4010 executed or when the process receives a signal.
4011
4012 Typical usage to execute a statement under control of the debugger is:
4013
4014 >>> import pdb
4015 >>> def f(x):
4016 ... print(1 / x)
4017 >>> pdb.run("f(2)")
4018 > <string>(1)<module>()
4019 (Pdb) continue
4020 0.5
4021 >>>
4022
4023 The typical usage to inspect a crashed program is:
4024
4025 >>> import pdb
4026 >>> def f(x):
4027 ... print(1 / x)
4028 ...
4029 >>> f(0)
4030 Traceback (most recent call last):
4031 File "<stdin>", line 1, in <module>
4032 File "<stdin>", line 2, in f
4033 ZeroDivisionError: division by zero
4034 >>> pdb.pm()
4035 > <stdin>(2)f()
4036 (Pdb) p x
4037 0
4038 (Pdb)
4039
4040 Changed in version 3.13: The implementation of **PEP 667** means that
4041 name assignments made via "pdb" will immediately affect the active
4042 scope, even when running inside an *optimized scope*.
4043
4044 The module defines the following functions; each enters the debugger
4045 in a slightly different way:
4046
4047 pdb.run(statement, globals=None, locals=None)
4048
4049 Execute the *statement* (given as a string or a code object) under
4050 debugger control. The debugger prompt appears before any code is
4051 executed; you can set breakpoints and type "continue", or you can
4052 step through the statement using "step" or "next" (all these
4053 commands are explained below). The optional *globals* and *locals*
4054 arguments specify the environment in which the code is executed; by
4055 default the dictionary of the module "__main__" is used. (See the
4056 explanation of the built-in "exec()" or "eval()" functions.)
4057
4058 pdb.runeval(expression, globals=None, locals=None)
4059
4060 Evaluate the *expression* (given as a string or a code object)
4061 under debugger control. When "runeval()" returns, it returns the
4062 value of the *expression*. Otherwise this function is similar to
4063 "run()".
4064
4065 pdb.runcall(function, *args, **kwds)
4066
4067 Call the *function* (a function or method object, not a string)
4068 with the given arguments. When "runcall()" returns, it returns
4069 whatever the function call returned. The debugger prompt appears
4070 as soon as the function is entered.
4071
4072 pdb.set_trace(*, header=None, commands=None)
4073
4074 Enter the debugger at the calling stack frame. This is useful to
4075 hard-code a breakpoint at a given point in a program, even if the
4076 code is not otherwise being debugged (e.g. when an assertion
4077 fails). If given, *header* is printed to the console just before
4078 debugging begins. The *commands* argument, if given, is a list of
4079 commands to execute when the debugger starts.
4080
4081 Changed in version 3.7: The keyword-only argument *header*.
4082
4083 Changed in version 3.13: "set_trace()" will enter the debugger
4084 immediately, rather than on the next line of code to be executed.
4085
4086 Added in version 3.14: The *commands* argument.
4087
4088 awaitable pdb.set_trace_async(*, header=None, commands=None)
4089
4090 async version of "set_trace()". This function should be used inside
4091 an async function with "await".
4092
4093 async def f():
4094 await pdb.set_trace_async()
4095
4096 "await" statements are supported if the debugger is invoked by this
4097 function.
4098
4099 Added in version 3.14.
4100
4101 pdb.post_mortem(t=None)
4102
4103 Enter post-mortem debugging of the given exception or traceback
4104 object. If no value is given, it uses the exception that is
4105 currently being handled, or raises "ValueError" if there isn’t one.
4106
4107 Changed in version 3.13: Support for exception objects was added.
4108
4109 pdb.pm()
4110
4111 Enter post-mortem debugging of the exception found in
4112 "sys.last_exc".
4113
4114 pdb.set_default_backend(backend)
4115
4116 There are two supported backends for pdb: "'settrace'" and
4117 "'monitoring'". See "bdb.Bdb" for details. The user can set the
4118 default backend to use if none is specified when instantiating
4119 "Pdb". If no backend is specified, the default is "'settrace'".
4120
4121 Note:
4122
4123 "breakpoint()" and "set_trace()" will not be affected by this
4124 function. They always use "'monitoring'" backend.
4125
4126 Added in version 3.14.
4127
4128 pdb.get_default_backend()
4129
4130 Returns the default backend for pdb.
4131
4132 Added in version 3.14.
4133
4134 The "run*" functions and "set_trace()" are aliases for instantiating
4135 the "Pdb" class and calling the method of the same name. If you want
4136 to access further features, you have to do this yourself:
4137
4138 class pdb.Pdb(completekey='tab', stdin=None, stdout=None, skip=None, nosigint=False, readrc=True, mode=None, backend=None, colorize=False)
4139
4140 "Pdb" is the debugger class.
4141
4142 The *completekey*, *stdin* and *stdout* arguments are passed to the
4143 underlying "cmd.Cmd" class; see the description there.
4144
4145 The *skip* argument, if given, must be an iterable of glob-style
4146 module name patterns. The debugger will not step into frames that
4147 originate in a module that matches one of these patterns. [1]
4148
4149 By default, Pdb sets a handler for the SIGINT signal (which is sent
4150 when the user presses "Ctrl"-"C" on the console) when you give a
4151 "continue" command. This allows you to break into the debugger
4152 again by pressing "Ctrl"-"C". If you want Pdb not to touch the
4153 SIGINT handler, set *nosigint* to true.
4154
4155 The *readrc* argument defaults to true and controls whether Pdb
4156 will load .pdbrc files from the filesystem.
4157
4158 The *mode* argument specifies how the debugger was invoked. It
4159 impacts the workings of some debugger commands. Valid values are
4160 "'inline'" (used by the breakpoint() builtin), "'cli'" (used by the
4161 command line invocation) or "None" (for backwards compatible
4162 behaviour, as before the *mode* argument was added).
4163
4164 The *backend* argument specifies the backend to use for the
4165 debugger. If "None" is passed, the default backend will be used.
4166 See "set_default_backend()". Otherwise the supported backends are
4167 "'settrace'" and "'monitoring'".
4168
4169 The *colorize* argument, if set to "True", will enable colorized
4170 output in the debugger, if color is supported. This will highlight
4171 source code displayed in pdb.
4172
4173 Example call to enable tracing with *skip*:
4174
4175 import pdb; pdb.Pdb(skip=['django.*']).set_trace()
4176
4177 Raises an auditing event "pdb.Pdb" with no arguments.
4178
4179 Changed in version 3.1: Added the *skip* parameter.
4180
4181 Changed in version 3.2: Added the *nosigint* parameter. Previously,
4182 a SIGINT handler was never set by Pdb.
4183
4184 Changed in version 3.6: The *readrc* argument.
4185
4186 Added in version 3.14: Added the *mode* argument.
4187
4188 Added in version 3.14: Added the *backend* argument.
4189
4190 Added in version 3.14: Added the *colorize* argument.
4191
4192 Changed in version 3.14: Inline breakpoints like "breakpoint()" or
4193 "pdb.set_trace()" will always stop the program at calling frame,
4194 ignoring the *skip* pattern (if any).
4195
4196 run(statement, globals=None, locals=None)
4197 runeval(expression, globals=None, locals=None)
4198 runcall(function, *args, **kwds)
4199 set_trace()
4200
4201 See the documentation for the functions explained above.
4202
4203
4204 Debugger commands
4205 =================
4206
4207 The commands recognized by the debugger are listed below. Most
4208 commands can be abbreviated to one or two letters as indicated; e.g.
4209 "h(elp)" means that either "h" or "help" can be used to enter the help
4210 command (but not "he" or "hel", nor "H" or "Help" or "HELP").
4211 Arguments to commands must be separated by whitespace (spaces or
4212 tabs). Optional arguments are enclosed in square brackets ("[]") in
4213 the command syntax; the square brackets must not be typed.
4214 Alternatives in the command syntax are separated by a vertical bar
4215 ("|").
4216
4217 Entering a blank line repeats the last command entered. Exception: if
4218 the last command was a "list" command, the next 11 lines are listed.
4219
4220 Commands that the debugger doesn’t recognize are assumed to be Python
4221 statements and are executed in the context of the program being
4222 debugged. Python statements can also be prefixed with an exclamation
4223 point ("!"). This is a powerful way to inspect the program being
4224 debugged; it is even possible to change a variable or call a function.
4225 When an exception occurs in such a statement, the exception name is
4226 printed but the debugger’s state is not changed.
4227
4228 Changed in version 3.13: Expressions/Statements whose prefix is a pdb
4229 command are now correctly identified and executed.
4230
4231 The debugger supports aliases. Aliases can have parameters which
4232 allows one a certain level of adaptability to the context under
4233 examination.
4234
4235 Multiple commands may be entered on a single line, separated by ";;".
4236 (A single ";" is not used as it is the separator for multiple commands
4237 in a line that is passed to the Python parser.) No intelligence is
4238 applied to separating the commands; the input is split at the first
4239 ";;" pair, even if it is in the middle of a quoted string. A
4240 workaround for strings with double semicolons is to use implicit
4241 string concatenation "';'';'" or "";"";"".
4242
4243 To set a temporary global variable, use a *convenience variable*. A
4244 *convenience variable* is a variable whose name starts with "$". For
4245 example, "$foo = 1" sets a global variable "$foo" which you can use in
4246 the debugger session. The *convenience variables* are cleared when
4247 the program resumes execution so it’s less likely to interfere with
4248 your program compared to using normal variables like "foo = 1".
4249
4250 There are four preset *convenience variables*:
4251
4252 * "$_frame": the current frame you are debugging
4253
4254 * "$_retval": the return value if the frame is returning
4255
4256 * "$_exception": the exception if the frame is raising an exception
4257
4258 * "$_asynctask": the asyncio task if pdb stops in an async function
4259
4260 Added in version 3.12: Added the *convenience variable* feature.
4261
4262 Added in version 3.14: Added the "$_asynctask" convenience variable.
4263
4264 If a file ".pdbrc" exists in the user’s home directory or in the
4265 current directory, it is read with "'utf-8'" encoding and executed as
4266 if it had been typed at the debugger prompt, with the exception that
4267 empty lines and lines starting with "#" are ignored. This is
4268 particularly useful for aliases. If both files exist, the one in the
4269 home directory is read first and aliases defined there can be
4270 overridden by the local file.
4271
4272 Changed in version 3.2: ".pdbrc" can now contain commands that
4273 continue debugging, such as "continue" or "next". Previously, these
4274 commands had no effect.
4275
4276 Changed in version 3.11: ".pdbrc" is now read with "'utf-8'" encoding.
4277 Previously, it was read with the system locale encoding.
4278
4279 h(elp) [command]
4280
4281 Without argument, print the list of available commands. With a
4282 *command* as argument, print help about that command. "help pdb"
4283 displays the full documentation (the docstring of the "pdb"
4284 module). Since the *command* argument must be an identifier, "help
4285 exec" must be entered to get help on the "!" command.
4286
4287 w(here) [count]
4288
4289 Print a stack trace, with the most recent frame at the bottom. if
4290 *count* is 0, print the current frame entry. If *count* is
4291 negative, print the least recent - *count* frames. If *count* is
4292 positive, print the most recent *count* frames. An arrow (">")
4293 indicates the current frame, which determines the context of most
4294 commands.
4295
4296 Changed in version 3.14: *count* argument is added.
4297
4298 d(own) [count]
4299
4300 Move the current frame *count* (default one) levels down in the
4301 stack trace (to a newer frame).
4302
4303 u(p) [count]
4304
4305 Move the current frame *count* (default one) levels up in the stack
4306 trace (to an older frame).
4307
4308 b(reak) [([filename:]lineno | function) [, condition]]
4309
4310 With a *lineno* argument, set a break at line *lineno* in the
4311 current file. The line number may be prefixed with a *filename* and
4312 a colon, to specify a breakpoint in another file (possibly one that
4313 hasn’t been loaded yet). The file is searched on "sys.path".
4314 Acceptable forms of *filename* are "/abspath/to/file.py",
4315 "relpath/file.py", "module" and "package.module".
4316
4317 With a *function* argument, set a break at the first executable
4318 statement within that function. *function* can be any expression
4319 that evaluates to a function in the current namespace.
4320
4321 If a second argument is present, it is an expression which must
4322 evaluate to true before the breakpoint is honored.
4323
4324 Without argument, list all breaks, including for each breakpoint,
4325 the number of times that breakpoint has been hit, the current
4326 ignore count, and the associated condition if any.
4327
4328 Each breakpoint is assigned a number to which all the other
4329 breakpoint commands refer.
4330
4331 tbreak [([filename:]lineno | function) [, condition]]
4332
4333 Temporary breakpoint, which is removed automatically when it is
4334 first hit. The arguments are the same as for "break".
4335
4336 cl(ear) [filename:lineno | bpnumber ...]
4337
4338 With a *filename:lineno* argument, clear all the breakpoints at
4339 this line. With a space separated list of breakpoint numbers, clear
4340 those breakpoints. Without argument, clear all breaks (but first
4341 ask confirmation).
4342
4343 disable bpnumber [bpnumber ...]
4344
4345 Disable the breakpoints given as a space separated list of
4346 breakpoint numbers. Disabling a breakpoint means it cannot cause
4347 the program to stop execution, but unlike clearing a breakpoint, it
4348 remains in the list of breakpoints and can be (re-)enabled.
4349
4350 enable bpnumber [bpnumber ...]
4351
4352 Enable the breakpoints specified.
4353
4354 ignore bpnumber [count]
4355
4356 Set the ignore count for the given breakpoint number. If *count*
4357 is omitted, the ignore count is set to 0. A breakpoint becomes
4358 active when the ignore count is zero. When non-zero, the *count*
4359 is decremented each time the breakpoint is reached and the
4360 breakpoint is not disabled and any associated condition evaluates
4361 to true.
4362
4363 condition bpnumber [condition]
4364
4365 Set a new *condition* for the breakpoint, an expression which must
4366 evaluate to true before the breakpoint is honored. If *condition*
4367 is absent, any existing condition is removed; i.e., the breakpoint
4368 is made unconditional.
4369
4370 commands [bpnumber]
4371
4372 Specify a list of commands for breakpoint number *bpnumber*. The
4373 commands themselves appear on the following lines. Type a line
4374 containing just "end" to terminate the commands. An example:
4375
4376 (Pdb) commands 1
4377 (com) p some_variable
4378 (com) end
4379 (Pdb)
4380
4381 To remove all commands from a breakpoint, type "commands" and
4382 follow it immediately with "end"; that is, give no commands.
4383
4384 With no *bpnumber* argument, "commands" refers to the last
4385 breakpoint set.
4386
4387 You can use breakpoint commands to start your program up again.
4388 Simply use the "continue" command, or "step", or any other command
4389 that resumes execution.
4390
4391 Specifying any command resuming execution (currently "continue",
4392 "step", "next", "return", "until", "jump", "quit" and their
4393 abbreviations) terminates the command list (as if that command was
4394 immediately followed by end). This is because any time you resume
4395 execution (even with a simple next or step), you may encounter
4396 another breakpoint—which could have its own command list, leading
4397 to ambiguities about which list to execute.
4398
4399 If the list of commands contains the "silent" command, or a command
4400 that resumes execution, then the breakpoint message containing
4401 information about the frame is not displayed.
4402
4403 Changed in version 3.14: Frame information will not be displayed if
4404 a command that resumes execution is present in the command list.
4405
4406 s(tep)
4407
4408 Execute the current line, stop at the first possible occasion
4409 (either in a function that is called or on the next line in the
4410 current function).
4411
4412 n(ext)
4413
4414 Continue execution until the next line in the current function is
4415 reached or it returns. (The difference between "next" and "step"
4416 is that "step" stops inside a called function, while "next"
4417 executes called functions at (nearly) full speed, only stopping at
4418 the next line in the current function.)
4419
4420 unt(il) [lineno]
4421
4422 Without argument, continue execution until the line with a number
4423 greater than the current one is reached.
4424
4425 With *lineno*, continue execution until a line with a number
4426 greater or equal to *lineno* is reached. In both cases, also stop
4427 when the current frame returns.
4428
4429 Changed in version 3.2: Allow giving an explicit line number.
4430
4431 r(eturn)
4432
4433 Continue execution until the current function returns.
4434
4435 c(ont(inue))
4436
4437 Continue execution, only stop when a breakpoint is encountered.
4438
4439 j(ump) lineno
4440
4441 Set the next line that will be executed. Only available in the
4442 bottom-most frame. This lets you jump back and execute code again,
4443 or jump forward to skip code that you don’t want to run.
4444
4445 It should be noted that not all jumps are allowed – for instance it
4446 is not possible to jump into the middle of a "for" loop or out of a
4447 "finally" clause.
4448
4449 l(ist) [first[, last]]
4450
4451 List source code for the current file. Without arguments, list 11
4452 lines around the current line or continue the previous listing.
4453 With "." as argument, list 11 lines around the current line. With
4454 one argument, list 11 lines around at that line. With two
4455 arguments, list the given range; if the second argument is less
4456 than the first, it is interpreted as a count.
4457
4458 The current line in the current frame is indicated by "->". If an
4459 exception is being debugged, the line where the exception was
4460 originally raised or propagated is indicated by ">>", if it differs
4461 from the current line.
4462
4463 Changed in version 3.2: Added the ">>" marker.
4464
4465 ll | longlist
4466
4467 List all source code for the current function or frame.
4468 Interesting lines are marked as for "list".
4469
4470 Added in version 3.2.
4471
4472 a(rgs)
4473
4474 Print the arguments of the current function and their current
4475 values.
4476
4477 p expression
4478
4479 Evaluate *expression* in the current context and print its value.
4480
4481 Note:
4482
4483 "print()" can also be used, but is not a debugger command — this
4484 executes the Python "print()" function.
4485
4486 pp expression
4487
4488 Like the "p" command, except the value of *expression* is pretty-
4489 printed using the "pprint" module.
4490
4491 whatis expression
4492
4493 Print the type of *expression*.
4494
4495 source expression
4496
4497 Try to get source code of *expression* and display it.
4498
4499 Added in version 3.2.
4500
4501 display [expression]
4502
4503 Display the value of *expression* if it changed, each time
4504 execution stops in the current frame.
4505
4506 Without *expression*, list all display expressions for the current
4507 frame.
4508
4509 Note:
4510
4511 Display evaluates *expression* and compares to the result of the
4512 previous evaluation of *expression*, so when the result is
4513 mutable, display may not be able to pick up the changes.
4514
4515 Example:
4516
4517 lst = []
4518 breakpoint()
4519 pass
4520 lst.append(1)
4521 print(lst)
4522
4523 Display won’t realize "lst" has been changed because the result of
4524 evaluation is modified in place by "lst.append(1)" before being
4525 compared:
4526
4527 > example.py(3)<module>()
4528 -> pass
4529 (Pdb) display lst
4530 display lst: []
4531 (Pdb) n
4532 > example.py(4)<module>()
4533 -> lst.append(1)
4534 (Pdb) n
4535 > example.py(5)<module>()
4536 -> print(lst)
4537 (Pdb)
4538
4539 You can do some tricks with copy mechanism to make it work:
4540
4541 > example.py(3)<module>()
4542 -> pass
4543 (Pdb) display lst[:]
4544 display lst[:]: []
4545 (Pdb) n
4546 > example.py(4)<module>()
4547 -> lst.append(1)
4548 (Pdb) n
4549 > example.py(5)<module>()
4550 -> print(lst)
4551 display lst[:]: [1] [old: []]
4552 (Pdb)
4553
4554 Added in version 3.2.
4555
4556 undisplay [expression]
4557
4558 Do not display *expression* anymore in the current frame. Without
4559 *expression*, clear all display expressions for the current frame.
4560
4561 Added in version 3.2.
4562
4563 interact
4564
4565 Start an interactive interpreter (using the "code" module) in a new
4566 global namespace initialised from the local and global namespaces
4567 for the current scope. Use "exit()" or "quit()" to exit the
4568 interpreter and return to the debugger.
4569
4570 Note:
4571
4572 As "interact" creates a new dedicated namespace for code
4573 execution, assignments to variables will not affect the original
4574 namespaces. However, modifications to any referenced mutable
4575 objects will be reflected in the original namespaces as usual.
4576
4577 Added in version 3.2.
4578
4579 Changed in version 3.13: "exit()" and "quit()" can be used to exit
4580 the "interact" command.
4581
4582 Changed in version 3.13: "interact" directs its output to the
4583 debugger’s output channel rather than "sys.stderr".
4584
4585 alias [name [command]]
4586
4587 Create an alias called *name* that executes *command*. The
4588 *command* must *not* be enclosed in quotes. Replaceable parameters
4589 can be indicated by "%1", "%2", … and "%9", while "%*" is replaced
4590 by all the parameters. If *command* is omitted, the current alias
4591 for *name* is shown. If no arguments are given, all aliases are
4592 listed.
4593
4594 Aliases may be nested and can contain anything that can be legally
4595 typed at the pdb prompt. Note that internal pdb commands *can* be
4596 overridden by aliases. Such a command is then hidden until the
4597 alias is removed. Aliasing is recursively applied to the first
4598 word of the command line; all other words in the line are left
4599 alone.
4600
4601 As an example, here are two useful aliases (especially when placed
4602 in the ".pdbrc" file):
4603
4604 # Print instance variables (usage "pi classInst")
4605 alias pi for k in %1.__dict__.keys(): print(f"%1.{k} = {%1.__dict__[k]}")
4606 # Print instance variables in self
4607 alias ps pi self
4608
4609 unalias name
4610
4611 Delete the specified alias *name*.
4612
4613 ! statement
4614
4615 Execute the (one-line) *statement* in the context of the current
4616 stack frame. The exclamation point can be omitted unless the first
4617 word of the statement resembles a debugger command, e.g.:
4618
4619 (Pdb) ! n=42
4620 (Pdb)
4621
4622 To set a global variable, you can prefix the assignment command
4623 with a "global" statement on the same line, e.g.:
4624
4625 (Pdb) global list_options; list_options = ['-l']
4626 (Pdb)
4627
4628 run [args ...]
4629 restart [args ...]
4630
4631 Restart the debugged Python program. If *args* is supplied, it is
4632 split with "shlex" and the result is used as the new "sys.argv".
4633 History, breakpoints, actions and debugger options are preserved.
4634 "restart" is an alias for "run".
4635
4636 Changed in version 3.14: "run" and "restart" commands are disabled
4637 when the debugger is invoked in "'inline'" mode.
4638
4639 q(uit)
4640
4641 Quit from the debugger. The program being executed is aborted. An
4642 end-of-file input is equivalent to "quit".
4643
4644 A confirmation prompt will be shown if the debugger is invoked in
4645 "'inline'" mode. Either "y", "Y", "<Enter>" or "EOF" will confirm
4646 the quit.
4647
4648 Changed in version 3.14: A confirmation prompt will be shown if the
4649 debugger is invoked in "'inline'" mode. After the confirmation, the
4650 debugger will call "sys.exit()" immediately, instead of raising
4651 "bdb.BdbQuit" in the next trace event.
4652
4653 debug code
4654
4655 Enter a recursive debugger that steps through *code* (which is an
4656 arbitrary expression or statement to be executed in the current
4657 environment).
4658
4659 retval
4660
4661 Print the return value for the last return of the current function.
4662
4663 exceptions [excnumber]
4664
4665 List or jump between chained exceptions.
4666
4667 When using "pdb.pm()" or "Pdb.post_mortem(...)" with a chained
4668 exception instead of a traceback, it allows the user to move
4669 between the chained exceptions using "exceptions" command to list
4670 exceptions, and "exceptions <number>" to switch to that exception.
4671
4672 Example:
4673
4674 def out():
4675 try:
4676 middle()
4677 except Exception as e:
4678 raise ValueError("reraise middle() error") from e
4679
4680 def middle():
4681 try:
4682 return inner(0)
4683 except Exception as e:
4684 raise ValueError("Middle fail")
4685
4686 def inner(x):
4687 1 / x
4688
4689 out()
4690
4691 calling "pdb.pm()" will allow to move between exceptions:
4692
4693 > example.py(5)out()
4694 -> raise ValueError("reraise middle() error") from e
4695
4696 (Pdb) exceptions
4697 0 ZeroDivisionError('division by zero')
4698 1 ValueError('Middle fail')
4699 > 2 ValueError('reraise middle() error')
4700
4701 (Pdb) exceptions 0
4702 > example.py(16)inner()
4703 -> 1 / x
4704
4705 (Pdb) up
4706 > example.py(10)middle()
4707 -> return inner(0)
4708
4709 Added in version 3.13.
4710
4711 -[ Footnotes ]-
4712
4713 [1] Whether a frame is considered to originate in a certain module is
4714 determined by the "__name__" in the frame globals.
4715 ''',
4716 'del': r'''The "del" statement
4717 *******************
4718
4719 del_stmt: "del" target_list
4720
4721 Deletion is recursively defined very similar to the way assignment is
4722 defined. Rather than spelling it out in full details, here are some
4723 hints.
4724
4725 Deletion of a target list recursively deletes each target, from left
4726 to right.
4727
4728 Deletion of a name removes the binding of that name from the local or
4729 global namespace, depending on whether the name occurs in a "global"
4730 statement in the same code block. Trying to delete an unbound name
4731 raises a "NameError" exception.
4732
4733 Deletion of attribute references and subscriptions is passed to the
4734 primary object involved; deletion of a slicing is in general
4735 equivalent to assignment of an empty slice of the right type (but even
4736 this is determined by the sliced object).
4737
4738 Changed in version 3.2: Previously it was illegal to delete a name
4739 from the local namespace if it occurs as a free variable in a nested
4740 block.
4741 ''',
4742 'dict': r'''Dictionary displays
4743 *******************
4744
4745 A dictionary display is a possibly empty series of dict items
4746 (key/value pairs) enclosed in curly braces:
4747
4748 dict_display: "{" [dict_item_list | dict_comprehension] "}"
4749 dict_item_list: dict_item ("," dict_item)* [","]
4750 dict_item: expression ":" expression | "**" or_expr
4751 dict_comprehension: expression ":" expression comp_for
4752
4753 A dictionary display yields a new dictionary object.
4754
4755 If a comma-separated sequence of dict items is given, they are
4756 evaluated from left to right to define the entries of the dictionary:
4757 each key object is used as a key into the dictionary to store the
4758 corresponding value. This means that you can specify the same key
4759 multiple times in the dict item list, and the final dictionary’s value
4760 for that key will be the last one given.
4761
4762 A double asterisk "**" denotes *dictionary unpacking*. Its operand
4763 must be a *mapping*. Each mapping item is added to the new
4764 dictionary. Later values replace values already set by earlier dict
4765 items and earlier dictionary unpackings.
4766
4767 Added in version 3.5: Unpacking into dictionary displays, originally
4768 proposed by **PEP 448**.
4769
4770 A dict comprehension, in contrast to list and set comprehensions,
4771 needs two expressions separated with a colon followed by the usual
4772 “for” and “if” clauses. When the comprehension is run, the resulting
4773 key and value elements are inserted in the new dictionary in the order
4774 they are produced.
4775
4776 Restrictions on the types of the key values are listed earlier in
4777 section The standard type hierarchy. (To summarize, the key type
4778 should be *hashable*, which excludes all mutable objects.) Clashes
4779 between duplicate keys are not detected; the last value (textually
4780 rightmost in the display) stored for a given key value prevails.
4781
4782 Changed in version 3.8: Prior to Python 3.8, in dict comprehensions,
4783 the evaluation order of key and value was not well-defined. In
4784 CPython, the value was evaluated before the key. Starting with 3.8,
4785 the key is evaluated before the value, as proposed by **PEP 572**.
4786 ''',
4787 'dynamic-features': r'''Interaction with dynamic features
4788 *********************************
4789
4790 Name resolution of free variables occurs at runtime, not at compile
4791 time. This means that the following code will print 42:
4792
4793 i = 10
4794 def f():
4795 print(i)
4796 i = 42
4797 f()
4798
4799 The "eval()" and "exec()" functions do not have access to the full
4800 environment for resolving names. Names may be resolved in the local
4801 and global namespaces of the caller. Free variables are not resolved
4802 in the nearest enclosing namespace, but in the global namespace. [1]
4803 The "exec()" and "eval()" functions have optional arguments to
4804 override the global and local namespace. If only one namespace is
4805 specified, it is used for both.
4806 ''',
4807 'else': r'''The "if" statement
4808 ******************
4809
4810 The "if" statement is used for conditional execution:
4811
4812 if_stmt: "if" assignment_expression ":" suite
4813 ("elif" assignment_expression ":" suite)*
4814 ["else" ":" suite]
4815
4816 It selects exactly one of the suites by evaluating the expressions one
4817 by one until one is found to be true (see section Boolean operations
4818 for the definition of true and false); then that suite is executed
4819 (and no other part of the "if" statement is executed or evaluated).
4820 If all expressions are false, the suite of the "else" clause, if
4821 present, is executed.
4822 ''',
4823 'exceptions': r'''Exceptions
4824 **********
4825
4826 Exceptions are a means of breaking out of the normal flow of control
4827 of a code block in order to handle errors or other exceptional
4828 conditions. An exception is *raised* at the point where the error is
4829 detected; it may be *handled* by the surrounding code block or by any
4830 code block that directly or indirectly invoked the code block where
4831 the error occurred.
4832
4833 The Python interpreter raises an exception when it detects a run-time
4834 error (such as division by zero). A Python program can also
4835 explicitly raise an exception with the "raise" statement. Exception
4836 handlers are specified with the "try" … "except" statement. The
4837 "finally" clause of such a statement can be used to specify cleanup
4838 code which does not handle the exception, but is executed whether an
4839 exception occurred or not in the preceding code.
4840
4841 Python uses the “termination” model of error handling: an exception
4842 handler can find out what happened and continue execution at an outer
4843 level, but it cannot repair the cause of the error and retry the
4844 failing operation (except by re-entering the offending piece of code
4845 from the top).
4846
4847 When an exception is not handled at all, the interpreter terminates
4848 execution of the program, or returns to its interactive main loop. In
4849 either case, it prints a stack traceback, except when the exception is
4850 "SystemExit".
4851
4852 Exceptions are identified by class instances. The "except" clause is
4853 selected depending on the class of the instance: it must reference the
4854 class of the instance or a *non-virtual base class* thereof. The
4855 instance can be received by the handler and can carry additional
4856 information about the exceptional condition.
4857
4858 Note:
4859
4860 Exception messages are not part of the Python API. Their contents
4861 may change from one version of Python to the next without warning
4862 and should not be relied on by code which will run under multiple
4863 versions of the interpreter.
4864
4865 See also the description of the "try" statement in section The try
4866 statement and "raise" statement in section The raise statement.
4867 ''',
4868 'execmodel': r'''Execution model
4869 ***************
4870
4871
4872 Structure of a program
4873 ======================
4874
4875 A Python program is constructed from code blocks. A *block* is a piece
4876 of Python program text that is executed as a unit. The following are
4877 blocks: a module, a function body, and a class definition. Each
4878 command typed interactively is a block. A script file (a file given
4879 as standard input to the interpreter or specified as a command line
4880 argument to the interpreter) is a code block. A script command (a
4881 command specified on the interpreter command line with the "-c"
4882 option) is a code block. A module run as a top level script (as module
4883 "__main__") from the command line using a "-m" argument is also a code
4884 block. The string argument passed to the built-in functions "eval()"
4885 and "exec()" is a code block.
4886
4887 A code block is executed in an *execution frame*. A frame contains
4888 some administrative information (used for debugging) and determines
4889 where and how execution continues after the code block’s execution has
4890 completed.
4891
4892
4893 Naming and binding
4894 ==================
4895
4896
4897 Binding of names
4898 ----------------
4899
4900 *Names* refer to objects. Names are introduced by name binding
4901 operations.
4902
4903 The following constructs bind names:
4904
4905 * formal parameters to functions,
4906
4907 * class definitions,
4908
4909 * function definitions,
4910
4911 * assignment expressions,
4912
4913 * targets that are identifiers if occurring in an assignment:
4914
4915 * "for" loop header,
4916
4917 * after "as" in a "with" statement, "except" clause, "except*"
4918 clause, or in the as-pattern in structural pattern matching,
4919
4920 * in a capture pattern in structural pattern matching
4921
4922 * "import" statements.
4923
4924 * "type" statements.
4925
4926 * type parameter lists.
4927
4928 The "import" statement of the form "from ... import *" binds all names
4929 defined in the imported module, except those beginning with an
4930 underscore. This form may only be used at the module level.
4931
4932 A target occurring in a "del" statement is also considered bound for
4933 this purpose (though the actual semantics are to unbind the name).
4934
4935 Each assignment or import statement occurs within a block defined by a
4936 class or function definition or at the module level (the top-level
4937 code block).
4938
4939 If a name is bound in a block, it is a local variable of that block,
4940 unless declared as "nonlocal" or "global". If a name is bound at the
4941 module level, it is a global variable. (The variables of the module
4942 code block are local and global.) If a variable is used in a code
4943 block but not defined there, it is a *free variable*.
4944
4945 Each occurrence of a name in the program text refers to the *binding*
4946 of that name established by the following name resolution rules.
4947
4948
4949 Resolution of names
4950 -------------------
4951
4952 A *scope* defines the visibility of a name within a block. If a local
4953 variable is defined in a block, its scope includes that block. If the
4954 definition occurs in a function block, the scope extends to any blocks
4955 contained within the defining one, unless a contained block introduces
4956 a different binding for the name.
4957
4958 When a name is used in a code block, it is resolved using the nearest
4959 enclosing scope. The set of all such scopes visible to a code block
4960 is called the block’s *environment*.
4961
4962 When a name is not found at all, a "NameError" exception is raised. If
4963 the current scope is a function scope, and the name refers to a local
4964 variable that has not yet been bound to a value at the point where the
4965 name is used, an "UnboundLocalError" exception is raised.
4966 "UnboundLocalError" is a subclass of "NameError".
4967
4968 If a name binding operation occurs anywhere within a code block, all
4969 uses of the name within the block are treated as references to the
4970 current block. This can lead to errors when a name is used within a
4971 block before it is bound. This rule is subtle. Python lacks
4972 declarations and allows name binding operations to occur anywhere
4973 within a code block. The local variables of a code block can be
4974 determined by scanning the entire text of the block for name binding
4975 operations. See the FAQ entry on UnboundLocalError for examples.
4976
4977 If the "global" statement occurs within a block, all uses of the names
4978 specified in the statement refer to the bindings of those names in the
4979 top-level namespace. Names are resolved in the top-level namespace by
4980 searching the global namespace, i.e. the namespace of the module
4981 containing the code block, and the builtins namespace, the namespace
4982 of the module "builtins". The global namespace is searched first. If
4983 the names are not found there, the builtins namespace is searched
4984 next. If the names are also not found in the builtins namespace, new
4985 variables are created in the global namespace. The global statement
4986 must precede all uses of the listed names.
4987
4988 The "global" statement has the same scope as a name binding operation
4989 in the same block. If the nearest enclosing scope for a free variable
4990 contains a global statement, the free variable is treated as a global.
4991
4992 The "nonlocal" statement causes corresponding names to refer to
4993 previously bound variables in the nearest enclosing function scope.
4994 "SyntaxError" is raised at compile time if the given name does not
4995 exist in any enclosing function scope. Type parameters cannot be
4996 rebound with the "nonlocal" statement.
4997
4998 The namespace for a module is automatically created the first time a
4999 module is imported. The main module for a script is always called
5000 "__main__".
5001
5002 Class definition blocks and arguments to "exec()" and "eval()" are
5003 special in the context of name resolution. A class definition is an
5004 executable statement that may use and define names. These references
5005 follow the normal rules for name resolution with an exception that
5006 unbound local variables are looked up in the global namespace. The
5007 namespace of the class definition becomes the attribute dictionary of
5008 the class. The scope of names defined in a class block is limited to
5009 the class block; it does not extend to the code blocks of methods.
5010 This includes comprehensions and generator expressions, but it does
5011 not include annotation scopes, which have access to their enclosing
5012 class scopes. This means that the following will fail:
5013
5014 class A:
5015 a = 42
5016 b = list(a + i for i in range(10))
5017
5018 However, the following will succeed:
5019
5020 class A:
5021 type Alias = Nested
5022 class Nested: pass
5023
5024 print(A.Alias.__value__) # <type 'A.Nested'>
5025
5026
5027 Annotation scopes
5028 -----------------
5029
5030 *Annotations*, type parameter lists and "type" statements introduce
5031 *annotation scopes*, which behave mostly like function scopes, but
5032 with some exceptions discussed below.
5033
5034 Annotation scopes are used in the following contexts:
5035
5036 * *Function annotations*.
5037
5038 * *Variable annotations*.
5039
5040 * Type parameter lists for generic type aliases.
5041
5042 * Type parameter lists for generic functions. A generic function’s
5043 annotations are executed within the annotation scope, but its
5044 defaults and decorators are not.
5045
5046 * Type parameter lists for generic classes. A generic class’s base
5047 classes and keyword arguments are executed within the annotation
5048 scope, but its decorators are not.
5049
5050 * The bounds, constraints, and default values for type parameters
5051 (lazily evaluated).
5052
5053 * The value of type aliases (lazily evaluated).
5054
5055 Annotation scopes differ from function scopes in the following ways:
5056
5057 * Annotation scopes have access to their enclosing class namespace. If
5058 an annotation scope is immediately within a class scope, or within
5059 another annotation scope that is immediately within a class scope,
5060 the code in the annotation scope can use names defined in the class
5061 scope as if it were executed directly within the class body. This
5062 contrasts with regular functions defined within classes, which
5063 cannot access names defined in the class scope.
5064
5065 * Expressions in annotation scopes cannot contain "yield", "yield
5066 from", "await", or ":=" expressions. (These expressions are allowed
5067 in other scopes contained within the annotation scope.)
5068
5069 * Names defined in annotation scopes cannot be rebound with "nonlocal"
5070 statements in inner scopes. This includes only type parameters, as
5071 no other syntactic elements that can appear within annotation scopes
5072 can introduce new names.
5073
5074 * While annotation scopes have an internal name, that name is not
5075 reflected in the *qualified name* of objects defined within the
5076 scope. Instead, the "__qualname__" of such objects is as if the
5077 object were defined in the enclosing scope.
5078
5079 Added in version 3.12: Annotation scopes were introduced in Python
5080 3.12 as part of **PEP 695**.
5081
5082 Changed in version 3.13: Annotation scopes are also used for type
5083 parameter defaults, as introduced by **PEP 696**.
5084
5085 Changed in version 3.14: Annotation scopes are now also used for
5086 annotations, as specified in **PEP 649** and **PEP 749**.
5087
5088
5089 Lazy evaluation
5090 ---------------
5091
5092 Most annotation scopes are *lazily evaluated*. This includes
5093 annotations, the values of type aliases created through the "type"
5094 statement, and the bounds, constraints, and default values of type
5095 variables created through the type parameter syntax. This means that
5096 they are not evaluated when the type alias or type variable is
5097 created, or when the object carrying annotations is created. Instead,
5098 they are only evaluated when necessary, for example when the
5099 "__value__" attribute on a type alias is accessed.
5100
5101 Example:
5102
5103 >>> type Alias = 1/0
5104 >>> Alias.__value__
5105 Traceback (most recent call last):
5106 ...
5107 ZeroDivisionError: division by zero
5108 >>> def func[T: 1/0](): pass
5109 >>> T = func.__type_params__[0]
5110 >>> T.__bound__
5111 Traceback (most recent call last):
5112 ...
5113 ZeroDivisionError: division by zero
5114
5115 Here the exception is raised only when the "__value__" attribute of
5116 the type alias or the "__bound__" attribute of the type variable is
5117 accessed.
5118
5119 This behavior is primarily useful for references to types that have
5120 not yet been defined when the type alias or type variable is created.
5121 For example, lazy evaluation enables creation of mutually recursive
5122 type aliases:
5123
5124 from typing import Literal
5125
5126 type SimpleExpr = int | Parenthesized
5127 type Parenthesized = tuple[Literal["("], Expr, Literal[")"]]
5128 type Expr = SimpleExpr | tuple[SimpleExpr, Literal["+", "-"], Expr]
5129
5130 Lazily evaluated values are evaluated in annotation scope, which means
5131 that names that appear inside the lazily evaluated value are looked up
5132 as if they were used in the immediately enclosing scope.
5133
5134 Added in version 3.12.
5135
5136
5137 Builtins and restricted execution
5138 ---------------------------------
5139
5140 **CPython implementation detail:** Users should not touch
5141 "__builtins__"; it is strictly an implementation detail. Users
5142 wanting to override values in the builtins namespace should "import"
5143 the "builtins" module and modify its attributes appropriately.
5144
5145 The builtins namespace associated with the execution of a code block
5146 is actually found by looking up the name "__builtins__" in its global
5147 namespace; this should be a dictionary or a module (in the latter case
5148 the module’s dictionary is used). By default, when in the "__main__"
5149 module, "__builtins__" is the built-in module "builtins"; when in any
5150 other module, "__builtins__" is an alias for the dictionary of the
5151 "builtins" module itself.
5152
5153
5154 Interaction with dynamic features
5155 ---------------------------------
5156
5157 Name resolution of free variables occurs at runtime, not at compile
5158 time. This means that the following code will print 42:
5159
5160 i = 10
5161 def f():
5162 print(i)
5163 i = 42
5164 f()
5165
5166 The "eval()" and "exec()" functions do not have access to the full
5167 environment for resolving names. Names may be resolved in the local
5168 and global namespaces of the caller. Free variables are not resolved
5169 in the nearest enclosing namespace, but in the global namespace. [1]
5170 The "exec()" and "eval()" functions have optional arguments to
5171 override the global and local namespace. If only one namespace is
5172 specified, it is used for both.
5173
5174
5175 Exceptions
5176 ==========
5177
5178 Exceptions are a means of breaking out of the normal flow of control
5179 of a code block in order to handle errors or other exceptional
5180 conditions. An exception is *raised* at the point where the error is
5181 detected; it may be *handled* by the surrounding code block or by any
5182 code block that directly or indirectly invoked the code block where
5183 the error occurred.
5184
5185 The Python interpreter raises an exception when it detects a run-time
5186 error (such as division by zero). A Python program can also
5187 explicitly raise an exception with the "raise" statement. Exception
5188 handlers are specified with the "try" … "except" statement. The
5189 "finally" clause of such a statement can be used to specify cleanup
5190 code which does not handle the exception, but is executed whether an
5191 exception occurred or not in the preceding code.
5192
5193 Python uses the “termination” model of error handling: an exception
5194 handler can find out what happened and continue execution at an outer
5195 level, but it cannot repair the cause of the error and retry the
5196 failing operation (except by re-entering the offending piece of code
5197 from the top).
5198
5199 When an exception is not handled at all, the interpreter terminates
5200 execution of the program, or returns to its interactive main loop. In
5201 either case, it prints a stack traceback, except when the exception is
5202 "SystemExit".
5203
5204 Exceptions are identified by class instances. The "except" clause is
5205 selected depending on the class of the instance: it must reference the
5206 class of the instance or a *non-virtual base class* thereof. The
5207 instance can be received by the handler and can carry additional
5208 information about the exceptional condition.
5209
5210 Note:
5211
5212 Exception messages are not part of the Python API. Their contents
5213 may change from one version of Python to the next without warning
5214 and should not be relied on by code which will run under multiple
5215 versions of the interpreter.
5216
5217 See also the description of the "try" statement in section The try
5218 statement and "raise" statement in section The raise statement.
5219
5220
5221 Runtime Components
5222 ==================
5223
5224
5225 General Computing Model
5226 -----------------------
5227
5228 Python’s execution model does not operate in a vacuum. It runs on a
5229 host machine and through that host’s runtime environment, including
5230 its operating system (OS), if there is one. When a program runs, the
5231 conceptual layers of how it runs on the host look something like this:
5232
5233 **host machine**
5234 **process** (global resources)
5235 **thread** (runs machine code)
5236
5237 Each process represents a program running on the host. Think of each
5238 process itself as the data part of its program. Think of the process’
5239 threads as the execution part of the program. This distinction will
5240 be important to understand the conceptual Python runtime.
5241
5242 The process, as the data part, is the execution context in which the
5243 program runs. It mostly consists of the set of resources assigned to
5244 the program by the host, including memory, signals, file handles,
5245 sockets, and environment variables.
5246
5247 Processes are isolated and independent from one another. (The same is
5248 true for hosts.) The host manages the process’ access to its assigned
5249 resources, in addition to coordinating between processes.
5250
5251 Each thread represents the actual execution of the program’s machine
5252 code, running relative to the resources assigned to the program’s
5253 process. It’s strictly up to the host how and when that execution
5254 takes place.
5255
5256 From the point of view of Python, a program always starts with exactly
5257 one thread. However, the program may grow to run in multiple
5258 simultaneous threads. Not all hosts support multiple threads per
5259 process, but most do. Unlike processes, threads in a process are not
5260 isolated and independent from one another. Specifically, all threads
5261 in a process share all of the process’ resources.
5262
5263 The fundamental point of threads is that each one does *run*
5264 independently, at the same time as the others. That may be only
5265 conceptually at the same time (“concurrently”) or physically (“in
5266 parallel”). Either way, the threads effectively run at a non-
5267 synchronized rate.
5268
5269 Note:
5270
5271 That non-synchronized rate means none of the process’ memory is
5272 guaranteed to stay consistent for the code running in any given
5273 thread. Thus multi-threaded programs must take care to coordinate
5274 access to intentionally shared resources. Likewise, they must take
5275 care to be absolutely diligent about not accessing any *other*
5276 resources in multiple threads; otherwise two threads running at the
5277 same time might accidentally interfere with each other’s use of some
5278 shared data. All this is true for both Python programs and the
5279 Python runtime.The cost of this broad, unstructured requirement is
5280 the tradeoff for the kind of raw concurrency that threads provide.
5281 The alternative to the required discipline generally means dealing
5282 with non-deterministic bugs and data corruption.
5283
5284
5285 Python Runtime Model
5286 --------------------
5287
5288 The same conceptual layers apply to each Python program, with some
5289 extra data layers specific to Python:
5290
5291 **host machine**
5292 **process** (global resources)
5293 Python global runtime (*state*)
5294 Python interpreter (*state*)
5295 **thread** (runs Python bytecode and “C-API”)
5296 Python thread *state*
5297
5298 At the conceptual level: when a Python program starts, it looks
5299 exactly like that diagram, with one of each. The runtime may grow to
5300 include multiple interpreters, and each interpreter may grow to
5301 include multiple thread states.
5302
5303 Note:
5304
5305 A Python implementation won’t necessarily implement the runtime
5306 layers distinctly or even concretely. The only exception is places
5307 where distinct layers are directly specified or exposed to users,
5308 like through the "threading" module.
5309
5310 Note:
5311
5312 The initial interpreter is typically called the “main” interpreter.
5313 Some Python implementations, like CPython, assign special roles to
5314 the main interpreter.Likewise, the host thread where the runtime was
5315 initialized is known as the “main” thread. It may be different from
5316 the process’ initial thread, though they are often the same. In
5317 some cases “main thread” may be even more specific and refer to the
5318 initial thread state. A Python runtime might assign specific
5319 responsibilities to the main thread, such as handling signals.
5320
5321 As a whole, the Python runtime consists of the global runtime state,
5322 interpreters, and thread states. The runtime ensures all that state
5323 stays consistent over its lifetime, particularly when used with
5324 multiple host threads.
5325
5326 The global runtime, at the conceptual level, is just a set of
5327 interpreters. While those interpreters are otherwise isolated and
5328 independent from one another, they may share some data or other
5329 resources. The runtime is responsible for managing these global
5330 resources safely. The actual nature and management of these resources
5331 is implementation-specific. Ultimately, the external utility of the
5332 global runtime is limited to managing interpreters.
5333
5334 In contrast, an “interpreter” is conceptually what we would normally
5335 think of as the (full-featured) “Python runtime”. When machine code
5336 executing in a host thread interacts with the Python runtime, it calls
5337 into Python in the context of a specific interpreter.
5338
5339 Note:
5340
5341 The term “interpreter” here is not the same as the “bytecode
5342 interpreter”, which is what regularly runs in threads, executing
5343 compiled Python code.In an ideal world, “Python runtime” would refer
5344 to what we currently call “interpreter”. However, it’s been called
5345 “interpreter” at least since introduced in 1997 (CPython:a027efa5b).
5346
5347 Each interpreter completely encapsulates all of the non-process-
5348 global, non-thread-specific state needed for the Python runtime to
5349 work. Notably, the interpreter’s state persists between uses. It
5350 includes fundamental data like "sys.modules". The runtime ensures
5351 multiple threads using the same interpreter will safely share it
5352 between them.
5353
5354 A Python implementation may support using multiple interpreters at the
5355 same time in the same process. They are independent and isolated from
5356 one another. For example, each interpreter has its own "sys.modules".
5357
5358 For thread-specific runtime state, each interpreter has a set of
5359 thread states, which it manages, in the same way the global runtime
5360 contains a set of interpreters. It can have thread states for as many
5361 host threads as it needs. It may even have multiple thread states for
5362 the same host thread, though that isn’t as common.
5363
5364 Each thread state, conceptually, has all the thread-specific runtime
5365 data an interpreter needs to operate in one host thread. The thread
5366 state includes the current raised exception and the thread’s Python
5367 call stack. It may include other thread-specific resources.
5368
5369 Note:
5370
5371 The term “Python thread” can sometimes refer to a thread state, but
5372 normally it means a thread created using the "threading" module.
5373
5374 Each thread state, over its lifetime, is always tied to exactly one
5375 interpreter and exactly one host thread. It will only ever be used in
5376 that thread and with that interpreter.
5377
5378 Multiple thread states may be tied to the same host thread, whether
5379 for different interpreters or even the same interpreter. However, for
5380 any given host thread, only one of the thread states tied to it can be
5381 used by the thread at a time.
5382
5383 Thread states are isolated and independent from one another and don’t
5384 share any data, except for possibly sharing an interpreter and objects
5385 or other resources belonging to that interpreter.
5386
5387 Once a program is running, new Python threads can be created using the
5388 "threading" module (on platforms and Python implementations that
5389 support threads). Additional processes can be created using the "os",
5390 "subprocess", and "multiprocessing" modules. Interpreters can be
5391 created and used with the "interpreters" module. Coroutines (async)
5392 can be run using "asyncio" in each interpreter, typically only in a
5393 single thread (often the main thread).
5394
5395 -[ Footnotes ]-
5396
5397 [1] This limitation occurs because the code that is executed by these
5398 operations is not available at the time the module is compiled.
5399 ''',
5400 'exprlists': r'''Expression lists
5401 ****************
5402
5403 starred_expression: "*" or_expr | expression
5404 flexible_expression: assignment_expression | starred_expression
5405 flexible_expression_list: flexible_expression ("," flexible_expression)* [","]
5406 starred_expression_list: starred_expression ("," starred_expression)* [","]
5407 expression_list: expression ("," expression)* [","]
5408 yield_list: expression_list | starred_expression "," [starred_expression_list]
5409
5410 Except when part of a list or set display, an expression list
5411 containing at least one comma yields a tuple. The length of the tuple
5412 is the number of expressions in the list. The expressions are
5413 evaluated from left to right.
5414
5415 An asterisk "*" denotes *iterable unpacking*. Its operand must be an
5416 *iterable*. The iterable is expanded into a sequence of items, which
5417 are included in the new tuple, list, or set, at the site of the
5418 unpacking.
5419
5420 Added in version 3.5: Iterable unpacking in expression lists,
5421 originally proposed by **PEP 448**.
5422
5423 Added in version 3.11: Any item in an expression list may be starred.
5424 See **PEP 646**.
5425
5426 A trailing comma is required only to create a one-item tuple, such as
5427 "1,"; it is optional in all other cases. A single expression without a
5428 trailing comma doesn’t create a tuple, but rather yields the value of
5429 that expression. (To create an empty tuple, use an empty pair of
5430 parentheses: "()".)
5431 ''',
5432 'floating': r'''Floating-point literals
5433 ***********************
5434
5435 Floating-point (float) literals, such as "3.14" or "1.5", denote
5436 approximations of real numbers.
5437
5438 They consist of *integer* and *fraction* parts, each composed of
5439 decimal digits. The parts are separated by a decimal point, ".":
5440
5441 2.71828
5442 4.0
5443
5444 Unlike in integer literals, leading zeros are allowed. For example,
5445 "077.010" is legal, and denotes the same number as "77.01".
5446
5447 As in integer literals, single underscores may occur between digits to
5448 help readability:
5449
5450 96_485.332_123
5451 3.14_15_93
5452
5453 Either of these parts, but not both, can be empty. For example:
5454
5455 10. # (equivalent to 10.0)
5456 .001 # (equivalent to 0.001)
5457
5458 Optionally, the integer and fraction may be followed by an *exponent*:
5459 the letter "e" or "E", followed by an optional sign, "+" or "-", and a
5460 number in the same format as the integer and fraction parts. The "e"
5461 or "E" represents “times ten raised to the power of”:
5462
5463 1.0e3 # (represents 1.0×10³, or 1000.0)
5464 1.166e-5 # (represents 1.166×10⁻⁵, or 0.00001166)
5465 6.02214076e+23 # (represents 6.02214076×10²³, or 602214076000000000000000.)
5466
5467 In floats with only integer and exponent parts, the decimal point may
5468 be omitted:
5469
5470 1e3 # (equivalent to 1.e3 and 1.0e3)
5471 0e0 # (equivalent to 0.)
5472
5473 Formally, floating-point literals are described by the following
5474 lexical definitions:
5475
5476 floatnumber:
5477 | digitpart "." [digitpart] [exponent]
5478 | "." digitpart [exponent]
5479 | digitpart exponent
5480 digitpart: digit (["_"] digit)*
5481 exponent: ("e" | "E") ["+" | "-"] digitpart
5482
5483 Changed in version 3.6: Underscores are now allowed for grouping
5484 purposes in literals.
5485 ''',
5486 'for': r'''The "for" statement
5487 *******************
5488
5489 The "for" statement is used to iterate over the elements of a sequence
5490 (such as a string, tuple or list) or other iterable object:
5491
5492 for_stmt: "for" target_list "in" starred_expression_list ":" suite
5493 ["else" ":" suite]
5494
5495 The "starred_expression_list" expression is evaluated once; it should
5496 yield an *iterable* object. An *iterator* is created for that
5497 iterable. The first item provided by the iterator is then assigned to
5498 the target list using the standard rules for assignments (see
5499 Assignment statements), and the suite is executed. This repeats for
5500 each item provided by the iterator. When the iterator is exhausted,
5501 the suite in the "else" clause, if present, is executed, and the loop
5502 terminates.
5503
5504 A "break" statement executed in the first suite terminates the loop
5505 without executing the "else" clause’s suite. A "continue" statement
5506 executed in the first suite skips the rest of the suite and continues
5507 with the next item, or with the "else" clause if there is no next
5508 item.
5509
5510 The for-loop makes assignments to the variables in the target list.
5511 This overwrites all previous assignments to those variables including
5512 those made in the suite of the for-loop:
5513
5514 for i in range(10):
5515 print(i)
5516 i = 5 # this will not affect the for-loop
5517 # because i will be overwritten with the next
5518 # index in the range
5519
5520 Names in the target list are not deleted when the loop is finished,
5521 but if the sequence is empty, they will not have been assigned to at
5522 all by the loop. Hint: the built-in type "range()" represents
5523 immutable arithmetic sequences of integers. For instance, iterating
5524 "range(3)" successively yields 0, 1, and then 2.
5525
5526 Changed in version 3.11: Starred elements are now allowed in the
5527 expression list.
5528 ''',
5529 'formatstrings': r'''Format string syntax
5530 ********************
5531
5532 The "str.format()" method and the "Formatter" class share the same
5533 syntax for format strings (although in the case of "Formatter",
5534 subclasses can define their own format string syntax). The syntax is
5535 related to that of formatted string literals and template string
5536 literals, but it is less sophisticated and, in particular, does not
5537 support arbitrary expressions in interpolations.
5538
5539 Format strings contain “replacement fields” surrounded by curly braces
5540 "{}". Anything that is not contained in braces is considered literal
5541 text, which is copied unchanged to the output. If you need to include
5542 a brace character in the literal text, it can be escaped by doubling:
5543 "{{" and "}}".
5544
5545 The grammar for a replacement field is as follows:
5546
5547 replacement_field: "{" [field_name] ["!" conversion] [":" format_spec] "}"
5548 field_name: arg_name ("." attribute_name | "[" element_index "]")*
5549 arg_name: [identifier | digit+]
5550 attribute_name: identifier
5551 element_index: digit+ | index_string
5552 index_string: <any source character except "]"> +
5553 conversion: "r" | "s" | "a"
5554 format_spec: format-spec:format_spec
5555
5556 In less formal terms, the replacement field can start with a
5557 *field_name* that specifies the object whose value is to be formatted
5558 and inserted into the output instead of the replacement field. The
5559 *field_name* is optionally followed by a *conversion* field, which is
5560 preceded by an exclamation point "'!'", and a *format_spec*, which is
5561 preceded by a colon "':'". These specify a non-default format for the
5562 replacement value.
5563
5564 See also the Format specification mini-language section.
5565
5566 The *field_name* itself begins with an *arg_name* that is either a
5567 number or a keyword. If it’s a number, it refers to a positional
5568 argument, and if it’s a keyword, it refers to a named keyword
5569 argument. An *arg_name* is treated as a number if a call to
5570 "str.isdecimal()" on the string would return true. If the numerical
5571 arg_names in a format string are 0, 1, 2, … in sequence, they can all
5572 be omitted (not just some) and the numbers 0, 1, 2, … will be
5573 automatically inserted in that order. Because *arg_name* is not quote-
5574 delimited, it is not possible to specify arbitrary dictionary keys
5575 (e.g., the strings "'10'" or "':-]'") within a format string. The
5576 *arg_name* can be followed by any number of index or attribute
5577 expressions. An expression of the form "'.name'" selects the named
5578 attribute using "getattr()", while an expression of the form
5579 "'[index]'" does an index lookup using "__getitem__()".
5580
5581 Changed in version 3.1: The positional argument specifiers can be
5582 omitted for "str.format()", so "'{} {}'.format(a, b)" is equivalent to
5583 "'{0} {1}'.format(a, b)".
5584
5585 Changed in version 3.4: The positional argument specifiers can be
5586 omitted for "Formatter".
5587
5588 Some simple format string examples:
5589
5590 "First, thou shalt count to {0}" # References first positional argument
5591 "Bring me a {}" # Implicitly references the first positional argument
5592 "From {} to {}" # Same as "From {0} to {1}"
5593 "My quest is {name}" # References keyword argument 'name'
5594 "Weight in tons {0.weight}" # 'weight' attribute of first positional arg
5595 "Units destroyed: {players[0]}" # First element of keyword argument 'players'.
5596
5597 The *conversion* field causes a type coercion before formatting.
5598 Normally, the job of formatting a value is done by the "__format__()"
5599 method of the value itself. However, in some cases it is desirable to
5600 force a type to be formatted as a string, overriding its own
5601 definition of formatting. By converting the value to a string before
5602 calling "__format__()", the normal formatting logic is bypassed.
5603
5604 Three conversion flags are currently supported: "'!s'" which calls
5605 "str()" on the value, "'!r'" which calls "repr()" and "'!a'" which
5606 calls "ascii()".
5607
5608 Some examples:
5609
5610 "Harold's a clever {0!s}" # Calls str() on the argument first
5611 "Bring out the holy {name!r}" # Calls repr() on the argument first
5612 "More {!a}" # Calls ascii() on the argument first
5613
5614 The *format_spec* field contains a specification of how the value
5615 should be presented, including such details as field width, alignment,
5616 padding, decimal precision and so on. Each value type can define its
5617 own “formatting mini-language” or interpretation of the *format_spec*.
5618
5619 Most built-in types support a common formatting mini-language, which
5620 is described in the next section.
5621
5622 A *format_spec* field can also include nested replacement fields
5623 within it. These nested replacement fields may contain a field name,
5624 conversion flag and format specification, but deeper nesting is not
5625 allowed. The replacement fields within the format_spec are
5626 substituted before the *format_spec* string is interpreted. This
5627 allows the formatting of a value to be dynamically specified.
5628
5629 See the Format examples section for some examples.
5630
5631
5632 Format specification mini-language
5633 ==================================
5634
5635 “Format specifications” are used within replacement fields contained
5636 within a format string to define how individual values are presented
5637 (see Format string syntax, f-strings, and t-strings). They can also be
5638 passed directly to the built-in "format()" function. Each formattable
5639 type may define how the format specification is to be interpreted.
5640
5641 Most built-in types implement the following options for format
5642 specifications, although some of the formatting options are only
5643 supported by the numeric types.
5644
5645 A general convention is that an empty format specification produces
5646 the same result as if you had called "str()" on the value. A non-empty
5647 format specification typically modifies the result.
5648
5649 The general form of a *standard format specifier* is:
5650
5651 format_spec: [options][width_and_precision][type]
5652 options: [[fill]align][sign]["z"]["#"]["0"]
5653 fill: <any character>
5654 align: "<" | ">" | "=" | "^"
5655 sign: "+" | "-" | " "
5656 width_and_precision: [width_with_grouping][precision_with_grouping]
5657 width_with_grouping: [width][grouping]
5658 precision_with_grouping: "." [precision][grouping] | "." grouping
5659 width: digit+
5660 precision: digit+
5661 grouping: "," | "_"
5662 type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g"
5663 | "G" | "n" | "o" | "s" | "x" | "X" | "%"
5664
5665 If a valid *align* value is specified, it can be preceded by a *fill*
5666 character that can be any character and defaults to a space if
5667 omitted. It is not possible to use a literal curly brace (”"{"” or
5668 “"}"”) as the *fill* character in a formatted string literal or when
5669 using the "str.format()" method. However, it is possible to insert a
5670 curly brace with a nested replacement field. This limitation doesn’t
5671 affect the "format()" function.
5672
5673 The meaning of the various alignment options is as follows:
5674
5675 +-----------+------------------------------------------------------------+
5676 | Option | Meaning |
5677 |===========|============================================================|
5678 | "'<'" | Forces the field to be left-aligned within the available |
5679 | | space (this is the default for most objects). |
5680 +-----------+------------------------------------------------------------+
5681 | "'>'" | Forces the field to be right-aligned within the available |
5682 | | space (this is the default for numbers). |
5683 +-----------+------------------------------------------------------------+
5684 | "'='" | Forces the padding to be placed after the sign (if any) |
5685 | | but before the digits. This is used for printing fields |
5686 | | in the form ‘+000000120’. This alignment option is only |
5687 | | valid for numeric types, excluding "complex". It becomes |
5688 | | the default for numbers when ‘0’ immediately precedes the |
5689 | | field width. |
5690 +-----------+------------------------------------------------------------+
5691 | "'^'" | Forces the field to be centered within the available |
5692 | | space. |
5693 +-----------+------------------------------------------------------------+
5694
5695 Note that unless a minimum field width is defined, the field width
5696 will always be the same size as the data to fill it, so that the
5697 alignment option has no meaning in this case.
5698
5699 The *sign* option is only valid for number types, and can be one of
5700 the following:
5701
5702 +-----------+------------------------------------------------------------+
5703 | Option | Meaning |
5704 |===========|============================================================|
5705 | "'+'" | Indicates that a sign should be used for both positive as |
5706 | | well as negative numbers. |
5707 +-----------+------------------------------------------------------------+
5708 | "'-'" | Indicates that a sign should be used only for negative |
5709 | | numbers (this is the default behavior). |
5710 +-----------+------------------------------------------------------------+
5711 | space | Indicates that a leading space should be used on positive |
5712 | | numbers, and a minus sign on negative numbers. |
5713 +-----------+------------------------------------------------------------+
5714
5715 The "'z'" option coerces negative zero floating-point values to
5716 positive zero after rounding to the format precision. This option is
5717 only valid for floating-point presentation types.
5718
5719 Changed in version 3.11: Added the "'z'" option (see also **PEP
5720 682**).
5721
5722 The "'#'" option causes the “alternate form” to be used for the
5723 conversion. The alternate form is defined differently for different
5724 types. This option is only valid for integer, float and complex
5725 types. For integers, when binary, octal, or hexadecimal output is
5726 used, this option adds the respective prefix "'0b'", "'0o'", "'0x'",
5727 or "'0X'" to the output value. For float and complex the alternate
5728 form causes the result of the conversion to always contain a decimal-
5729 point character, even if no digits follow it. Normally, a decimal-
5730 point character appears in the result of these conversions only if a
5731 digit follows it. In addition, for "'g'" and "'G'" conversions,
5732 trailing zeros are not removed from the result.
5733
5734 The *width* is a decimal integer defining the minimum total field
5735 width, including any prefixes, separators, and other formatting
5736 characters. If not specified, then the field width will be determined
5737 by the content.
5738
5739 When no explicit alignment is given, preceding the *width* field by a
5740 zero ("'0'") character enables sign-aware zero-padding for numeric
5741 types, excluding "complex". This is equivalent to a *fill* character
5742 of "'0'" with an *alignment* type of "'='".
5743
5744 Changed in version 3.10: Preceding the *width* field by "'0'" no
5745 longer affects the default alignment for strings.
5746
5747 The *precision* is a decimal integer indicating how many digits should
5748 be displayed after the decimal point for presentation types "'f'" and
5749 "'F'", or before and after the decimal point for presentation types
5750 "'g'" or "'G'". For string presentation types the field indicates the
5751 maximum field size - in other words, how many characters will be used
5752 from the field content. The *precision* is not allowed for integer
5753 presentation types.
5754
5755 The *grouping* option after *width* and *precision* fields specifies a
5756 digit group separator for the integral and fractional parts of a
5757 number respectively. It can be one of the following:
5758
5759 +-----------+------------------------------------------------------------+
5760 | Option | Meaning |
5761 |===========|============================================================|
5762 | "','" | Inserts a comma every 3 digits for integer presentation |
5763 | | type "'d'" and floating-point presentation types, |
5764 | | excluding "'n'". For other presentation types, this option |
5765 | | is not supported. |
5766 +-----------+------------------------------------------------------------+
5767 | "'_'" | Inserts an underscore every 3 digits for integer |
5768 | | presentation type "'d'" and floating-point presentation |
5769 | | types, excluding "'n'". For integer presentation types |
5770 | | "'b'", "'o'", "'x'", and "'X'", underscores are inserted |
5771 | | every 4 digits. For other presentation types, this option |
5772 | | is not supported. |
5773 +-----------+------------------------------------------------------------+
5774
5775 For a locale aware separator, use the "'n'" presentation type instead.
5776
5777 Changed in version 3.1: Added the "','" option (see also **PEP 378**).
5778
5779 Changed in version 3.6: Added the "'_'" option (see also **PEP 515**).
5780
5781 Changed in version 3.14: Support the *grouping* option for the
5782 fractional part.
5783
5784 Finally, the *type* determines how the data should be presented.
5785
5786 The available string presentation types are:
5787
5788 +-----------+------------------------------------------------------------+
5789 | Type | Meaning |
5790 |===========|============================================================|
5791 | "'s'" | String format. This is the default type for strings and |
5792 | | may be omitted. |
5793 +-----------+------------------------------------------------------------+
5794 | None | The same as "'s'". |
5795 +-----------+------------------------------------------------------------+
5796
5797 The available integer presentation types are:
5798
5799 +-----------+------------------------------------------------------------+
5800 | Type | Meaning |
5801 |===========|============================================================|
5802 | "'b'" | Binary format. Outputs the number in base 2. |
5803 +-----------+------------------------------------------------------------+
5804 | "'c'" | Character. Converts the integer to the corresponding |
5805 | | unicode character before printing. |
5806 +-----------+------------------------------------------------------------+
5807 | "'d'" | Decimal Integer. Outputs the number in base 10. |
5808 +-----------+------------------------------------------------------------+
5809 | "'o'" | Octal format. Outputs the number in base 8. |
5810 +-----------+------------------------------------------------------------+
5811 | "'x'" | Hex format. Outputs the number in base 16, using lower- |
5812 | | case letters for the digits above 9. |
5813 +-----------+------------------------------------------------------------+
5814 | "'X'" | Hex format. Outputs the number in base 16, using upper- |
5815 | | case letters for the digits above 9. In case "'#'" is |
5816 | | specified, the prefix "'0x'" will be upper-cased to "'0X'" |
5817 | | as well. |
5818 +-----------+------------------------------------------------------------+
5819 | "'n'" | Number. This is the same as "'d'", except that it uses the |
5820 | | current locale setting to insert the appropriate digit |
5821 | | group separators. |
5822 +-----------+------------------------------------------------------------+
5823 | None | The same as "'d'". |
5824 +-----------+------------------------------------------------------------+
5825
5826 In addition to the above presentation types, integers can be formatted
5827 with the floating-point presentation types listed below (except "'n'"
5828 and "None"). When doing so, "float()" is used to convert the integer
5829 to a floating-point number before formatting.
5830
5831 The available presentation types for "float" and "Decimal" values are:
5832
5833 +-----------+------------------------------------------------------------+
5834 | Type | Meaning |
5835 |===========|============================================================|
5836 | "'e'" | Scientific notation. For a given precision "p", formats |
5837 | | the number in scientific notation with the letter ‘e’ |
5838 | | separating the coefficient from the exponent. The |
5839 | | coefficient has one digit before and "p" digits after the |
5840 | | decimal point, for a total of "p + 1" significant digits. |
5841 | | With no precision given, uses a precision of "6" digits |
5842 | | after the decimal point for "float", and shows all |
5843 | | coefficient digits for "Decimal". If "p=0", the decimal |
5844 | | point is omitted unless the "#" option is used. For |
5845 | | "float", the exponent always contains at least two digits, |
5846 | | and is zero if the value is zero. |
5847 +-----------+------------------------------------------------------------+
5848 | "'E'" | Scientific notation. Same as "'e'" except it uses an upper |
5849 | | case ‘E’ as the separator character. |
5850 +-----------+------------------------------------------------------------+
5851 | "'f'" | Fixed-point notation. For a given precision "p", formats |
5852 | | the number as a decimal number with exactly "p" digits |
5853 | | following the decimal point. With no precision given, uses |
5854 | | a precision of "6" digits after the decimal point for |
5855 | | "float", and uses a precision large enough to show all |
5856 | | coefficient digits for "Decimal". If "p=0", the decimal |
5857 | | point is omitted unless the "#" option is used. |
5858 +-----------+------------------------------------------------------------+
5859 | "'F'" | Fixed-point notation. Same as "'f'", but converts "nan" to |
5860 | | "NAN" and "inf" to "INF". |
5861 +-----------+------------------------------------------------------------+
5862 | "'g'" | General format. For a given precision "p >= 1", this |
5863 | | rounds the number to "p" significant digits and then |
5864 | | formats the result in either fixed-point format or in |
5865 | | scientific notation, depending on its magnitude. A |
5866 | | precision of "0" is treated as equivalent to a precision |
5867 | | of "1". The precise rules are as follows: suppose that |
5868 | | the result formatted with presentation type "'e'" and |
5869 | | precision "p-1" would have exponent "exp". Then, if "m <= |
5870 | | exp < p", where "m" is -4 for floats and -6 for |
5871 | | "Decimals", the number is formatted with presentation type |
5872 | | "'f'" and precision "p-1-exp". Otherwise, the number is |
5873 | | formatted with presentation type "'e'" and precision |
5874 | | "p-1". In both cases insignificant trailing zeros are |
5875 | | removed from the significand, and the decimal point is |
5876 | | also removed if there are no remaining digits following |
5877 | | it, unless the "'#'" option is used. With no precision |
5878 | | given, uses a precision of "6" significant digits for |
5879 | | "float". For "Decimal", the coefficient of the result is |
5880 | | formed from the coefficient digits of the value; |
5881 | | scientific notation is used for values smaller than "1e-6" |
5882 | | in absolute value and values where the place value of the |
5883 | | least significant digit is larger than 1, and fixed-point |
5884 | | notation is used otherwise. Positive and negative |
5885 | | infinity, positive and negative zero, and nans, are |
5886 | | formatted as "inf", "-inf", "0", "-0" and "nan" |
5887 | | respectively, regardless of the precision. |
5888 +-----------+------------------------------------------------------------+
5889 | "'G'" | General format. Same as "'g'" except switches to "'E'" if |
5890 | | the number gets too large. The representations of infinity |
5891 | | and NaN are uppercased, too. |
5892 +-----------+------------------------------------------------------------+
5893 | "'n'" | Number. This is the same as "'g'", except that it uses the |
5894 | | current locale setting to insert the appropriate digit |
5895 | | group separators for the integral part of a number. |
5896 +-----------+------------------------------------------------------------+
5897 | "'%'" | Percentage. Multiplies the number by 100 and displays in |
5898 | | fixed ("'f'") format, followed by a percent sign. |
5899 +-----------+------------------------------------------------------------+
5900 | None | For "float" this is like the "'g'" type, except that when |
5901 | | fixed- point notation is used to format the result, it |
5902 | | always includes at least one digit past the decimal point, |
5903 | | and switches to the scientific notation when "exp >= p - |
5904 | | 1". When the precision is not specified, the latter will |
5905 | | be as large as needed to represent the given value |
5906 | | faithfully. For "Decimal", this is the same as either |
5907 | | "'g'" or "'G'" depending on the value of |
5908 | | "context.capitals" for the current decimal context. The |
5909 | | overall effect is to match the output of "str()" as |
5910 | | altered by the other format modifiers. |
5911 +-----------+------------------------------------------------------------+
5912
5913 The result should be correctly rounded to a given precision "p" of
5914 digits after the decimal point. The rounding mode for "float" matches
5915 that of the "round()" builtin. For "Decimal", the rounding mode of
5916 the current context will be used.
5917
5918 The available presentation types for "complex" are the same as those
5919 for "float" ("'%'" is not allowed). Both the real and imaginary
5920 components of a complex number are formatted as floating-point
5921 numbers, according to the specified presentation type. They are
5922 separated by the mandatory sign of the imaginary part, the latter
5923 being terminated by a "j" suffix. If the presentation type is
5924 missing, the result will match the output of "str()" (complex numbers
5925 with a non-zero real part are also surrounded by parentheses),
5926 possibly altered by other format modifiers.
5927
5928
5929 Format examples
5930 ===============
5931
5932 This section contains examples of the "str.format()" syntax and
5933 comparison with the old "%"-formatting.
5934
5935 In most of the cases the syntax is similar to the old "%"-formatting,
5936 with the addition of the "{}" and with ":" used instead of "%". For
5937 example, "'%03.2f'" can be translated to "'{:03.2f}'".
5938
5939 The new format syntax also supports new and different options, shown
5940 in the following examples.
5941
5942 Accessing arguments by position:
5943
5944 >>> '{0}, {1}, {2}'.format('a', 'b', 'c')
5945 'a, b, c'
5946 >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only
5947 'a, b, c'
5948 >>> '{2}, {1}, {0}'.format('a', 'b', 'c')
5949 'c, b, a'
5950 >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence
5951 'c, b, a'
5952 >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated
5953 'abracadabra'
5954
5955 Accessing arguments by name:
5956
5957 >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
5958 'Coordinates: 37.24N, -115.81W'
5959 >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
5960 >>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
5961 'Coordinates: 37.24N, -115.81W'
5962
5963 Accessing arguments’ attributes:
5964
5965 >>> c = 3-5j
5966 >>> ('The complex number {0} is formed from the real part {0.real} '
5967 ... 'and the imaginary part {0.imag}.').format(c)
5968 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
5969 >>> class Point:
5970 ... def __init__(self, x, y):
5971 ... self.x, self.y = x, y
5972 ... def __str__(self):
5973 ... return 'Point({self.x}, {self.y})'.format(self=self)
5974 ...
5975 >>> str(Point(4, 2))
5976 'Point(4, 2)'
5977
5978 Accessing arguments’ items:
5979
5980 >>> coord = (3, 5)
5981 >>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
5982 'X: 3; Y: 5'
5983
5984 Replacing "%s" and "%r":
5985
5986 >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
5987 "repr() shows quotes: 'test1'; str() doesn't: test2"
5988
5989 Aligning the text and specifying a width:
5990
5991 >>> '{:<30}'.format('left aligned')
5992 'left aligned '
5993 >>> '{:>30}'.format('right aligned')
5994 ' right aligned'
5995 >>> '{:^30}'.format('centered')
5996 ' centered '
5997 >>> '{:*^30}'.format('centered') # use '*' as a fill char
5998 '***********centered***********'
5999
6000 Replacing "%+f", "%-f", and "% f" and specifying a sign:
6001
6002 >>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it always
6003 '+3.140000; -3.140000'
6004 >>> '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
6005 ' 3.140000; -3.140000'
6006 >>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}'
6007 '3.140000; -3.140000'
6008
6009 Replacing "%x" and "%o" and converting the value to different bases:
6010
6011 >>> # format also supports binary numbers
6012 >>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
6013 'int: 42; hex: 2a; oct: 52; bin: 101010'
6014 >>> # with 0x, 0o, or 0b as prefix:
6015 >>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
6016 'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
6017
6018 Using the comma or the underscore as a digit group separator:
6019
6020 >>> '{:,}'.format(1234567890)
6021 '1,234,567,890'
6022 >>> '{:_}'.format(1234567890)
6023 '1_234_567_890'
6024 >>> '{:_b}'.format(1234567890)
6025 '100_1001_1001_0110_0000_0010_1101_0010'
6026 >>> '{:_x}'.format(1234567890)
6027 '4996_02d2'
6028 >>> '{:_}'.format(123456789.123456789)
6029 '123_456_789.12345679'
6030 >>> '{:.,}'.format(123456789.123456789)
6031 '123456789.123,456,79'
6032 >>> '{:,._}'.format(123456789.123456789)
6033 '123,456,789.123_456_79'
6034
6035 Expressing a percentage:
6036
6037 >>> points = 19
6038 >>> total = 22
6039 >>> 'Correct answers: {:.2%}'.format(points/total)
6040 'Correct answers: 86.36%'
6041
6042 Using type-specific formatting:
6043
6044 >>> import datetime as dt
6045 >>> d = dt.datetime(2010, 7, 4, 12, 15, 58)
6046 >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
6047 '2010-07-04 12:15:58'
6048
6049 Nesting arguments and more complex examples:
6050
6051 >>> for align, text in zip('<^>', ['left', 'center', 'right']):
6052 ... '{0:{fill}{align}16}'.format(text, fill=align, align=align)
6053 ...
6054 'left<<<<<<<<<<<<'
6055 '^^^^^center^^^^^'
6056 '>>>>>>>>>>>right'
6057 >>>
6058 >>> octets = [192, 168, 0, 1]
6059 >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
6060 'C0A80001'
6061 >>> int(_, 16)
6062 3232235521
6063 >>>
6064 >>> width = 5
6065 >>> for num in range(5,12):
6066 ... for base in 'dXob':
6067 ... print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
6068 ... print()
6069 ...
6070 5 5 5 101
6071 6 6 6 110
6072 7 7 7 111
6073 8 8 10 1000
6074 9 9 11 1001
6075 10 A 12 1010
6076 11 B 13 1011
6077 ''',
6078 'function': r'''Function definitions
6079 ********************
6080
6081 A function definition defines a user-defined function object (see
6082 section The standard type hierarchy):
6083
6084 funcdef: [decorators] "def" funcname [type_params] "(" [parameter_list] ")"
6085 ["->" expression] ":" suite
6086 decorators: decorator+
6087 decorator: "@" assignment_expression NEWLINE
6088 parameter_list: defparameter ("," defparameter)* "," "/" ["," [parameter_list_no_posonly]]
6089 | parameter_list_no_posonly
6090 parameter_list_no_posonly: defparameter ("," defparameter)* ["," [parameter_list_starargs]]
6091 | parameter_list_starargs
6092 parameter_list_starargs: "*" [star_parameter] ("," defparameter)* ["," [parameter_star_kwargs]]
6093 | "*" ("," defparameter)+ ["," [parameter_star_kwargs]]
6094 | parameter_star_kwargs
6095 parameter_star_kwargs: "**" parameter [","]
6096 parameter: identifier [":" expression]
6097 star_parameter: identifier [":" ["*"] expression]
6098 defparameter: parameter ["=" expression]
6099 funcname: identifier
6100
6101 A function definition is an executable statement. Its execution binds
6102 the function name in the current local namespace to a function object
6103 (a wrapper around the executable code for the function). This
6104 function object contains a reference to the current global namespace
6105 as the global namespace to be used when the function is called.
6106
6107 The function definition does not execute the function body; this gets
6108 executed only when the function is called. [4]
6109
6110 A function definition may be wrapped by one or more *decorator*
6111 expressions. Decorator expressions are evaluated when the function is
6112 defined, in the scope that contains the function definition. The
6113 result must be a callable, which is invoked with the function object
6114 as the only argument. The returned value is bound to the function name
6115 instead of the function object. Multiple decorators are applied in
6116 nested fashion. For example, the following code
6117
6118 @f1(arg)
6119 @f2
6120 def func(): pass
6121
6122 is roughly equivalent to
6123
6124 def func(): pass
6125 func = f1(arg)(f2(func))
6126
6127 except that the original function is not temporarily bound to the name
6128 "func".
6129
6130 Changed in version 3.9: Functions may be decorated with any valid
6131 "assignment_expression". Previously, the grammar was much more
6132 restrictive; see **PEP 614** for details.
6133
6134 A list of type parameters may be given in square brackets between the
6135 function’s name and the opening parenthesis for its parameter list.
6136 This indicates to static type checkers that the function is generic.
6137 At runtime, the type parameters can be retrieved from the function’s
6138 "__type_params__" attribute. See Generic functions for more.
6139
6140 Changed in version 3.12: Type parameter lists are new in Python 3.12.
6141
6142 When one or more *parameters* have the form *parameter* "="
6143 *expression*, the function is said to have “default parameter values.”
6144 For a parameter with a default value, the corresponding *argument* may
6145 be omitted from a call, in which case the parameter’s default value is
6146 substituted. If a parameter has a default value, all following
6147 parameters up until the “"*"” must also have a default value — this is
6148 a syntactic restriction that is not expressed by the grammar.
6149
6150 **Default parameter values are evaluated from left to right when the
6151 function definition is executed.** This means that the expression is
6152 evaluated once, when the function is defined, and that the same “pre-
6153 computed” value is used for each call. This is especially important
6154 to understand when a default parameter value is a mutable object, such
6155 as a list or a dictionary: if the function modifies the object (e.g.
6156 by appending an item to a list), the default parameter value is in
6157 effect modified. This is generally not what was intended. A way
6158 around this is to use "None" as the default, and explicitly test for
6159 it in the body of the function, e.g.:
6160
6161 def whats_on_the_telly(penguin=None):
6162 if penguin is None:
6163 penguin = []
6164 penguin.append("property of the zoo")
6165 return penguin
6166
6167 Function call semantics are described in more detail in section Calls.
6168 A function call always assigns values to all parameters mentioned in
6169 the parameter list, either from positional arguments, from keyword
6170 arguments, or from default values. If the form “"*identifier"” is
6171 present, it is initialized to a tuple receiving any excess positional
6172 parameters, defaulting to the empty tuple. If the form
6173 “"**identifier"” is present, it is initialized to a new ordered
6174 mapping receiving any excess keyword arguments, defaulting to a new
6175 empty mapping of the same type. Parameters after “"*"” or
6176 “"*identifier"” are keyword-only parameters and may only be passed by
6177 keyword arguments. Parameters before “"/"” are positional-only
6178 parameters and may only be passed by positional arguments.
6179
6180 Changed in version 3.8: The "/" function parameter syntax may be used
6181 to indicate positional-only parameters. See **PEP 570** for details.
6182
6183 Parameters may have an *annotation* of the form “": expression"”
6184 following the parameter name. Any parameter may have an annotation,
6185 even those of the form "*identifier" or "**identifier". (As a special
6186 case, parameters of the form "*identifier" may have an annotation “":
6187 *expression"”.) Functions may have “return” annotation of the form
6188 “"-> expression"” after the parameter list. These annotations can be
6189 any valid Python expression. The presence of annotations does not
6190 change the semantics of a function. See Annotations for more
6191 information on annotations.
6192
6193 Changed in version 3.11: Parameters of the form “"*identifier"” may
6194 have an annotation “": *expression"”. See **PEP 646**.
6195
6196 It is also possible to create anonymous functions (functions not bound
6197 to a name), for immediate use in expressions. This uses lambda
6198 expressions, described in section Lambdas. Note that the lambda
6199 expression is merely a shorthand for a simplified function definition;
6200 a function defined in a “"def"” statement can be passed around or
6201 assigned to another name just like a function defined by a lambda
6202 expression. The “"def"” form is actually more powerful since it
6203 allows the execution of multiple statements and annotations.
6204
6205 **Programmer’s note:** Functions are first-class objects. A “"def"”
6206 statement executed inside a function definition defines a local
6207 function that can be returned or passed around. Free variables used
6208 in the nested function can access the local variables of the function
6209 containing the def. See section Naming and binding for details.
6210
6211 See also:
6212
6213 **PEP 3107** - Function Annotations
6214 The original specification for function annotations.
6215
6216 **PEP 484** - Type Hints
6217 Definition of a standard meaning for annotations: type hints.
6218
6219 **PEP 526** - Syntax for Variable Annotations
6220 Ability to type hint variable declarations, including class
6221 variables and instance variables.
6222
6223 **PEP 563** - Postponed Evaluation of Annotations
6224 Support for forward references within annotations by preserving
6225 annotations in a string form at runtime instead of eager
6226 evaluation.
6227
6228 **PEP 318** - Decorators for Functions and Methods
6229 Function and method decorators were introduced. Class decorators
6230 were introduced in **PEP 3129**.
6231 ''',
6232 'global': r'''The "global" statement
6233 **********************
6234
6235 global_stmt: "global" identifier ("," identifier)*
6236
6237 The "global" statement causes the listed identifiers to be interpreted
6238 as globals. It would be impossible to assign to a global variable
6239 without "global", although free variables may refer to globals without
6240 being declared global.
6241
6242 The "global" statement applies to the entire current scope (module,
6243 function body or class definition). A "SyntaxError" is raised if a
6244 variable is used or assigned to prior to its global declaration in the
6245 scope.
6246
6247 At the module level, all variables are global, so a "global" statement
6248 has no effect. However, variables must still not be used or assigned
6249 to prior to their "global" declaration. This requirement is relaxed in
6250 the interactive prompt (*REPL*).
6251
6252 **Programmer’s note:** "global" is a directive to the parser. It
6253 applies only to code parsed at the same time as the "global"
6254 statement. In particular, a "global" statement contained in a string
6255 or code object supplied to the built-in "exec()" function does not
6256 affect the code block *containing* the function call, and code
6257 contained in such a string is unaffected by "global" statements in the
6258 code containing the function call. The same applies to the "eval()"
6259 and "compile()" functions.
6260 ''',
6261 'id-classes': r'''Reserved classes of identifiers
6262 *******************************
6263
6264 Certain classes of identifiers (besides keywords) have special
6265 meanings. These classes are identified by the patterns of leading and
6266 trailing underscore characters:
6267
6268 "_*"
6269 Not imported by "from module import *".
6270
6271 "_"
6272 In a "case" pattern within a "match" statement, "_" is a soft
6273 keyword that denotes a wildcard.
6274
6275 Separately, the interactive interpreter makes the result of the
6276 last evaluation available in the variable "_". (It is stored in the
6277 "builtins" module, alongside built-in functions like "print".)
6278
6279 Elsewhere, "_" is a regular identifier. It is often used to name
6280 “special” items, but it is not special to Python itself.
6281
6282 Note:
6283
6284 The name "_" is often used in conjunction with
6285 internationalization; refer to the documentation for the
6286 "gettext" module for more information on this convention.It is
6287 also commonly used for unused variables.
6288
6289 "__*__"
6290 System-defined names, informally known as “dunder” names. These
6291 names are defined by the interpreter and its implementation
6292 (including the standard library). Current system names are
6293 discussed in the Special method names section and elsewhere. More
6294 will likely be defined in future versions of Python. *Any* use of
6295 "__*__" names, in any context, that does not follow explicitly
6296 documented use, is subject to breakage without warning.
6297
6298 "__*"
6299 Class-private names. Names in this category, when used within the
6300 context of a class definition, are re-written to use a mangled form
6301 to help avoid name clashes between “private” attributes of base and
6302 derived classes. See section Identifiers (Names).
6303 ''',
6304 'identifiers': r'''Names (identifiers and keywords)
6305 ********************************
6306
6307 "NAME" tokens represent *identifiers*, *keywords*, and *soft
6308 keywords*.
6309
6310 Names are composed of the following characters:
6311
6312 * uppercase and lowercase letters ("A-Z" and "a-z"),
6313
6314 * the underscore ("_"),
6315
6316 * digits ("0" through "9"), which cannot appear as the first
6317 character, and
6318
6319 * non-ASCII characters. Valid names may only contain “letter-like” and
6320 “digit-like” characters; see Non-ASCII characters in names for
6321 details.
6322
6323 Names must contain at least one character, but have no upper length
6324 limit. Case is significant.
6325
6326 Formally, names are described by the following lexical definitions:
6327
6328 NAME: name_start name_continue*
6329 name_start: "a"..."z" | "A"..."Z" | "_" | <non-ASCII character>
6330 name_continue: name_start | "0"..."9"
6331 identifier: <NAME, except keywords>
6332
6333 Note that not all names matched by this grammar are valid; see Non-
6334 ASCII characters in names for details.
6335
6336
6337 Keywords
6338 ========
6339
6340 The following names are used as reserved words, or *keywords* of the
6341 language, and cannot be used as ordinary identifiers. They must be
6342 spelled exactly as written here:
6343
6344 False await else import pass
6345 None break except in raise
6346 True class finally is return
6347 and continue for lambda try
6348 as def from nonlocal while
6349 assert del global not with
6350 async elif if or yield
6351
6352
6353 Soft Keywords
6354 =============
6355
6356 Added in version 3.10.
6357
6358 Some names are only reserved under specific contexts. These are known
6359 as *soft keywords*:
6360
6361 * "match", "case", and "_", when used in the "match" statement.
6362
6363 * "type", when used in the "type" statement.
6364
6365 These syntactically act as keywords in their specific contexts, but
6366 this distinction is done at the parser level, not when tokenizing.
6367
6368 As soft keywords, their use in the grammar is possible while still
6369 preserving compatibility with existing code that uses these names as
6370 identifier names.
6371
6372 Changed in version 3.12: "type" is now a soft keyword.
6373
6374
6375 Reserved classes of identifiers
6376 ===============================
6377
6378 Certain classes of identifiers (besides keywords) have special
6379 meanings. These classes are identified by the patterns of leading and
6380 trailing underscore characters:
6381
6382 "_*"
6383 Not imported by "from module import *".
6384
6385 "_"
6386 In a "case" pattern within a "match" statement, "_" is a soft
6387 keyword that denotes a wildcard.
6388
6389 Separately, the interactive interpreter makes the result of the
6390 last evaluation available in the variable "_". (It is stored in the
6391 "builtins" module, alongside built-in functions like "print".)
6392
6393 Elsewhere, "_" is a regular identifier. It is often used to name
6394 “special” items, but it is not special to Python itself.
6395
6396 Note:
6397
6398 The name "_" is often used in conjunction with
6399 internationalization; refer to the documentation for the
6400 "gettext" module for more information on this convention.It is
6401 also commonly used for unused variables.
6402
6403 "__*__"
6404 System-defined names, informally known as “dunder” names. These
6405 names are defined by the interpreter and its implementation
6406 (including the standard library). Current system names are
6407 discussed in the Special method names section and elsewhere. More
6408 will likely be defined in future versions of Python. *Any* use of
6409 "__*__" names, in any context, that does not follow explicitly
6410 documented use, is subject to breakage without warning.
6411
6412 "__*"
6413 Class-private names. Names in this category, when used within the
6414 context of a class definition, are re-written to use a mangled form
6415 to help avoid name clashes between “private” attributes of base and
6416 derived classes. See section Identifiers (Names).
6417
6418
6419 Non-ASCII characters in names
6420 =============================
6421
6422 Names that contain non-ASCII characters need additional normalization
6423 and validation beyond the rules and grammar explained above. For
6424 example, "ř_1", "蛇", or "साँप" are valid names, but "r〰2", "€", or
6425 "🐍" are not.
6426
6427 This section explains the exact rules.
6428
6429 All names are converted into the normalization form NFKC while
6430 parsing. This means that, for example, some typographic variants of
6431 characters are converted to their “basic” form. For example,
6432 "fiⁿₐˡᵢᶻₐᵗᵢᵒₙ" normalizes to "finalization", so Python treats them as
6433 the same name:
6434
6435 >>> fiⁿₐˡᵢᶻₐᵗᵢᵒₙ = 3
6436 >>> finalization
6437 3
6438
6439 Note:
6440
6441 Normalization is done at the lexical level only. Run-time functions
6442 that take names as *strings* generally do not normalize their
6443 arguments. For example, the variable defined above is accessible at
6444 run time in the "globals()" dictionary as
6445 "globals()["finalization"]" but not "globals()["fiⁿₐˡᵢᶻₐᵗᵢᵒₙ"]".
6446
6447 Similarly to how ASCII-only names must contain only letters, digits
6448 and the underscore, and cannot start with a digit, a valid name must
6449 start with a character in the “letter-like” set "xid_start", and the
6450 remaining characters must be in the “letter- and digit-like” set
6451 "xid_continue".
6452
6453 These sets are based on the *XID_Start* and *XID_Continue* sets as
6454 defined by the Unicode standard annex UAX-31. Python’s "xid_start"
6455 additionally includes the underscore ("_"). Note that Python does not
6456 necessarily conform to UAX-31.
6457
6458 A non-normative listing of characters in the *XID_Start* and
6459 *XID_Continue* sets as defined by Unicode is available in the
6460 DerivedCoreProperties.txt file in the Unicode Character Database. For
6461 reference, the construction rules for the "xid_*" sets are given
6462 below.
6463
6464 The set "id_start" is defined as the union of:
6465
6466 * Unicode category "<Lu>" - uppercase letters (includes "A" to "Z")
6467
6468 * Unicode category "<Ll>" - lowercase letters (includes "a" to "z")
6469
6470 * Unicode category "<Lt>" - titlecase letters
6471
6472 * Unicode category "<Lm>" - modifier letters
6473
6474 * Unicode category "<Lo>" - other letters
6475
6476 * Unicode category "<Nl>" - letter numbers
6477
6478 * {""_""} - the underscore
6479
6480 * "<Other_ID_Start>" - an explicit set of characters in PropList.txt
6481 to support backwards compatibility
6482
6483 The set "xid_start" then closes this set under NFKC normalization, by
6484 removing all characters whose normalization is not of the form
6485 "id_start id_continue*".
6486
6487 The set "id_continue" is defined as the union of:
6488
6489 * "id_start" (see above)
6490
6491 * Unicode category "<Nd>" - decimal numbers (includes "0" to "9")
6492
6493 * Unicode category "<Pc>" - connector punctuations
6494
6495 * Unicode category "<Mn>" - nonspacing marks
6496
6497 * Unicode category "<Mc>" - spacing combining marks
6498
6499 * "<Other_ID_Continue>" - another explicit set of characters in
6500 PropList.txt to support backwards compatibility
6501
6502 Again, "xid_continue" closes this set under NFKC normalization.
6503
6504 Unicode categories use the version of the Unicode Character Database
6505 as included in the "unicodedata" module.
6506
6507 See also:
6508
6509 * **PEP 3131** – Supporting Non-ASCII Identifiers
6510
6511 * **PEP 672** – Unicode-related Security Considerations for Python
6512 ''',
6513 'if': r'''The "if" statement
6514 ******************
6515
6516 The "if" statement is used for conditional execution:
6517
6518 if_stmt: "if" assignment_expression ":" suite
6519 ("elif" assignment_expression ":" suite)*
6520 ["else" ":" suite]
6521
6522 It selects exactly one of the suites by evaluating the expressions one
6523 by one until one is found to be true (see section Boolean operations
6524 for the definition of true and false); then that suite is executed
6525 (and no other part of the "if" statement is executed or evaluated).
6526 If all expressions are false, the suite of the "else" clause, if
6527 present, is executed.
6528 ''',
6529 'imaginary': r'''Imaginary literals
6530 ******************
6531
6532 Python has complex number objects, but no complex literals. Instead,
6533 *imaginary literals* denote complex numbers with a zero real part.
6534
6535 For example, in math, the complex number 3+4.2*i* is written as the
6536 real number 3 added to the imaginary number 4.2*i*. Python uses a
6537 similar syntax, except the imaginary unit is written as "j" rather
6538 than *i*:
6539
6540 3+4.2j
6541
6542 This is an expression composed of the integer literal "3", the
6543 operator ‘"+"’, and the imaginary literal "4.2j". Since these are
6544 three separate tokens, whitespace is allowed between them:
6545
6546 3 + 4.2j
6547
6548 No whitespace is allowed *within* each token. In particular, the "j"
6549 suffix, may not be separated from the number before it.
6550
6551 The number before the "j" has the same syntax as a floating-point
6552 literal. Thus, the following are valid imaginary literals:
6553
6554 4.2j
6555 3.14j
6556 10.j
6557 .001j
6558 1e100j
6559 3.14e-10j
6560 3.14_15_93j
6561
6562 Unlike in a floating-point literal the decimal point can be omitted if
6563 the imaginary number only has an integer part. The number is still
6564 evaluated as a floating-point number, not an integer:
6565
6566 10j
6567 0j
6568 1000000000000000000000000j # equivalent to 1e+24j
6569
6570 The "j" suffix is case-insensitive. That means you can use "J"
6571 instead:
6572
6573 3.14J # equivalent to 3.14j
6574
6575 Formally, imaginary literals are described by the following lexical
6576 definition:
6577
6578 imagnumber: (floatnumber | digitpart) ("j" | "J")
6579 ''',
6580 'import': r'''The "import" statement
6581 **********************
6582
6583 import_stmt: "import" module ["as" identifier] ("," module ["as" identifier])*
6584 | "from" relative_module "import" identifier ["as" identifier]
6585 ("," identifier ["as" identifier])*
6586 | "from" relative_module "import" "(" identifier ["as" identifier]
6587 ("," identifier ["as" identifier])* [","] ")"
6588 | "from" relative_module "import" "*"
6589 module: (identifier ".")* identifier
6590 relative_module: "."* module | "."+
6591
6592 The basic import statement (no "from" clause) is executed in two
6593 steps:
6594
6595 1. find a module, loading and initializing it if necessary
6596
6597 2. define a name or names in the current namespace for the scope where
6598 the "import" statement occurs, just as an assignment statement
6599 would (including "global" and "nonlocal" semantics).
6600
6601 When the statement contains multiple clauses (separated by commas) the
6602 two steps are carried out separately for each clause, just as though
6603 the clauses had been separated out into individual import statements.
6604
6605 The details of the first step, finding and loading modules, are
6606 described in greater detail in the section on the import system, which
6607 also describes the various types of packages and modules that can be
6608 imported, as well as all the hooks that can be used to customize the
6609 import system. Note that failures in this step may indicate either
6610 that the module could not be located, *or* that an error occurred
6611 while initializing the module, which includes execution of the
6612 module’s code.
6613
6614 If the requested module is retrieved successfully, it will be made
6615 available in the local namespace in one of three ways:
6616
6617 * If the module name is followed by "as", then the name following "as"
6618 is bound directly to the imported module.
6619
6620 * If no other name is specified, and the module being imported is a
6621 top level module, the module’s name is bound in the local namespace
6622 as a reference to the imported module
6623
6624 * If the module being imported is *not* a top level module, then the
6625 name of the top level package that contains the module is bound in
6626 the local namespace as a reference to the top level package. The
6627 imported module must be accessed using its full qualified name
6628 rather than directly
6629
6630 The "from" form uses a slightly more complex process:
6631
6632 1. find the module specified in the "from" clause, loading and
6633 initializing it if necessary;
6634
6635 2. for each of the identifiers specified in the "import" clauses:
6636
6637 1. check if the imported module has an attribute by that name
6638
6639 2. if not, attempt to import a submodule with that name and then
6640 check the imported module again for that attribute
6641
6642 3. if the attribute is not found, "ImportError" is raised.
6643
6644 4. otherwise, a reference to that value is stored in the current
6645 namespace, using the name in the "as" clause if it is present,
6646 otherwise using the attribute name
6647
6648 Examples:
6649
6650 import foo # foo imported and bound locally
6651 import foo.bar.baz # foo, foo.bar, and foo.bar.baz imported, foo bound locally
6652 import foo.bar.baz as fbb # foo, foo.bar, and foo.bar.baz imported, foo.bar.baz bound as fbb
6653 from foo.bar import baz # foo, foo.bar, and foo.bar.baz imported, foo.bar.baz bound as baz
6654 from foo import attr # foo imported and foo.attr bound as attr
6655
6656 If the list of identifiers is replaced by a star ("'*'"), all public
6657 names defined in the module are bound in the local namespace for the
6658 scope where the "import" statement occurs.
6659
6660 The *public names* defined by a module are determined by checking the
6661 module’s namespace for a variable named "__all__"; if defined, it must
6662 be a sequence of strings which are names defined or imported by that
6663 module. Names containing non-ASCII characters must be in the
6664 normalization form NFKC; see Non-ASCII characters in names for
6665 details. The names given in "__all__" are all considered public and
6666 are required to exist. If "__all__" is not defined, the set of public
6667 names includes all names found in the module’s namespace which do not
6668 begin with an underscore character ("'_'"). "__all__" should contain
6669 the entire public API. It is intended to avoid accidentally exporting
6670 items that are not part of the API (such as library modules which were
6671 imported and used within the module).
6672
6673 The wild card form of import — "from module import *" — is only
6674 allowed at the module level. Attempting to use it in class or
6675 function definitions will raise a "SyntaxError".
6676
6677 When specifying what module to import you do not have to specify the
6678 absolute name of the module. When a module or package is contained
6679 within another package it is possible to make a relative import within
6680 the same top package without having to mention the package name. By
6681 using leading dots in the specified module or package after "from" you
6682 can specify how high to traverse up the current package hierarchy
6683 without specifying exact names. One leading dot means the current
6684 package where the module making the import exists. Two dots means up
6685 one package level. Three dots is up two levels, etc. So if you execute
6686 "from . import mod" from a module in the "pkg" package then you will
6687 end up importing "pkg.mod". If you execute "from ..subpkg2 import mod"
6688 from within "pkg.subpkg1" you will import "pkg.subpkg2.mod". The
6689 specification for relative imports is contained in the Package
6690 Relative Imports section.
6691
6692 "importlib.import_module()" is provided to support applications that
6693 determine dynamically the modules to be loaded.
6694
6695 Raises an auditing event "import" with arguments "module", "filename",
6696 "sys.path", "sys.meta_path", "sys.path_hooks".
6697
6698
6699 Future statements
6700 =================
6701
6702 A *future statement* is a directive to the compiler that a particular
6703 module should be compiled using syntax or semantics that will be
6704 available in a specified future release of Python where the feature
6705 becomes standard.
6706
6707 The future statement is intended to ease migration to future versions
6708 of Python that introduce incompatible changes to the language. It
6709 allows use of the new features on a per-module basis before the
6710 release in which the feature becomes standard.
6711
6712 future_stmt: "from" "__future__" "import" feature ["as" identifier]
6713 ("," feature ["as" identifier])*
6714 | "from" "__future__" "import" "(" feature ["as" identifier]
6715 ("," feature ["as" identifier])* [","] ")"
6716 feature: identifier
6717
6718 A future statement must appear near the top of the module. The only
6719 lines that can appear before a future statement are:
6720
6721 * the module docstring (if any),
6722
6723 * comments,
6724
6725 * blank lines, and
6726
6727 * other future statements.
6728
6729 The only feature that requires using the future statement is
6730 "annotations" (see **PEP 563**).
6731
6732 All historical features enabled by the future statement are still
6733 recognized by Python 3. The list includes "absolute_import",
6734 "division", "generators", "generator_stop", "unicode_literals",
6735 "print_function", "nested_scopes" and "with_statement". They are all
6736 redundant because they are always enabled, and only kept for backwards
6737 compatibility.
6738
6739 A future statement is recognized and treated specially at compile
6740 time: Changes to the semantics of core constructs are often
6741 implemented by generating different code. It may even be the case
6742 that a new feature introduces new incompatible syntax (such as a new
6743 reserved word), in which case the compiler may need to parse the
6744 module differently. Such decisions cannot be pushed off until
6745 runtime.
6746
6747 For any given release, the compiler knows which feature names have
6748 been defined, and raises a compile-time error if a future statement
6749 contains a feature not known to it.
6750
6751 The direct runtime semantics are the same as for any import statement:
6752 there is a standard module "__future__", described later, and it will
6753 be imported in the usual way at the time the future statement is
6754 executed.
6755
6756 The interesting runtime semantics depend on the specific feature
6757 enabled by the future statement.
6758
6759 Note that there is nothing special about the statement:
6760
6761 import __future__ [as name]
6762
6763 That is not a future statement; it’s an ordinary import statement with
6764 no special semantics or syntax restrictions.
6765
6766 Code compiled by calls to the built-in functions "exec()" and
6767 "compile()" that occur in a module "M" containing a future statement
6768 will, by default, use the new syntax or semantics associated with the
6769 future statement. This can be controlled by optional arguments to
6770 "compile()" — see the documentation of that function for details.
6771
6772 A future statement typed at an interactive interpreter prompt will
6773 take effect for the rest of the interpreter session. If an
6774 interpreter is started with the "-i" option, is passed a script name
6775 to execute, and the script includes a future statement, it will be in
6776 effect in the interactive session started after the script is
6777 executed.
6778
6779 See also:
6780
6781 **PEP 236** - Back to the __future__
6782 The original proposal for the __future__ mechanism.
6783 ''',
6784 'in': r'''Membership test operations
6785 **************************
6786
6787 The operators "in" and "not in" test for membership. "x in s"
6788 evaluates to "True" if *x* is a member of *s*, and "False" otherwise.
6789 "x not in s" returns the negation of "x in s". All built-in sequences
6790 and set types support this as well as dictionary, for which "in" tests
6791 whether the dictionary has a given key. For container types such as
6792 list, tuple, set, frozenset, dict, or collections.deque, the
6793 expression "x in y" is equivalent to "any(x is e or x == e for e in
6794 y)".
6795
6796 For the string and bytes types, "x in y" is "True" if and only if *x*
6797 is a substring of *y*. An equivalent test is "y.find(x) != -1".
6798 Empty strings are always considered to be a substring of any other
6799 string, so """ in "abc"" will return "True".
6800
6801 For user-defined classes which define the "__contains__()" method, "x
6802 in y" returns "True" if "y.__contains__(x)" returns a true value, and
6803 "False" otherwise.
6804
6805 For user-defined classes which do not define "__contains__()" but do
6806 define "__iter__()", "x in y" is "True" if some value "z", for which
6807 the expression "x is z or x == z" is true, is produced while iterating
6808 over "y". If an exception is raised during the iteration, it is as if
6809 "in" raised that exception.
6810
6811 Lastly, the old-style iteration protocol is tried: if a class defines
6812 "__getitem__()", "x in y" is "True" if and only if there is a non-
6813 negative integer index *i* such that "x is y[i] or x == y[i]", and no
6814 lower integer index raises the "IndexError" exception. (If any other
6815 exception is raised, it is as if "in" raised that exception).
6816
6817 The operator "not in" is defined to have the inverse truth value of
6818 "in".
6819 ''',
6820 'integers': r'''Integer literals
6821 ****************
6822
6823 Integer literals denote whole numbers. For example:
6824
6825 7
6826 3
6827 2147483647
6828
6829 There is no limit for the length of integer literals apart from what
6830 can be stored in available memory:
6831
6832 7922816251426433759354395033679228162514264337593543950336
6833
6834 Underscores can be used to group digits for enhanced readability, and
6835 are ignored for determining the numeric value of the literal. For
6836 example, the following literals are equivalent:
6837
6838 100_000_000_000
6839 100000000000
6840 1_00_00_00_00_000
6841
6842 Underscores can only occur between digits. For example, "_123",
6843 "321_", and "123__321" are *not* valid literals.
6844
6845 Integers can be specified in binary (base 2), octal (base 8), or
6846 hexadecimal (base 16) using the prefixes "0b", "0o" and "0x",
6847 respectively. Hexadecimal digits 10 through 15 are represented by
6848 letters "A"-"F", case-insensitive. For example:
6849
6850 0b100110111
6851 0b_1110_0101
6852 0o177
6853 0o377
6854 0xdeadbeef
6855 0xDead_Beef
6856
6857 An underscore can follow the base specifier. For example, "0x_1f" is a
6858 valid literal, but "0_x1f" and "0x__1f" are not.
6859
6860 Leading zeros in a non-zero decimal number are not allowed. For
6861 example, "0123" is not a valid literal. This is for disambiguation
6862 with C-style octal literals, which Python used before version 3.0.
6863
6864 Formally, integer literals are described by the following lexical
6865 definitions:
6866
6867 integer: decinteger | bininteger | octinteger | hexinteger | zerointeger
6868 decinteger: nonzerodigit (["_"] digit)*
6869 bininteger: "0" ("b" | "B") (["_"] bindigit)+
6870 octinteger: "0" ("o" | "O") (["_"] octdigit)+
6871 hexinteger: "0" ("x" | "X") (["_"] hexdigit)+
6872 zerointeger: "0"+ (["_"] "0")*
6873 nonzerodigit: "1"..."9"
6874 digit: "0"..."9"
6875 bindigit: "0" | "1"
6876 octdigit: "0"..."7"
6877 hexdigit: digit | "a"..."f" | "A"..."F"
6878
6879 Changed in version 3.6: Underscores are now allowed for grouping
6880 purposes in literals.
6881 ''',
6882 'lambda': r'''Lambdas
6883 *******
6884
6885 lambda_expr: "lambda" [parameter_list] ":" expression
6886
6887 Lambda expressions (sometimes called lambda forms) are used to create
6888 anonymous functions. The expression "lambda parameters: expression"
6889 yields a function object. The unnamed object behaves like a function
6890 object defined with:
6891
6892 def <lambda>(parameters):
6893 return expression
6894
6895 See section Function definitions for the syntax of parameter lists.
6896 Note that functions created with lambda expressions cannot contain
6897 statements or annotations.
6898 ''',
6899 'lists': r'''List displays
6900 *************
6901
6902 A list display is a possibly empty series of expressions enclosed in
6903 square brackets:
6904
6905 list_display: "[" [flexible_expression_list | comprehension] "]"
6906
6907 A list display yields a new list object, the contents being specified
6908 by either a list of expressions or a comprehension. When a comma-
6909 separated list of expressions is supplied, its elements are evaluated
6910 from left to right and placed into the list object in that order.
6911 When a comprehension is supplied, the list is constructed from the
6912 elements resulting from the comprehension.
6913 ''',
6914 'naming': r'''Naming and binding
6915 ******************
6916
6917
6918 Binding of names
6919 ================
6920
6921 *Names* refer to objects. Names are introduced by name binding
6922 operations.
6923
6924 The following constructs bind names:
6925
6926 * formal parameters to functions,
6927
6928 * class definitions,
6929
6930 * function definitions,
6931
6932 * assignment expressions,
6933
6934 * targets that are identifiers if occurring in an assignment:
6935
6936 * "for" loop header,
6937
6938 * after "as" in a "with" statement, "except" clause, "except*"
6939 clause, or in the as-pattern in structural pattern matching,
6940
6941 * in a capture pattern in structural pattern matching
6942
6943 * "import" statements.
6944
6945 * "type" statements.
6946
6947 * type parameter lists.
6948
6949 The "import" statement of the form "from ... import *" binds all names
6950 defined in the imported module, except those beginning with an
6951 underscore. This form may only be used at the module level.
6952
6953 A target occurring in a "del" statement is also considered bound for
6954 this purpose (though the actual semantics are to unbind the name).
6955
6956 Each assignment or import statement occurs within a block defined by a
6957 class or function definition or at the module level (the top-level
6958 code block).
6959
6960 If a name is bound in a block, it is a local variable of that block,
6961 unless declared as "nonlocal" or "global". If a name is bound at the
6962 module level, it is a global variable. (The variables of the module
6963 code block are local and global.) If a variable is used in a code
6964 block but not defined there, it is a *free variable*.
6965
6966 Each occurrence of a name in the program text refers to the *binding*
6967 of that name established by the following name resolution rules.
6968
6969
6970 Resolution of names
6971 ===================
6972
6973 A *scope* defines the visibility of a name within a block. If a local
6974 variable is defined in a block, its scope includes that block. If the
6975 definition occurs in a function block, the scope extends to any blocks
6976 contained within the defining one, unless a contained block introduces
6977 a different binding for the name.
6978
6979 When a name is used in a code block, it is resolved using the nearest
6980 enclosing scope. The set of all such scopes visible to a code block
6981 is called the block’s *environment*.
6982
6983 When a name is not found at all, a "NameError" exception is raised. If
6984 the current scope is a function scope, and the name refers to a local
6985 variable that has not yet been bound to a value at the point where the
6986 name is used, an "UnboundLocalError" exception is raised.
6987 "UnboundLocalError" is a subclass of "NameError".
6988
6989 If a name binding operation occurs anywhere within a code block, all
6990 uses of the name within the block are treated as references to the
6991 current block. This can lead to errors when a name is used within a
6992 block before it is bound. This rule is subtle. Python lacks
6993 declarations and allows name binding operations to occur anywhere
6994 within a code block. The local variables of a code block can be
6995 determined by scanning the entire text of the block for name binding
6996 operations. See the FAQ entry on UnboundLocalError for examples.
6997
6998 If the "global" statement occurs within a block, all uses of the names
6999 specified in the statement refer to the bindings of those names in the
7000 top-level namespace. Names are resolved in the top-level namespace by
7001 searching the global namespace, i.e. the namespace of the module
7002 containing the code block, and the builtins namespace, the namespace
7003 of the module "builtins". The global namespace is searched first. If
7004 the names are not found there, the builtins namespace is searched
7005 next. If the names are also not found in the builtins namespace, new
7006 variables are created in the global namespace. The global statement
7007 must precede all uses of the listed names.
7008
7009 The "global" statement has the same scope as a name binding operation
7010 in the same block. If the nearest enclosing scope for a free variable
7011 contains a global statement, the free variable is treated as a global.
7012
7013 The "nonlocal" statement causes corresponding names to refer to
7014 previously bound variables in the nearest enclosing function scope.
7015 "SyntaxError" is raised at compile time if the given name does not
7016 exist in any enclosing function scope. Type parameters cannot be
7017 rebound with the "nonlocal" statement.
7018
7019 The namespace for a module is automatically created the first time a
7020 module is imported. The main module for a script is always called
7021 "__main__".
7022
7023 Class definition blocks and arguments to "exec()" and "eval()" are
7024 special in the context of name resolution. A class definition is an
7025 executable statement that may use and define names. These references
7026 follow the normal rules for name resolution with an exception that
7027 unbound local variables are looked up in the global namespace. The
7028 namespace of the class definition becomes the attribute dictionary of
7029 the class. The scope of names defined in a class block is limited to
7030 the class block; it does not extend to the code blocks of methods.
7031 This includes comprehensions and generator expressions, but it does
7032 not include annotation scopes, which have access to their enclosing
7033 class scopes. This means that the following will fail:
7034
7035 class A:
7036 a = 42
7037 b = list(a + i for i in range(10))
7038
7039 However, the following will succeed:
7040
7041 class A:
7042 type Alias = Nested
7043 class Nested: pass
7044
7045 print(A.Alias.__value__) # <type 'A.Nested'>
7046
7047
7048 Annotation scopes
7049 =================
7050
7051 *Annotations*, type parameter lists and "type" statements introduce
7052 *annotation scopes*, which behave mostly like function scopes, but
7053 with some exceptions discussed below.
7054
7055 Annotation scopes are used in the following contexts:
7056
7057 * *Function annotations*.
7058
7059 * *Variable annotations*.
7060
7061 * Type parameter lists for generic type aliases.
7062
7063 * Type parameter lists for generic functions. A generic function’s
7064 annotations are executed within the annotation scope, but its
7065 defaults and decorators are not.
7066
7067 * Type parameter lists for generic classes. A generic class’s base
7068 classes and keyword arguments are executed within the annotation
7069 scope, but its decorators are not.
7070
7071 * The bounds, constraints, and default values for type parameters
7072 (lazily evaluated).
7073
7074 * The value of type aliases (lazily evaluated).
7075
7076 Annotation scopes differ from function scopes in the following ways:
7077
7078 * Annotation scopes have access to their enclosing class namespace. If
7079 an annotation scope is immediately within a class scope, or within
7080 another annotation scope that is immediately within a class scope,
7081 the code in the annotation scope can use names defined in the class
7082 scope as if it were executed directly within the class body. This
7083 contrasts with regular functions defined within classes, which
7084 cannot access names defined in the class scope.
7085
7086 * Expressions in annotation scopes cannot contain "yield", "yield
7087 from", "await", or ":=" expressions. (These expressions are allowed
7088 in other scopes contained within the annotation scope.)
7089
7090 * Names defined in annotation scopes cannot be rebound with "nonlocal"
7091 statements in inner scopes. This includes only type parameters, as
7092 no other syntactic elements that can appear within annotation scopes
7093 can introduce new names.
7094
7095 * While annotation scopes have an internal name, that name is not
7096 reflected in the *qualified name* of objects defined within the
7097 scope. Instead, the "__qualname__" of such objects is as if the
7098 object were defined in the enclosing scope.
7099
7100 Added in version 3.12: Annotation scopes were introduced in Python
7101 3.12 as part of **PEP 695**.
7102
7103 Changed in version 3.13: Annotation scopes are also used for type
7104 parameter defaults, as introduced by **PEP 696**.
7105
7106 Changed in version 3.14: Annotation scopes are now also used for
7107 annotations, as specified in **PEP 649** and **PEP 749**.
7108
7109
7110 Lazy evaluation
7111 ===============
7112
7113 Most annotation scopes are *lazily evaluated*. This includes
7114 annotations, the values of type aliases created through the "type"
7115 statement, and the bounds, constraints, and default values of type
7116 variables created through the type parameter syntax. This means that
7117 they are not evaluated when the type alias or type variable is
7118 created, or when the object carrying annotations is created. Instead,
7119 they are only evaluated when necessary, for example when the
7120 "__value__" attribute on a type alias is accessed.
7121
7122 Example:
7123
7124 >>> type Alias = 1/0
7125 >>> Alias.__value__
7126 Traceback (most recent call last):
7127 ...
7128 ZeroDivisionError: division by zero
7129 >>> def func[T: 1/0](): pass
7130 >>> T = func.__type_params__[0]
7131 >>> T.__bound__
7132 Traceback (most recent call last):
7133 ...
7134 ZeroDivisionError: division by zero
7135
7136 Here the exception is raised only when the "__value__" attribute of
7137 the type alias or the "__bound__" attribute of the type variable is
7138 accessed.
7139
7140 This behavior is primarily useful for references to types that have
7141 not yet been defined when the type alias or type variable is created.
7142 For example, lazy evaluation enables creation of mutually recursive
7143 type aliases:
7144
7145 from typing import Literal
7146
7147 type SimpleExpr = int | Parenthesized
7148 type Parenthesized = tuple[Literal["("], Expr, Literal[")"]]
7149 type Expr = SimpleExpr | tuple[SimpleExpr, Literal["+", "-"], Expr]
7150
7151 Lazily evaluated values are evaluated in annotation scope, which means
7152 that names that appear inside the lazily evaluated value are looked up
7153 as if they were used in the immediately enclosing scope.
7154
7155 Added in version 3.12.
7156
7157
7158 Builtins and restricted execution
7159 =================================
7160
7161 **CPython implementation detail:** Users should not touch
7162 "__builtins__"; it is strictly an implementation detail. Users
7163 wanting to override values in the builtins namespace should "import"
7164 the "builtins" module and modify its attributes appropriately.
7165
7166 The builtins namespace associated with the execution of a code block
7167 is actually found by looking up the name "__builtins__" in its global
7168 namespace; this should be a dictionary or a module (in the latter case
7169 the module’s dictionary is used). By default, when in the "__main__"
7170 module, "__builtins__" is the built-in module "builtins"; when in any
7171 other module, "__builtins__" is an alias for the dictionary of the
7172 "builtins" module itself.
7173
7174
7175 Interaction with dynamic features
7176 =================================
7177
7178 Name resolution of free variables occurs at runtime, not at compile
7179 time. This means that the following code will print 42:
7180
7181 i = 10
7182 def f():
7183 print(i)
7184 i = 42
7185 f()
7186
7187 The "eval()" and "exec()" functions do not have access to the full
7188 environment for resolving names. Names may be resolved in the local
7189 and global namespaces of the caller. Free variables are not resolved
7190 in the nearest enclosing namespace, but in the global namespace. [1]
7191 The "exec()" and "eval()" functions have optional arguments to
7192 override the global and local namespace. If only one namespace is
7193 specified, it is used for both.
7194 ''',
7195 'nonlocal': r'''The "nonlocal" statement
7196 ************************
7197
7198 nonlocal_stmt: "nonlocal" identifier ("," identifier)*
7199
7200 When the definition of a function or class is nested (enclosed) within
7201 the definitions of other functions, its nonlocal scopes are the local
7202 scopes of the enclosing functions. The "nonlocal" statement causes the
7203 listed identifiers to refer to names previously bound in nonlocal
7204 scopes. It allows encapsulated code to rebind such nonlocal
7205 identifiers. If a name is bound in more than one nonlocal scope, the
7206 nearest binding is used. If a name is not bound in any nonlocal scope,
7207 or if there is no nonlocal scope, a "SyntaxError" is raised.
7208
7209 The "nonlocal" statement applies to the entire scope of a function or
7210 class body. A "SyntaxError" is raised if a variable is used or
7211 assigned to prior to its nonlocal declaration in the scope.
7212
7213 See also:
7214
7215 **PEP 3104** - Access to Names in Outer Scopes
7216 The specification for the "nonlocal" statement.
7217
7218 **Programmer’s note:** "nonlocal" is a directive to the parser and
7219 applies only to code parsed along with it. See the note for the
7220 "global" statement.
7221 ''',
7222 'numbers': r'''Numeric literals
7223 ****************
7224
7225 "NUMBER" tokens represent numeric literals, of which there are three
7226 types: integers, floating-point numbers, and imaginary numbers.
7227
7228 NUMBER: integer | floatnumber | imagnumber
7229
7230 The numeric value of a numeric literal is the same as if it were
7231 passed as a string to the "int", "float" or "complex" class
7232 constructor, respectively. Note that not all valid inputs for those
7233 constructors are also valid literals.
7234
7235 Numeric literals do not include a sign; a phrase like "-1" is actually
7236 an expression composed of the unary operator ‘"-"’ and the literal
7237 "1".
7238
7239
7240 Integer literals
7241 ================
7242
7243 Integer literals denote whole numbers. For example:
7244
7245 7
7246 3
7247 2147483647
7248
7249 There is no limit for the length of integer literals apart from what
7250 can be stored in available memory:
7251
7252 7922816251426433759354395033679228162514264337593543950336
7253
7254 Underscores can be used to group digits for enhanced readability, and
7255 are ignored for determining the numeric value of the literal. For
7256 example, the following literals are equivalent:
7257
7258 100_000_000_000
7259 100000000000
7260 1_00_00_00_00_000
7261
7262 Underscores can only occur between digits. For example, "_123",
7263 "321_", and "123__321" are *not* valid literals.
7264
7265 Integers can be specified in binary (base 2), octal (base 8), or
7266 hexadecimal (base 16) using the prefixes "0b", "0o" and "0x",
7267 respectively. Hexadecimal digits 10 through 15 are represented by
7268 letters "A"-"F", case-insensitive. For example:
7269
7270 0b100110111
7271 0b_1110_0101
7272 0o177
7273 0o377
7274 0xdeadbeef
7275 0xDead_Beef
7276
7277 An underscore can follow the base specifier. For example, "0x_1f" is a
7278 valid literal, but "0_x1f" and "0x__1f" are not.
7279
7280 Leading zeros in a non-zero decimal number are not allowed. For
7281 example, "0123" is not a valid literal. This is for disambiguation
7282 with C-style octal literals, which Python used before version 3.0.
7283
7284 Formally, integer literals are described by the following lexical
7285 definitions:
7286
7287 integer: decinteger | bininteger | octinteger | hexinteger | zerointeger
7288 decinteger: nonzerodigit (["_"] digit)*
7289 bininteger: "0" ("b" | "B") (["_"] bindigit)+
7290 octinteger: "0" ("o" | "O") (["_"] octdigit)+
7291 hexinteger: "0" ("x" | "X") (["_"] hexdigit)+
7292 zerointeger: "0"+ (["_"] "0")*
7293 nonzerodigit: "1"..."9"
7294 digit: "0"..."9"
7295 bindigit: "0" | "1"
7296 octdigit: "0"..."7"
7297 hexdigit: digit | "a"..."f" | "A"..."F"
7298
7299 Changed in version 3.6: Underscores are now allowed for grouping
7300 purposes in literals.
7301
7302
7303 Floating-point literals
7304 =======================
7305
7306 Floating-point (float) literals, such as "3.14" or "1.5", denote
7307 approximations of real numbers.
7308
7309 They consist of *integer* and *fraction* parts, each composed of
7310 decimal digits. The parts are separated by a decimal point, ".":
7311
7312 2.71828
7313 4.0
7314
7315 Unlike in integer literals, leading zeros are allowed. For example,
7316 "077.010" is legal, and denotes the same number as "77.01".
7317
7318 As in integer literals, single underscores may occur between digits to
7319 help readability:
7320
7321 96_485.332_123
7322 3.14_15_93
7323
7324 Either of these parts, but not both, can be empty. For example:
7325
7326 10. # (equivalent to 10.0)
7327 .001 # (equivalent to 0.001)
7328
7329 Optionally, the integer and fraction may be followed by an *exponent*:
7330 the letter "e" or "E", followed by an optional sign, "+" or "-", and a
7331 number in the same format as the integer and fraction parts. The "e"
7332 or "E" represents “times ten raised to the power of”:
7333
7334 1.0e3 # (represents 1.0×10³, or 1000.0)
7335 1.166e-5 # (represents 1.166×10⁻⁵, or 0.00001166)
7336 6.02214076e+23 # (represents 6.02214076×10²³, or 602214076000000000000000.)
7337
7338 In floats with only integer and exponent parts, the decimal point may
7339 be omitted:
7340
7341 1e3 # (equivalent to 1.e3 and 1.0e3)
7342 0e0 # (equivalent to 0.)
7343
7344 Formally, floating-point literals are described by the following
7345 lexical definitions:
7346
7347 floatnumber:
7348 | digitpart "." [digitpart] [exponent]
7349 | "." digitpart [exponent]
7350 | digitpart exponent
7351 digitpart: digit (["_"] digit)*
7352 exponent: ("e" | "E") ["+" | "-"] digitpart
7353
7354 Changed in version 3.6: Underscores are now allowed for grouping
7355 purposes in literals.
7356
7357
7358 Imaginary literals
7359 ==================
7360
7361 Python has complex number objects, but no complex literals. Instead,
7362 *imaginary literals* denote complex numbers with a zero real part.
7363
7364 For example, in math, the complex number 3+4.2*i* is written as the
7365 real number 3 added to the imaginary number 4.2*i*. Python uses a
7366 similar syntax, except the imaginary unit is written as "j" rather
7367 than *i*:
7368
7369 3+4.2j
7370
7371 This is an expression composed of the integer literal "3", the
7372 operator ‘"+"’, and the imaginary literal "4.2j". Since these are
7373 three separate tokens, whitespace is allowed between them:
7374
7375 3 + 4.2j
7376
7377 No whitespace is allowed *within* each token. In particular, the "j"
7378 suffix, may not be separated from the number before it.
7379
7380 The number before the "j" has the same syntax as a floating-point
7381 literal. Thus, the following are valid imaginary literals:
7382
7383 4.2j
7384 3.14j
7385 10.j
7386 .001j
7387 1e100j
7388 3.14e-10j
7389 3.14_15_93j
7390
7391 Unlike in a floating-point literal the decimal point can be omitted if
7392 the imaginary number only has an integer part. The number is still
7393 evaluated as a floating-point number, not an integer:
7394
7395 10j
7396 0j
7397 1000000000000000000000000j # equivalent to 1e+24j
7398
7399 The "j" suffix is case-insensitive. That means you can use "J"
7400 instead:
7401
7402 3.14J # equivalent to 3.14j
7403
7404 Formally, imaginary literals are described by the following lexical
7405 definition:
7406
7407 imagnumber: (floatnumber | digitpart) ("j" | "J")
7408 ''',
7409 'numeric-types': r'''Emulating numeric types
7410 ***********************
7411
7412 The following methods can be defined to emulate numeric objects.
7413 Methods corresponding to operations that are not supported by the
7414 particular kind of number implemented (e.g., bitwise operations for
7415 non-integral numbers) should be left undefined.
7416
7417 object.__add__(self, other)
7418 object.__sub__(self, other)
7419 object.__mul__(self, other)
7420 object.__matmul__(self, other)
7421 object.__truediv__(self, other)
7422 object.__floordiv__(self, other)
7423 object.__mod__(self, other)
7424 object.__divmod__(self, other)
7425 object.__pow__(self, other[, modulo])
7426 object.__lshift__(self, other)
7427 object.__rshift__(self, other)
7428 object.__and__(self, other)
7429 object.__xor__(self, other)
7430 object.__or__(self, other)
7431
7432 These methods are called to implement the binary arithmetic
7433 operations ("+", "-", "*", "@", "/", "//", "%", "divmod()",
7434 "pow()", "**", "<<", ">>", "&", "^", "|"). For instance, to
7435 evaluate the expression "x + y", where *x* is an instance of a
7436 class that has an "__add__()" method, "type(x).__add__(x, y)" is
7437 called. The "__divmod__()" method should be the equivalent to
7438 using "__floordiv__()" and "__mod__()"; it should not be related to
7439 "__truediv__()". Note that "__pow__()" should be defined to accept
7440 an optional third argument if the three-argument version of the
7441 built-in "pow()" function is to be supported.
7442
7443 If one of those methods does not support the operation with the
7444 supplied arguments, it should return "NotImplemented".
7445
7446 object.__radd__(self, other)
7447 object.__rsub__(self, other)
7448 object.__rmul__(self, other)
7449 object.__rmatmul__(self, other)
7450 object.__rtruediv__(self, other)
7451 object.__rfloordiv__(self, other)
7452 object.__rmod__(self, other)
7453 object.__rdivmod__(self, other)
7454 object.__rpow__(self, other[, modulo])
7455 object.__rlshift__(self, other)
7456 object.__rrshift__(self, other)
7457 object.__rand__(self, other)
7458 object.__rxor__(self, other)
7459 object.__ror__(self, other)
7460
7461 These methods are called to implement the binary arithmetic
7462 operations ("+", "-", "*", "@", "/", "//", "%", "divmod()",
7463 "pow()", "**", "<<", ">>", "&", "^", "|") with reflected (swapped)
7464 operands. These functions are only called if the operands are of
7465 different types, when the left operand does not support the
7466 corresponding operation [3], or the right operand’s class is
7467 derived from the left operand’s class. [4] For instance, to
7468 evaluate the expression "x - y", where *y* is an instance of a
7469 class that has an "__rsub__()" method, "type(y).__rsub__(y, x)" is
7470 called if "type(x).__sub__(x, y)" returns "NotImplemented" or
7471 "type(y)" is a subclass of "type(x)". [5]
7472
7473 Note that "__rpow__()" should be defined to accept an optional
7474 third argument if the three-argument version of the built-in
7475 "pow()" function is to be supported.
7476
7477 Changed in version 3.14: Three-argument "pow()" now try calling
7478 "__rpow__()" if necessary. Previously it was only called in two-
7479 argument "pow()" and the binary power operator.
7480
7481 Note:
7482
7483 If the right operand’s type is a subclass of the left operand’s
7484 type and that subclass provides a different implementation of the
7485 reflected method for the operation, this method will be called
7486 before the left operand’s non-reflected method. This behavior
7487 allows subclasses to override their ancestors’ operations.
7488
7489 object.__iadd__(self, other)
7490 object.__isub__(self, other)
7491 object.__imul__(self, other)
7492 object.__imatmul__(self, other)
7493 object.__itruediv__(self, other)
7494 object.__ifloordiv__(self, other)
7495 object.__imod__(self, other)
7496 object.__ipow__(self, other[, modulo])
7497 object.__ilshift__(self, other)
7498 object.__irshift__(self, other)
7499 object.__iand__(self, other)
7500 object.__ixor__(self, other)
7501 object.__ior__(self, other)
7502
7503 These methods are called to implement the augmented arithmetic
7504 assignments ("+=", "-=", "*=", "@=", "/=", "//=", "%=", "**=",
7505 "<<=", ">>=", "&=", "^=", "|="). These methods should attempt to
7506 do the operation in-place (modifying *self*) and return the result
7507 (which could be, but does not have to be, *self*). If a specific
7508 method is not defined, or if that method returns "NotImplemented",
7509 the augmented assignment falls back to the normal methods. For
7510 instance, if *x* is an instance of a class with an "__iadd__()"
7511 method, "x += y" is equivalent to "x = x.__iadd__(y)" . If
7512 "__iadd__()" does not exist, or if "x.__iadd__(y)" returns
7513 "NotImplemented", "x.__add__(y)" and "y.__radd__(x)" are
7514 considered, as with the evaluation of "x + y". In certain
7515 situations, augmented assignment can result in unexpected errors
7516 (see Why does a_tuple[i] += [‘item’] raise an exception when the
7517 addition works?), but this behavior is in fact part of the data
7518 model.
7519
7520 object.__neg__(self)
7521 object.__pos__(self)
7522 object.__abs__(self)
7523 object.__invert__(self)
7524
7525 Called to implement the unary arithmetic operations ("-", "+",
7526 "abs()" and "~").
7527
7528 object.__complex__(self)
7529 object.__int__(self)
7530 object.__float__(self)
7531
7532 Called to implement the built-in functions "complex()", "int()" and
7533 "float()". Should return a value of the appropriate type.
7534
7535 object.__index__(self)
7536
7537 Called to implement "operator.index()", and whenever Python needs
7538 to losslessly convert the numeric object to an integer object (such
7539 as in slicing, or in the built-in "bin()", "hex()" and "oct()"
7540 functions). Presence of this method indicates that the numeric
7541 object is an integer type. Must return an integer.
7542
7543 If "__int__()", "__float__()" and "__complex__()" are not defined
7544 then corresponding built-in functions "int()", "float()" and
7545 "complex()" fall back to "__index__()".
7546
7547 object.__round__(self[, ndigits])
7548 object.__trunc__(self)
7549 object.__floor__(self)
7550 object.__ceil__(self)
7551
7552 Called to implement the built-in function "round()" and "math"
7553 functions "trunc()", "floor()" and "ceil()". Unless *ndigits* is
7554 passed to "__round__()" all these methods should return the value
7555 of the object truncated to an "Integral" (typically an "int").
7556
7557 Changed in version 3.14: "int()" no longer delegates to the
7558 "__trunc__()" method.
7559 ''',
7560 'objects': r'''Objects, values and types
7561 *************************
7562
7563 *Objects* are Python’s abstraction for data. All data in a Python
7564 program is represented by objects or by relations between objects.
7565 Even code is represented by objects.
7566
7567 Every object has an identity, a type and a value. An object’s
7568 *identity* never changes once it has been created; you may think of it
7569 as the object’s address in memory. The "is" operator compares the
7570 identity of two objects; the "id()" function returns an integer
7571 representing its identity.
7572
7573 **CPython implementation detail:** For CPython, "id(x)" is the memory
7574 address where "x" is stored.
7575
7576 An object’s type determines the operations that the object supports
7577 (e.g., “does it have a length?”) and also defines the possible values
7578 for objects of that type. The "type()" function returns an object’s
7579 type (which is an object itself). Like its identity, an object’s
7580 *type* is also unchangeable. [1]
7581
7582 The *value* of some objects can change. Objects whose value can
7583 change are said to be *mutable*; objects whose value is unchangeable
7584 once they are created are called *immutable*. (The value of an
7585 immutable container object that contains a reference to a mutable
7586 object can change when the latter’s value is changed; however the
7587 container is still considered immutable, because the collection of
7588 objects it contains cannot be changed. So, immutability is not
7589 strictly the same as having an unchangeable value, it is more subtle.)
7590 An object’s mutability is determined by its type; for instance,
7591 numbers, strings and tuples are immutable, while dictionaries and
7592 lists are mutable.
7593
7594 Objects are never explicitly destroyed; however, when they become
7595 unreachable they may be garbage-collected. An implementation is
7596 allowed to postpone garbage collection or omit it altogether — it is a
7597 matter of implementation quality how garbage collection is
7598 implemented, as long as no objects are collected that are still
7599 reachable.
7600
7601 **CPython implementation detail:** CPython currently uses a reference-
7602 counting scheme with (optional) delayed detection of cyclically linked
7603 garbage, which collects most objects as soon as they become
7604 unreachable, but is not guaranteed to collect garbage containing
7605 circular references. See the documentation of the "gc" module for
7606 information on controlling the collection of cyclic garbage. Other
7607 implementations act differently and CPython may change. Do not depend
7608 on immediate finalization of objects when they become unreachable (so
7609 you should always close files explicitly).
7610
7611 Note that the use of the implementation’s tracing or debugging
7612 facilities may keep objects alive that would normally be collectable.
7613 Also note that catching an exception with a "try"…"except" statement
7614 may keep objects alive.
7615
7616 Some objects contain references to “external” resources such as open
7617 files or windows. It is understood that these resources are freed
7618 when the object is garbage-collected, but since garbage collection is
7619 not guaranteed to happen, such objects also provide an explicit way to
7620 release the external resource, usually a "close()" method. Programs
7621 are strongly recommended to explicitly close such objects. The
7622 "try"…"finally" statement and the "with" statement provide convenient
7623 ways to do this.
7624
7625 Some objects contain references to other objects; these are called
7626 *containers*. Examples of containers are tuples, lists and
7627 dictionaries. The references are part of a container’s value. In
7628 most cases, when we talk about the value of a container, we imply the
7629 values, not the identities of the contained objects; however, when we
7630 talk about the mutability of a container, only the identities of the
7631 immediately contained objects are implied. So, if an immutable
7632 container (like a tuple) contains a reference to a mutable object, its
7633 value changes if that mutable object is changed.
7634
7635 Types affect almost all aspects of object behavior. Even the
7636 importance of object identity is affected in some sense: for immutable
7637 types, operations that compute new values may actually return a
7638 reference to any existing object with the same type and value, while
7639 for mutable objects this is not allowed. For example, after "a = 1; b
7640 = 1", *a* and *b* may or may not refer to the same object with the
7641 value one, depending on the implementation. This is because "int" is
7642 an immutable type, so the reference to "1" can be reused. This
7643 behaviour depends on the implementation used, so should not be relied
7644 upon, but is something to be aware of when making use of object
7645 identity tests. However, after "c = []; d = []", *c* and *d* are
7646 guaranteed to refer to two different, unique, newly created empty
7647 lists. (Note that "e = f = []" assigns the *same* object to both *e*
7648 and *f*.)
7649 ''',
7650 'operator-summary': r'''Operator precedence
7651 *******************
7652
7653 The following table summarizes the operator precedence in Python, from
7654 highest precedence (most binding) to lowest precedence (least
7655 binding). Operators in the same box have the same precedence. Unless
7656 the syntax is explicitly given, operators are binary. Operators in
7657 the same box group left to right (except for exponentiation and
7658 conditional expressions, which group from right to left).
7659
7660 Note that comparisons, membership tests, and identity tests, all have
7661 the same precedence and have a left-to-right chaining feature as
7662 described in the Comparisons section.
7663
7664 +-------------------------------------------------+---------------------------------------+
7665 | Operator | Description |
7666 |=================================================|=======================================|
7667 | "(expressions...)", "[expressions...]", "{key: | Binding or parenthesized expression, |
7668 | value...}", "{expressions...}" | list display, dictionary display, set |
7669 | | display |
7670 +-------------------------------------------------+---------------------------------------+
7671 | "x[index]", "x[index:index]" "x(arguments...)", | Subscription (including slicing), |
7672 | "x.attribute" | call, attribute reference |
7673 +-------------------------------------------------+---------------------------------------+
7674 | "await x" | Await expression |
7675 +-------------------------------------------------+---------------------------------------+
7676 | "**" | Exponentiation [5] |
7677 +-------------------------------------------------+---------------------------------------+
7678 | "+x", "-x", "~x" | Positive, negative, bitwise NOT |
7679 +-------------------------------------------------+---------------------------------------+
7680 | "*", "@", "/", "//", "%" | Multiplication, matrix |
7681 | | multiplication, division, floor |
7682 | | division, remainder [6] |
7683 +-------------------------------------------------+---------------------------------------+
7684 | "+", "-" | Addition and subtraction |
7685 +-------------------------------------------------+---------------------------------------+
7686 | "<<", ">>" | Shifts |
7687 +-------------------------------------------------+---------------------------------------+
7688 | "&" | Bitwise AND |
7689 +-------------------------------------------------+---------------------------------------+
7690 | "^" | Bitwise XOR |
7691 +-------------------------------------------------+---------------------------------------+
7692 | "|" | Bitwise OR |
7693 +-------------------------------------------------+---------------------------------------+
7694 | "in", "not in", "is", "is not", "<", "<=", ">", | Comparisons, including membership |
7695 | ">=", "!=", "==" | tests and identity tests |
7696 +-------------------------------------------------+---------------------------------------+
7697 | "not x" | Boolean NOT |
7698 +-------------------------------------------------+---------------------------------------+
7699 | "and" | Boolean AND |
7700 +-------------------------------------------------+---------------------------------------+
7701 | "or" | Boolean OR |
7702 +-------------------------------------------------+---------------------------------------+
7703 | "if" – "else" | Conditional expression |
7704 +-------------------------------------------------+---------------------------------------+
7705 | "lambda" | Lambda expression |
7706 +-------------------------------------------------+---------------------------------------+
7707 | ":=" | Assignment expression |
7708 +-------------------------------------------------+---------------------------------------+
7709
7710 -[ Footnotes ]-
7711
7712 [1] While "abs(x%y) < abs(y)" is true mathematically, for floats it
7713 may not be true numerically due to roundoff. For example, and
7714 assuming a platform on which a Python float is an IEEE 754 double-
7715 precision number, in order that "-1e-100 % 1e100" have the same
7716 sign as "1e100", the computed result is "-1e-100 + 1e100", which
7717 is numerically exactly equal to "1e100". The function
7718 "math.fmod()" returns a result whose sign matches the sign of the
7719 first argument instead, and so returns "-1e-100" in this case.
7720 Which approach is more appropriate depends on the application.
7721
7722 [2] If x is very close to an exact integer multiple of y, it’s
7723 possible for "x//y" to be one larger than "(x-x%y)//y" due to
7724 rounding. In such cases, Python returns the latter result, in
7725 order to preserve that "divmod(x,y)[0] * y + x % y" be very close
7726 to "x".
7727
7728 [3] The Unicode standard distinguishes between *code points* (e.g.
7729 U+0041) and *abstract characters* (e.g. “LATIN CAPITAL LETTER A”).
7730 While most abstract characters in Unicode are only represented
7731 using one code point, there is a number of abstract characters
7732 that can in addition be represented using a sequence of more than
7733 one code point. For example, the abstract character “LATIN
7734 CAPITAL LETTER C WITH CEDILLA” can be represented as a single
7735 *precomposed character* at code position U+00C7, or as a sequence
7736 of a *base character* at code position U+0043 (LATIN CAPITAL
7737 LETTER C), followed by a *combining character* at code position
7738 U+0327 (COMBINING CEDILLA).
7739
7740 The comparison operators on strings compare at the level of
7741 Unicode code points. This may be counter-intuitive to humans. For
7742 example, ""\u00C7" == "\u0043\u0327"" is "False", even though both
7743 strings represent the same abstract character “LATIN CAPITAL
7744 LETTER C WITH CEDILLA”.
7745
7746 To compare strings at the level of abstract characters (that is,
7747 in a way intuitive to humans), use "unicodedata.normalize()".
7748
7749 [4] Due to automatic garbage-collection, free lists, and the dynamic
7750 nature of descriptors, you may notice seemingly unusual behaviour
7751 in certain uses of the "is" operator, like those involving
7752 comparisons between instance methods, or constants. Check their
7753 documentation for more info.
7754
7755 [5] The power operator "**" binds less tightly than an arithmetic or
7756 bitwise unary operator on its right, that is, "2**-1" is "0.5".
7757
7758 [6] The "%" operator is also used for string formatting; the same
7759 precedence applies.
7760 ''',
7761 'pass': r'''The "pass" statement
7762 ********************
7763
7764 pass_stmt: "pass"
7765
7766 "pass" is a null operation — when it is executed, nothing happens. It
7767 is useful as a placeholder when a statement is required syntactically,
7768 but no code needs to be executed, for example:
7769
7770 def f(arg): pass # a function that does nothing (yet)
7771
7772 class C: pass # a class with no methods (yet)
7773 ''',
7774 'power': r'''The power operator
7775 ******************
7776
7777 The power operator binds more tightly than unary operators on its
7778 left; it binds less tightly than unary operators on its right. The
7779 syntax is:
7780
7781 power: (await_expr | primary) ["**" u_expr]
7782
7783 Thus, in an unparenthesized sequence of power and unary operators, the
7784 operators are evaluated from right to left (this does not constrain
7785 the evaluation order for the operands): "-1**2" results in "-1".
7786
7787 The power operator has the same semantics as the built-in "pow()"
7788 function, when called with two arguments: it yields its left argument
7789 raised to the power of its right argument. Numeric arguments are first
7790 converted to a common type, and the result is of that type.
7791
7792 For int operands, the result has the same type as the operands unless
7793 the second argument is negative; in that case, all arguments are
7794 converted to float and a float result is delivered. For example,
7795 "10**2" returns "100", but "10**-2" returns "0.01".
7796
7797 Raising "0.0" to a negative power results in a "ZeroDivisionError".
7798 Raising a negative number to a fractional power results in a "complex"
7799 number. (In earlier versions it raised a "ValueError".)
7800
7801 This operation can be customized using the special "__pow__()" and
7802 "__rpow__()" methods.
7803 ''',
7804 'raise': r'''The "raise" statement
7805 *********************
7806
7807 raise_stmt: "raise" [expression ["from" expression]]
7808
7809 If no expressions are present, "raise" re-raises the exception that is
7810 currently being handled, which is also known as the *active
7811 exception*. If there isn’t currently an active exception, a
7812 "RuntimeError" exception is raised indicating that this is an error.
7813
7814 Otherwise, "raise" evaluates the first expression as the exception
7815 object. It must be either a subclass or an instance of
7816 "BaseException". If it is a class, the exception instance will be
7817 obtained when needed by instantiating the class with no arguments.
7818
7819 The *type* of the exception is the exception instance’s class, the
7820 *value* is the instance itself.
7821
7822 A traceback object is normally created automatically when an exception
7823 is raised and attached to it as the "__traceback__" attribute. You can
7824 create an exception and set your own traceback in one step using the
7825 "with_traceback()" exception method (which returns the same exception
7826 instance, with its traceback set to its argument), like so:
7827
7828 raise Exception("foo occurred").with_traceback(tracebackobj)
7829
7830 The "from" clause is used for exception chaining: if given, the second
7831 *expression* must be another exception class or instance. If the
7832 second expression is an exception instance, it will be attached to the
7833 raised exception as the "__cause__" attribute (which is writable). If
7834 the expression is an exception class, the class will be instantiated
7835 and the resulting exception instance will be attached to the raised
7836 exception as the "__cause__" attribute. If the raised exception is not
7837 handled, both exceptions will be printed:
7838
7839 >>> try:
7840 ... print(1 / 0)
7841 ... except Exception as exc:
7842 ... raise RuntimeError("Something bad happened") from exc
7843 ...
7844 Traceback (most recent call last):
7845 File "<stdin>", line 2, in <module>
7846 print(1 / 0)
7847 ~~^~~
7848 ZeroDivisionError: division by zero
7849
7850 The above exception was the direct cause of the following exception:
7851
7852 Traceback (most recent call last):
7853 File "<stdin>", line 4, in <module>
7854 raise RuntimeError("Something bad happened") from exc
7855 RuntimeError: Something bad happened
7856
7857 A similar mechanism works implicitly if a new exception is raised when
7858 an exception is already being handled. An exception may be handled
7859 when an "except" or "finally" clause, or a "with" statement, is used.
7860 The previous exception is then attached as the new exception’s
7861 "__context__" attribute:
7862
7863 >>> try:
7864 ... print(1 / 0)
7865 ... except:
7866 ... raise RuntimeError("Something bad happened")
7867 ...
7868 Traceback (most recent call last):
7869 File "<stdin>", line 2, in <module>
7870 print(1 / 0)
7871 ~~^~~
7872 ZeroDivisionError: division by zero
7873
7874 During handling of the above exception, another exception occurred:
7875
7876 Traceback (most recent call last):
7877 File "<stdin>", line 4, in <module>
7878 raise RuntimeError("Something bad happened")
7879 RuntimeError: Something bad happened
7880
7881 Exception chaining can be explicitly suppressed by specifying "None"
7882 in the "from" clause:
7883
7884 >>> try:
7885 ... print(1 / 0)
7886 ... except:
7887 ... raise RuntimeError("Something bad happened") from None
7888 ...
7889 Traceback (most recent call last):
7890 File "<stdin>", line 4, in <module>
7891 RuntimeError: Something bad happened
7892
7893 Additional information on exceptions can be found in section
7894 Exceptions, and information about handling exceptions is in section
7895 The try statement.
7896
7897 Changed in version 3.3: "None" is now permitted as "Y" in "raise X
7898 from Y".Added the "__suppress_context__" attribute to suppress
7899 automatic display of the exception context.
7900
7901 Changed in version 3.11: If the traceback of the active exception is
7902 modified in an "except" clause, a subsequent "raise" statement re-
7903 raises the exception with the modified traceback. Previously, the
7904 exception was re-raised with the traceback it had when it was caught.
7905 ''',
7906 'return': r'''The "return" statement
7907 **********************
7908
7909 return_stmt: "return" [expression_list]
7910
7911 "return" may only occur syntactically nested in a function definition,
7912 not within a nested class definition.
7913
7914 If an expression list is present, it is evaluated, else "None" is
7915 substituted.
7916
7917 "return" leaves the current function call with the expression list (or
7918 "None") as return value.
7919
7920 When "return" passes control out of a "try" statement with a "finally"
7921 clause, that "finally" clause is executed before really leaving the
7922 function.
7923
7924 In a generator function, the "return" statement indicates that the
7925 generator is done and will cause "StopIteration" to be raised. The
7926 returned value (if any) is used as an argument to construct
7927 "StopIteration" and becomes the "StopIteration.value" attribute.
7928
7929 In an asynchronous generator function, an empty "return" statement
7930 indicates that the asynchronous generator is done and will cause
7931 "StopAsyncIteration" to be raised. A non-empty "return" statement is
7932 a syntax error in an asynchronous generator function.
7933 ''',
7934 'sequence-types': r'''Emulating container types
7935 *************************
7936
7937 The following methods can be defined to implement container objects.
7938 None of them are provided by the "object" class itself. Containers
7939 usually are *sequences* (such as "lists" or "tuples") or *mappings*
7940 (like *dictionaries*), but can represent other containers as well.
7941 The first set of methods is used either to emulate a sequence or to
7942 emulate a mapping; the difference is that for a sequence, the
7943 allowable keys should be the integers *k* for which "0 <= k < N" where
7944 *N* is the length of the sequence, or "slice" objects, which define a
7945 range of items. It is also recommended that mappings provide the
7946 methods "keys()", "values()", "items()", "get()", "clear()",
7947 "setdefault()", "pop()", "popitem()", "copy()", and "update()"
7948 behaving similar to those for Python’s standard "dictionary" objects.
7949 The "collections.abc" module provides a "MutableMapping" *abstract
7950 base class* to help create those methods from a base set of
7951 "__getitem__()", "__setitem__()", "__delitem__()", and "keys()".
7952
7953 Mutable sequences should provide methods "append()", "clear()",
7954 "count()", "extend()", "index()", "insert()", "pop()", "remove()", and
7955 "reverse()", like Python standard "list" objects. Finally, sequence
7956 types should implement addition (meaning concatenation) and
7957 multiplication (meaning repetition) by defining the methods
7958 "__add__()", "__radd__()", "__iadd__()", "__mul__()", "__rmul__()" and
7959 "__imul__()" described below; they should not define other numerical
7960 operators.
7961
7962 It is recommended that both mappings and sequences implement the
7963 "__contains__()" method to allow efficient use of the "in" operator;
7964 for mappings, "in" should search the mapping’s keys; for sequences, it
7965 should search through the values. It is further recommended that both
7966 mappings and sequences implement the "__iter__()" method to allow
7967 efficient iteration through the container; for mappings, "__iter__()"
7968 should iterate through the object’s keys; for sequences, it should
7969 iterate through the values.
7970
7971 object.__len__(self)
7972
7973 Called to implement the built-in function "len()". Should return
7974 the length of the object, an integer ">=" 0. Also, an object that
7975 doesn’t define a "__bool__()" method and whose "__len__()" method
7976 returns zero is considered to be false in a Boolean context.
7977
7978 **CPython implementation detail:** In CPython, the length is
7979 required to be at most "sys.maxsize". If the length is larger than
7980 "sys.maxsize" some features (such as "len()") may raise
7981 "OverflowError". To prevent raising "OverflowError" by truth value
7982 testing, an object must define a "__bool__()" method.
7983
7984 object.__length_hint__(self)
7985
7986 Called to implement "operator.length_hint()". Should return an
7987 estimated length for the object (which may be greater or less than
7988 the actual length). The length must be an integer ">=" 0. The
7989 return value may also be "NotImplemented", which is treated the
7990 same as if the "__length_hint__" method didn’t exist at all. This
7991 method is purely an optimization and is never required for
7992 correctness.
7993
7994 Added in version 3.4.
7995
7996 object.__getitem__(self, subscript)
7997
7998 Called to implement *subscription*, that is, "self[subscript]". See
7999 Subscriptions and slicings for details on the syntax.
8000
8001 There are two types of built-in objects that support subscription
8002 via "__getitem__()":
8003
8004 * **sequences**, where *subscript* (also called *index*) should be
8005 an integer or a "slice" object. See the sequence documentation
8006 for the expected behavior, including handling "slice" objects and
8007 negative indices.
8008
8009 * **mappings**, where *subscript* is also called the *key*. See
8010 mapping documentation for the expected behavior.
8011
8012 If *subscript* is of an inappropriate type, "__getitem__()" should
8013 raise "TypeError". If *subscript* has an inappropriate value,
8014 "__getitem__()" should raise an "LookupError" or one of its
8015 subclasses ("IndexError" for sequences; "KeyError" for mappings).
8016
8017 Note:
8018
8019 Slicing is handled by "__getitem__()", "__setitem__()", and
8020 "__delitem__()". A call like
8021
8022 a[1:2] = b
8023
8024 is translated to
8025
8026 a[slice(1, 2, None)] = b
8027
8028 and so forth. Missing slice items are always filled in with
8029 "None".
8030
8031 Note:
8032
8033 The sequence iteration protocol (used, for example, in "for"
8034 loops), expects that an "IndexError" will be raised for illegal
8035 indexes to allow proper detection of the end of a sequence.
8036
8037 Note:
8038
8039 When subscripting a *class*, the special class method
8040 "__class_getitem__()" may be called instead of "__getitem__()".
8041 See __class_getitem__ versus __getitem__ for more details.
8042
8043 object.__setitem__(self, key, value)
8044
8045 Called to implement assignment to "self[key]". Same note as for
8046 "__getitem__()". This should only be implemented for mappings if
8047 the objects support changes to the values for keys, or if new keys
8048 can be added, or for sequences if elements can be replaced. The
8049 same exceptions should be raised for improper *key* values as for
8050 the "__getitem__()" method.
8051
8052 object.__delitem__(self, key)
8053
8054 Called to implement deletion of "self[key]". Same note as for
8055 "__getitem__()". This should only be implemented for mappings if
8056 the objects support removal of keys, or for sequences if elements
8057 can be removed from the sequence. The same exceptions should be
8058 raised for improper *key* values as for the "__getitem__()" method.
8059
8060 object.__missing__(self, key)
8061
8062 Called by "dict"."__getitem__()" to implement "self[key]" for dict
8063 subclasses when key is not in the dictionary.
8064
8065 object.__iter__(self)
8066
8067 This method is called when an *iterator* is required for a
8068 container. This method should return a new iterator object that can
8069 iterate over all the objects in the container. For mappings, it
8070 should iterate over the keys of the container.
8071
8072 object.__reversed__(self)
8073
8074 Called (if present) by the "reversed()" built-in to implement
8075 reverse iteration. It should return a new iterator object that
8076 iterates over all the objects in the container in reverse order.
8077
8078 If the "__reversed__()" method is not provided, the "reversed()"
8079 built-in will fall back to using the sequence protocol ("__len__()"
8080 and "__getitem__()"). Objects that support the sequence protocol
8081 should only provide "__reversed__()" if they can provide an
8082 implementation that is more efficient than the one provided by
8083 "reversed()".
8084
8085 The membership test operators ("in" and "not in") are normally
8086 implemented as an iteration through a container. However, container
8087 objects can supply the following special method with a more efficient
8088 implementation, which also does not require the object be iterable.
8089
8090 object.__contains__(self, item)
8091
8092 Called to implement membership test operators. Should return true
8093 if *item* is in *self*, false otherwise. For mapping objects, this
8094 should consider the keys of the mapping rather than the values or
8095 the key-item pairs.
8096
8097 For objects that don’t define "__contains__()", the membership test
8098 first tries iteration via "__iter__()", then the old sequence
8099 iteration protocol via "__getitem__()", see this section in the
8100 language reference.
8101 ''',
8102 'shifting': r'''Shifting operations
8103 *******************
8104
8105 The shifting operations have lower priority than the arithmetic
8106 operations:
8107
8108 shift_expr: a_expr | shift_expr ("<<" | ">>") a_expr
8109
8110 These operators accept integers as arguments. They shift the first
8111 argument to the left or right by the number of bits given by the
8112 second argument.
8113
8114 The left shift operation can be customized using the special
8115 "__lshift__()" and "__rlshift__()" methods. The right shift operation
8116 can be customized using the special "__rshift__()" and "__rrshift__()"
8117 methods.
8118
8119 A right shift by *n* bits is defined as floor division by "pow(2,n)".
8120 A left shift by *n* bits is defined as multiplication with "pow(2,n)".
8121 ''',
8122 'slicings': r'''Slicings
8123 ********
8124
8125 A more advanced form of subscription, *slicing*, is commonly used to
8126 extract a portion of a sequence. In this form, the subscript is a
8127 *slice*: up to three expressions separated by colons. Any of the
8128 expressions may be omitted, but a slice must contain at least one
8129 colon:
8130
8131 >>> number_names = ['zero', 'one', 'two', 'three', 'four', 'five']
8132 >>> number_names[1:3]
8133 ['one', 'two']
8134 >>> number_names[1:]
8135 ['one', 'two', 'three', 'four', 'five']
8136 >>> number_names[:3]
8137 ['zero', 'one', 'two']
8138 >>> number_names[:]
8139 ['zero', 'one', 'two', 'three', 'four', 'five']
8140 >>> number_names[::2]
8141 ['zero', 'two', 'four']
8142 >>> number_names[:-3]
8143 ['zero', 'one', 'two']
8144 >>> del number_names[4:]
8145 >>> number_names
8146 ['zero', 'one', 'two', 'three']
8147
8148 When a slice is evaluated, the interpreter constructs a "slice" object
8149 whose "start", "stop" and "step" attributes, respectively, are the
8150 results of the expressions between the colons. Any missing expression
8151 evaluates to "None". This "slice" object is then passed to the
8152 "__getitem__()" or "__class_getitem__()" *special method*, as above.
8153
8154 # continuing with the SubscriptionDemo instance defined above:
8155 >>> demo[2:3]
8156 subscripted with: slice(2, 3, None)
8157 >>> demo[::'spam']
8158 subscripted with: slice(None, None, 'spam')
8159 ''',
8160 'specialattrs': r'''Special Attributes
8161 ******************
8162
8163 The implementation adds a few special read-only attributes to several
8164 object types, where they are relevant. Some of these are not reported
8165 by the "dir()" built-in function.
8166
8167 definition.__name__
8168
8169 The name of the class, function, method, descriptor, or generator
8170 instance.
8171
8172 definition.__qualname__
8173
8174 The *qualified name* of the class, function, method, descriptor, or
8175 generator instance.
8176
8177 Added in version 3.3.
8178
8179 definition.__module__
8180
8181 The name of the module in which a class or function was defined.
8182
8183 definition.__doc__
8184
8185 The documentation string of a class or function, or "None" if
8186 undefined.
8187
8188 definition.__type_params__
8189
8190 The type parameters of generic classes, functions, and type
8191 aliases. For classes and functions that are not generic, this will
8192 be an empty tuple.
8193
8194 Added in version 3.12.
8195 ''',
8196 'specialnames': r'''Special method names
8197 ********************
8198
8199 A class can implement certain operations that are invoked by special
8200 syntax (such as arithmetic operations or subscripting and slicing) by
8201 defining methods with special names. This is Python’s approach to
8202 *operator overloading*, allowing classes to define their own behavior
8203 with respect to language operators. For instance, if a class defines
8204 a method named "__getitem__()", and "x" is an instance of this class,
8205 then "x[i]" is roughly equivalent to "type(x).__getitem__(x, i)".
8206 Except where mentioned, attempts to execute an operation raise an
8207 exception when no appropriate method is defined (typically
8208 "AttributeError" or "TypeError").
8209
8210 Setting a special method to "None" indicates that the corresponding
8211 operation is not available. For example, if a class sets "__iter__()"
8212 to "None", the class is not iterable, so calling "iter()" on its
8213 instances will raise a "TypeError" (without falling back to
8214 "__getitem__()"). [2]
8215
8216 When implementing a class that emulates any built-in type, it is
8217 important that the emulation only be implemented to the degree that it
8218 makes sense for the object being modelled. For example, some
8219 sequences may work well with retrieval of individual elements, but
8220 extracting a slice may not make sense. (One example of this is the
8221 NodeList interface in the W3C’s Document Object Model.)
8222
8223
8224 Basic customization
8225 ===================
8226
8227 object.__new__(cls[, ...])
8228
8229 Called to create a new instance of class *cls*. "__new__()" is a
8230 static method (special-cased so you need not declare it as such)
8231 that takes the class of which an instance was requested as its
8232 first argument. The remaining arguments are those passed to the
8233 object constructor expression (the call to the class). The return
8234 value of "__new__()" should be the new object instance (usually an
8235 instance of *cls*).
8236
8237 Typical implementations create a new instance of the class by
8238 invoking the superclass’s "__new__()" method using
8239 "super().__new__(cls[, ...])" with appropriate arguments and then
8240 modifying the newly created instance as necessary before returning
8241 it.
8242
8243 If "__new__()" is invoked during object construction and it returns
8244 an instance of *cls*, then the new instance’s "__init__()" method
8245 will be invoked like "__init__(self[, ...])", where *self* is the
8246 new instance and the remaining arguments are the same as were
8247 passed to the object constructor.
8248
8249 If "__new__()" does not return an instance of *cls*, then the new
8250 instance’s "__init__()" method will not be invoked.
8251
8252 "__new__()" is intended mainly to allow subclasses of immutable
8253 types (like int, str, or tuple) to customize instance creation. It
8254 is also commonly overridden in custom metaclasses in order to
8255 customize class creation.
8256
8257 object.__init__(self[, ...])
8258
8259 Called after the instance has been created (by "__new__()"), but
8260 before it is returned to the caller. The arguments are those
8261 passed to the class constructor expression. If a base class has an
8262 "__init__()" method, the derived class’s "__init__()" method, if
8263 any, must explicitly call it to ensure proper initialization of the
8264 base class part of the instance; for example:
8265 "super().__init__([args...])".
8266
8267 Because "__new__()" and "__init__()" work together in constructing
8268 objects ("__new__()" to create it, and "__init__()" to customize
8269 it), no non-"None" value may be returned by "__init__()"; doing so
8270 will cause a "TypeError" to be raised at runtime.
8271
8272 object.__del__(self)
8273
8274 Called when the instance is about to be destroyed. This is also
8275 called a finalizer or (improperly) a destructor. If a base class
8276 has a "__del__()" method, the derived class’s "__del__()" method,
8277 if any, must explicitly call it to ensure proper deletion of the
8278 base class part of the instance.
8279
8280 It is possible (though not recommended!) for the "__del__()" method
8281 to postpone destruction of the instance by creating a new reference
8282 to it. This is called object *resurrection*. It is
8283 implementation-dependent whether "__del__()" is called a second
8284 time when a resurrected object is about to be destroyed; the
8285 current *CPython* implementation only calls it once.
8286
8287 It is not guaranteed that "__del__()" methods are called for
8288 objects that still exist when the interpreter exits.
8289 "weakref.finalize" provides a straightforward way to register a
8290 cleanup function to be called when an object is garbage collected.
8291
8292 Note:
8293
8294 "del x" doesn’t directly call "x.__del__()" — the former
8295 decrements the reference count for "x" by one, and the latter is
8296 only called when "x"’s reference count reaches zero.
8297
8298 **CPython implementation detail:** It is possible for a reference
8299 cycle to prevent the reference count of an object from going to
8300 zero. In this case, the cycle will be later detected and deleted
8301 by the *cyclic garbage collector*. A common cause of reference
8302 cycles is when an exception has been caught in a local variable.
8303 The frame’s locals then reference the exception, which references
8304 its own traceback, which references the locals of all frames caught
8305 in the traceback.
8306
8307 See also: Documentation for the "gc" module.
8308
8309 Warning:
8310
8311 Due to the precarious circumstances under which "__del__()"
8312 methods are invoked, exceptions that occur during their execution
8313 are ignored, and a warning is printed to "sys.stderr" instead.
8314 In particular:
8315
8316 * "__del__()" can be invoked when arbitrary code is being
8317 executed, including from any arbitrary thread. If "__del__()"
8318 needs to take a lock or invoke any other blocking resource, it
8319 may deadlock as the resource may already be taken by the code
8320 that gets interrupted to execute "__del__()".
8321
8322 * "__del__()" can be executed during interpreter shutdown. As a
8323 consequence, the global variables it needs to access (including
8324 other modules) may already have been deleted or set to "None".
8325 Python guarantees that globals whose name begins with a single
8326 underscore are deleted from their module before other globals
8327 are deleted; if no other references to such globals exist, this
8328 may help in assuring that imported modules are still available
8329 at the time when the "__del__()" method is called.
8330
8331 object.__repr__(self)
8332
8333 Called by the "repr()" built-in function to compute the “official”
8334 string representation of an object. If at all possible, this
8335 should look like a valid Python expression that could be used to
8336 recreate an object with the same value (given an appropriate
8337 environment). If this is not possible, a string of the form
8338 "<...some useful description...>" should be returned. The return
8339 value must be a string object. If a class defines "__repr__()" but
8340 not "__str__()", then "__repr__()" is also used when an “informal”
8341 string representation of instances of that class is required.
8342
8343 This is typically used for debugging, so it is important that the
8344 representation is information-rich and unambiguous. A default
8345 implementation is provided by the "object" class itself.
8346
8347 object.__str__(self)
8348
8349 Called by "str(object)", the default "__format__()" implementation,
8350 and the built-in function "print()", to compute the “informal” or
8351 nicely printable string representation of an object. The return
8352 value must be a str object.
8353
8354 This method differs from "object.__repr__()" in that there is no
8355 expectation that "__str__()" return a valid Python expression: a
8356 more convenient or concise representation can be used.
8357
8358 The default implementation defined by the built-in type "object"
8359 calls "object.__repr__()".
8360
8361 object.__bytes__(self)
8362
8363 Called by bytes to compute a byte-string representation of an
8364 object. This should return a "bytes" object. The "object" class
8365 itself does not provide this method.
8366
8367 object.__format__(self, format_spec)
8368
8369 Called by the "format()" built-in function, and by extension,
8370 evaluation of formatted string literals and the "str.format()"
8371 method, to produce a “formatted” string representation of an
8372 object. The *format_spec* argument is a string that contains a
8373 description of the formatting options desired. The interpretation
8374 of the *format_spec* argument is up to the type implementing
8375 "__format__()", however most classes will either delegate
8376 formatting to one of the built-in types, or use a similar
8377 formatting option syntax.
8378
8379 See Format specification mini-language for a description of the
8380 standard formatting syntax.
8381
8382 The return value must be a string object.
8383
8384 The default implementation by the "object" class should be given an
8385 empty *format_spec* string. It delegates to "__str__()".
8386
8387 Changed in version 3.4: The __format__ method of "object" itself
8388 raises a "TypeError" if passed any non-empty string.
8389
8390 Changed in version 3.7: "object.__format__(x, '')" is now
8391 equivalent to "str(x)" rather than "format(str(x), '')".
8392
8393 object.__lt__(self, other)
8394 object.__le__(self, other)
8395 object.__eq__(self, other)
8396 object.__ne__(self, other)
8397 object.__gt__(self, other)
8398 object.__ge__(self, other)
8399
8400 These are the so-called “rich comparison” methods. The
8401 correspondence between operator symbols and method names is as
8402 follows: "x<y" calls "x.__lt__(y)", "x<=y" calls "x.__le__(y)",
8403 "x==y" calls "x.__eq__(y)", "x!=y" calls "x.__ne__(y)", "x>y" calls
8404 "x.__gt__(y)", and "x>=y" calls "x.__ge__(y)".
8405
8406 A rich comparison method may return the singleton "NotImplemented"
8407 if it does not implement the operation for a given pair of
8408 arguments. By convention, "False" and "True" are returned for a
8409 successful comparison. However, these methods can return any value,
8410 so if the comparison operator is used in a Boolean context (e.g.,
8411 in the condition of an "if" statement), Python will call "bool()"
8412 on the value to determine if the result is true or false.
8413
8414 By default, "object" implements "__eq__()" by using "is", returning
8415 "NotImplemented" in the case of a false comparison: "True if x is y
8416 else NotImplemented". For "__ne__()", by default it delegates to
8417 "__eq__()" and inverts the result unless it is "NotImplemented".
8418 There are no other implied relationships among the comparison
8419 operators or default implementations; for example, the truth of
8420 "(x<y or x==y)" does not imply "x<=y". To automatically generate
8421 ordering operations from a single root operation, see
8422 "functools.total_ordering()".
8423
8424 By default, the "object" class provides implementations consistent
8425 with Value comparisons: equality compares according to object
8426 identity, and order comparisons raise "TypeError". Each default
8427 method may generate these results directly, but may also return
8428 "NotImplemented".
8429
8430 See the paragraph on "__hash__()" for some important notes on
8431 creating *hashable* objects which support custom comparison
8432 operations and are usable as dictionary keys.
8433
8434 There are no swapped-argument versions of these methods (to be used
8435 when the left argument does not support the operation but the right
8436 argument does); rather, "__lt__()" and "__gt__()" are each other’s
8437 reflection, "__le__()" and "__ge__()" are each other’s reflection,
8438 and "__eq__()" and "__ne__()" are their own reflection. If the
8439 operands are of different types, and the right operand’s type is a
8440 direct or indirect subclass of the left operand’s type, the
8441 reflected method of the right operand has priority, otherwise the
8442 left operand’s method has priority. Virtual subclassing is not
8443 considered.
8444
8445 When no appropriate method returns any value other than
8446 "NotImplemented", the "==" and "!=" operators will fall back to
8447 "is" and "is not", respectively.
8448
8449 object.__hash__(self)
8450
8451 Called by built-in function "hash()" and for operations on members
8452 of hashed collections including "set", "frozenset", and "dict".
8453 The "__hash__()" method should return an integer. The only required
8454 property is that objects which compare equal have the same hash
8455 value; it is advised to mix together the hash values of the
8456 components of the object that also play a part in comparison of
8457 objects by packing them into a tuple and hashing the tuple.
8458 Example:
8459
8460 def __hash__(self):
8461 return hash((self.name, self.nick, self.color))
8462
8463 Note:
8464
8465 "hash()" truncates the value returned from an object’s custom
8466 "__hash__()" method to the size of a "Py_ssize_t". This is
8467 typically 8 bytes on 64-bit builds and 4 bytes on 32-bit builds.
8468 If an object’s "__hash__()" must interoperate on builds of
8469 different bit sizes, be sure to check the width on all supported
8470 builds. An easy way to do this is with "python -c "import sys;
8471 print(sys.hash_info.width)"".
8472
8473 If a class does not define an "__eq__()" method it should not
8474 define a "__hash__()" operation either; if it defines "__eq__()"
8475 but not "__hash__()", its instances will not be usable as items in
8476 hashable collections. If a class defines mutable objects and
8477 implements an "__eq__()" method, it should not implement
8478 "__hash__()", since the implementation of *hashable* collections
8479 requires that a key’s hash value is immutable (if the object’s hash
8480 value changes, it will be in the wrong hash bucket).
8481
8482 User-defined classes have "__eq__()" and "__hash__()" methods by
8483 default (inherited from the "object" class); with them, all objects
8484 compare unequal (except with themselves) and "x.__hash__()" returns
8485 an appropriate value such that "x == y" implies both that "x is y"
8486 and "hash(x) == hash(y)".
8487
8488 A class that overrides "__eq__()" and does not define "__hash__()"
8489 will have its "__hash__()" implicitly set to "None". When the
8490 "__hash__()" method of a class is "None", instances of the class
8491 will raise an appropriate "TypeError" when a program attempts to
8492 retrieve their hash value, and will also be correctly identified as
8493 unhashable when checking "isinstance(obj,
8494 collections.abc.Hashable)".
8495
8496 If a class that overrides "__eq__()" needs to retain the
8497 implementation of "__hash__()" from a parent class, the interpreter
8498 must be told this explicitly by setting "__hash__ =
8499 <ParentClass>.__hash__".
8500
8501 If a class that does not override "__eq__()" wishes to suppress
8502 hash support, it should include "__hash__ = None" in the class
8503 definition. A class which defines its own "__hash__()" that
8504 explicitly raises a "TypeError" would be incorrectly identified as
8505 hashable by an "isinstance(obj, collections.abc.Hashable)" call.
8506
8507 Note:
8508
8509 By default, the "__hash__()" values of str and bytes objects are
8510 “salted” with an unpredictable random value. Although they
8511 remain constant within an individual Python process, they are not
8512 predictable between repeated invocations of Python.This is
8513 intended to provide protection against a denial-of-service caused
8514 by carefully chosen inputs that exploit the worst case
8515 performance of a dict insertion, *O*(*n*^2) complexity. See
8516 https://ocert.org/advisories/ocert-2011-003.html for
8517 details.Changing hash values affects the iteration order of sets.
8518 Python has never made guarantees about this ordering (and it
8519 typically varies between 32-bit and 64-bit builds).See also
8520 "PYTHONHASHSEED".
8521
8522 Changed in version 3.3: Hash randomization is enabled by default.
8523
8524 object.__bool__(self)
8525
8526 Called to implement truth value testing and the built-in operation
8527 "bool()"; should return "False" or "True". When this method is not
8528 defined, "__len__()" is called, if it is defined, and the object is
8529 considered true if its result is nonzero. If a class defines
8530 neither "__len__()" nor "__bool__()" (which is true of the "object"
8531 class itself), all its instances are considered true.
8532
8533
8534 Customizing attribute access
8535 ============================
8536
8537 The following methods can be defined to customize the meaning of
8538 attribute access (use of, assignment to, or deletion of "x.name") for
8539 class instances.
8540
8541 object.__getattr__(self, name)
8542
8543 Called when the default attribute access fails with an
8544 "AttributeError" (either "__getattribute__()" raises an
8545 "AttributeError" because *name* is not an instance attribute or an
8546 attribute in the class tree for "self"; or "__get__()" of a *name*
8547 property raises "AttributeError"). This method should either
8548 return the (computed) attribute value or raise an "AttributeError"
8549 exception. The "object" class itself does not provide this method.
8550
8551 Note that if the attribute is found through the normal mechanism,
8552 "__getattr__()" is not called. (This is an intentional asymmetry
8553 between "__getattr__()" and "__setattr__()".) This is done both for
8554 efficiency reasons and because otherwise "__getattr__()" would have
8555 no way to access other attributes of the instance. Note that at
8556 least for instance variables, you can take total control by not
8557 inserting any values in the instance attribute dictionary (but
8558 instead inserting them in another object). See the
8559 "__getattribute__()" method below for a way to actually get total
8560 control over attribute access.
8561
8562 object.__getattribute__(self, name)
8563
8564 Called unconditionally to implement attribute accesses for
8565 instances of the class. If the class also defines "__getattr__()",
8566 the latter will not be called unless "__getattribute__()" either
8567 calls it explicitly or raises an "AttributeError". This method
8568 should return the (computed) attribute value or raise an
8569 "AttributeError" exception. In order to avoid infinite recursion in
8570 this method, its implementation should always call the base class
8571 method with the same name to access any attributes it needs, for
8572 example, "object.__getattribute__(self, name)".
8573
8574 Note:
8575
8576 This method may still be bypassed when looking up special methods
8577 as the result of implicit invocation via language syntax or
8578 built-in functions. See Special method lookup.
8579
8580 For certain sensitive attribute accesses, raises an auditing event
8581 "object.__getattr__" with arguments "obj" and "name".
8582
8583 object.__setattr__(self, name, value)
8584
8585 Called when an attribute assignment is attempted. This is called
8586 instead of the normal mechanism (i.e. store the value in the
8587 instance dictionary). *name* is the attribute name, *value* is the
8588 value to be assigned to it.
8589
8590 If "__setattr__()" wants to assign to an instance attribute, it
8591 should call the base class method with the same name, for example,
8592 "object.__setattr__(self, name, value)".
8593
8594 For certain sensitive attribute assignments, raises an auditing
8595 event "object.__setattr__" with arguments "obj", "name", "value".
8596
8597 object.__delattr__(self, name)
8598
8599 Like "__setattr__()" but for attribute deletion instead of
8600 assignment. This should only be implemented if "del obj.name" is
8601 meaningful for the object.
8602
8603 For certain sensitive attribute deletions, raises an auditing event
8604 "object.__delattr__" with arguments "obj" and "name".
8605
8606 object.__dir__(self)
8607
8608 Called when "dir()" is called on the object. An iterable must be
8609 returned. "dir()" converts the returned iterable to a list and
8610 sorts it.
8611
8612
8613 Customizing module attribute access
8614 -----------------------------------
8615
8616 module.__getattr__()
8617 module.__dir__()
8618
8619 Special names "__getattr__" and "__dir__" can be also used to
8620 customize access to module attributes. The "__getattr__" function at
8621 the module level should accept one argument which is the name of an
8622 attribute and return the computed value or raise an "AttributeError".
8623 If an attribute is not found on a module object through the normal
8624 lookup, i.e. "object.__getattribute__()", then "__getattr__" is
8625 searched in the module "__dict__" before raising an "AttributeError".
8626 If found, it is called with the attribute name and the result is
8627 returned.
8628
8629 The "__dir__" function should accept no arguments, and return an
8630 iterable of strings that represents the names accessible on module. If
8631 present, this function overrides the standard "dir()" search on a
8632 module.
8633
8634 module.__class__
8635
8636 For a more fine grained customization of the module behavior (setting
8637 attributes, properties, etc.), one can set the "__class__" attribute
8638 of a module object to a subclass of "types.ModuleType". For example:
8639
8640 import sys
8641 from types import ModuleType
8642
8643 class VerboseModule(ModuleType):
8644 def __repr__(self):
8645 return f'Verbose {self.__name__}'
8646
8647 def __setattr__(self, attr, value):
8648 print(f'Setting {attr}...')
8649 super().__setattr__(attr, value)
8650
8651 sys.modules[__name__].__class__ = VerboseModule
8652
8653 Note:
8654
8655 Defining module "__getattr__" and setting module "__class__" only
8656 affect lookups made using the attribute access syntax – directly
8657 accessing the module globals (whether by code within the module, or
8658 via a reference to the module’s globals dictionary) is unaffected.
8659
8660 Changed in version 3.5: "__class__" module attribute is now writable.
8661
8662 Added in version 3.7: "__getattr__" and "__dir__" module attributes.
8663
8664 See also:
8665
8666 **PEP 562** - Module __getattr__ and __dir__
8667 Describes the "__getattr__" and "__dir__" functions on modules.
8668
8669
8670 Implementing Descriptors
8671 ------------------------
8672
8673 The following methods only apply when an instance of the class
8674 containing the method (a so-called *descriptor* class) appears in an
8675 *owner* class (the descriptor must be in either the owner’s class
8676 dictionary or in the class dictionary for one of its parents). In the
8677 examples below, “the attribute” refers to the attribute whose name is
8678 the key of the property in the owner class’ "__dict__". The "object"
8679 class itself does not implement any of these protocols.
8680
8681 object.__get__(self, instance, owner=None)
8682
8683 Called to get the attribute of the owner class (class attribute
8684 access) or of an instance of that class (instance attribute
8685 access). The optional *owner* argument is the owner class, while
8686 *instance* is the instance that the attribute was accessed through,
8687 or "None" when the attribute is accessed through the *owner*.
8688
8689 This method should return the computed attribute value or raise an
8690 "AttributeError" exception.
8691
8692 **PEP 252** specifies that "__get__()" is callable with one or two
8693 arguments. Python’s own built-in descriptors support this
8694 specification; however, it is likely that some third-party tools
8695 have descriptors that require both arguments. Python’s own
8696 "__getattribute__()" implementation always passes in both arguments
8697 whether they are required or not.
8698
8699 object.__set__(self, instance, value)
8700
8701 Called to set the attribute on an instance *instance* of the owner
8702 class to a new value, *value*.
8703
8704 Note, adding "__set__()" or "__delete__()" changes the kind of
8705 descriptor to a “data descriptor”. See Invoking Descriptors for
8706 more details.
8707
8708 object.__delete__(self, instance)
8709
8710 Called to delete the attribute on an instance *instance* of the
8711 owner class.
8712
8713 Instances of descriptors may also have the "__objclass__" attribute
8714 present:
8715
8716 object.__objclass__
8717
8718 The attribute "__objclass__" is interpreted by the "inspect" module
8719 as specifying the class where this object was defined (setting this
8720 appropriately can assist in runtime introspection of dynamic class
8721 attributes). For callables, it may indicate that an instance of the
8722 given type (or a subclass) is expected or required as the first
8723 positional argument (for example, CPython sets this attribute for
8724 unbound methods that are implemented in C).
8725
8726
8727 Invoking Descriptors
8728 --------------------
8729
8730 In general, a descriptor is an object attribute with “binding
8731 behavior”, one whose attribute access has been overridden by methods
8732 in the descriptor protocol: "__get__()", "__set__()", and
8733 "__delete__()". If any of those methods are defined for an object, it
8734 is said to be a descriptor.
8735
8736 The default behavior for attribute access is to get, set, or delete
8737 the attribute from an object’s dictionary. For instance, "a.x" has a
8738 lookup chain starting with "a.__dict__['x']", then
8739 "type(a).__dict__['x']", and continuing through the base classes of
8740 "type(a)" excluding metaclasses.
8741
8742 However, if the looked-up value is an object defining one of the
8743 descriptor methods, then Python may override the default behavior and
8744 invoke the descriptor method instead. Where this occurs in the
8745 precedence chain depends on which descriptor methods were defined and
8746 how they were called.
8747
8748 The starting point for descriptor invocation is a binding, "a.x". How
8749 the arguments are assembled depends on "a":
8750
8751 Direct Call
8752 The simplest and least common call is when user code directly
8753 invokes a descriptor method: "x.__get__(a)".
8754
8755 Instance Binding
8756 If binding to an object instance, "a.x" is transformed into the
8757 call: "type(a).__dict__['x'].__get__(a, type(a))".
8758
8759 Class Binding
8760 If binding to a class, "A.x" is transformed into the call:
8761 "A.__dict__['x'].__get__(None, A)".
8762
8763 Super Binding
8764 A dotted lookup such as "super(A, a).x" searches
8765 "a.__class__.__mro__" for a base class "B" following "A" and then
8766 returns "B.__dict__['x'].__get__(a, A)". If not a descriptor, "x"
8767 is returned unchanged.
8768
8769 For instance bindings, the precedence of descriptor invocation depends
8770 on which descriptor methods are defined. A descriptor can define any
8771 combination of "__get__()", "__set__()" and "__delete__()". If it
8772 does not define "__get__()", then accessing the attribute will return
8773 the descriptor object itself unless there is a value in the object’s
8774 instance dictionary. If the descriptor defines "__set__()" and/or
8775 "__delete__()", it is a data descriptor; if it defines neither, it is
8776 a non-data descriptor. Normally, data descriptors define both
8777 "__get__()" and "__set__()", while non-data descriptors have just the
8778 "__get__()" method. Data descriptors with "__get__()" and "__set__()"
8779 (and/or "__delete__()") defined always override a redefinition in an
8780 instance dictionary. In contrast, non-data descriptors can be
8781 overridden by instances.
8782
8783 Python methods (including those decorated with "@staticmethod" and
8784 "@classmethod") are implemented as non-data descriptors. Accordingly,
8785 instances can redefine and override methods. This allows individual
8786 instances to acquire behaviors that differ from other instances of the
8787 same class.
8788
8789 The "property()" function is implemented as a data descriptor.
8790 Accordingly, instances cannot override the behavior of a property.
8791
8792
8793 __slots__
8794 ---------
8795
8796 *__slots__* allow us to explicitly declare data members (like
8797 properties) and deny the creation of "__dict__" and *__weakref__*
8798 (unless explicitly declared in *__slots__* or available in a parent.)
8799
8800 The space saved over using "__dict__" can be significant. Attribute
8801 lookup speed can be significantly improved as well.
8802
8803 object.__slots__
8804
8805 This class variable can be assigned a string, iterable, or sequence
8806 of strings with variable names used by instances. *__slots__*
8807 reserves space for the declared variables and prevents the
8808 automatic creation of "__dict__" and *__weakref__* for each
8809 instance.
8810
8811 Notes on using *__slots__*:
8812
8813 * When inheriting from a class without *__slots__*, the "__dict__" and
8814 *__weakref__* attribute of the instances will always be accessible.
8815
8816 * Without a "__dict__" variable, instances cannot be assigned new
8817 variables not listed in the *__slots__* definition. Attempts to
8818 assign to an unlisted variable name raises "AttributeError". If
8819 dynamic assignment of new variables is desired, then add
8820 "'__dict__'" to the sequence of strings in the *__slots__*
8821 declaration.
8822
8823 * Without a *__weakref__* variable for each instance, classes defining
8824 *__slots__* do not support "weak references" to its instances. If
8825 weak reference support is needed, then add "'__weakref__'" to the
8826 sequence of strings in the *__slots__* declaration.
8827
8828 * *__slots__* are implemented at the class level by creating
8829 descriptors for each variable name. As a result, class attributes
8830 cannot be used to set default values for instance variables defined
8831 by *__slots__*; otherwise, the class attribute would overwrite the
8832 descriptor assignment.
8833
8834 * The action of a *__slots__* declaration is not limited to the class
8835 where it is defined. *__slots__* declared in parents are available
8836 in child classes. However, instances of a child subclass will get a
8837 "__dict__" and *__weakref__* unless the subclass also defines
8838 *__slots__* (which should only contain names of any *additional*
8839 slots).
8840
8841 * If a class defines a slot also defined in a base class, the instance
8842 variable defined by the base class slot is inaccessible (except by
8843 retrieving its descriptor directly from the base class). This
8844 renders the meaning of the program undefined. In the future, a
8845 check may be added to prevent this.
8846
8847 * "TypeError" will be raised if nonempty *__slots__* are defined for a
8848 class derived from a ""variable-length" built-in type" such as
8849 "int", "bytes", and "tuple".
8850
8851 * Any non-string *iterable* may be assigned to *__slots__*.
8852
8853 * If a "dictionary" is used to assign *__slots__*, the dictionary keys
8854 will be used as the slot names. The values of the dictionary can be
8855 used to provide per-attribute docstrings that will be recognised by
8856 "inspect.getdoc()" and displayed in the output of "help()".
8857
8858 * "__class__" assignment works only if both classes have the same
8859 *__slots__*.
8860
8861 * Multiple inheritance with multiple slotted parent classes can be
8862 used, but only one parent is allowed to have attributes created by
8863 slots (the other bases must have empty slot layouts) - violations
8864 raise "TypeError".
8865
8866 * If an *iterator* is used for *__slots__* then a *descriptor* is
8867 created for each of the iterator’s values. However, the *__slots__*
8868 attribute will be an empty iterator.
8869
8870
8871 Customizing class creation
8872 ==========================
8873
8874 Whenever a class inherits from another class, "__init_subclass__()" is
8875 called on the parent class. This way, it is possible to write classes
8876 which change the behavior of subclasses. This is closely related to
8877 class decorators, but where class decorators only affect the specific
8878 class they’re applied to, "__init_subclass__" solely applies to future
8879 subclasses of the class defining the method.
8880
8881 classmethod object.__init_subclass__(cls)
8882
8883 This method is called whenever the containing class is subclassed.
8884 *cls* is then the new subclass. If defined as a normal instance
8885 method, this method is implicitly converted to a class method.
8886
8887 Keyword arguments which are given to a new class are passed to the
8888 parent class’s "__init_subclass__". For compatibility with other
8889 classes using "__init_subclass__", one should take out the needed
8890 keyword arguments and pass the others over to the base class, as
8891 in:
8892
8893 class Philosopher:
8894 def __init_subclass__(cls, /, default_name, **kwargs):
8895 super().__init_subclass__(**kwargs)
8896 cls.default_name = default_name
8897
8898 class AustralianPhilosopher(Philosopher, default_name="Bruce"):
8899 pass
8900
8901 The default implementation "object.__init_subclass__" does nothing,
8902 but raises an error if it is called with any arguments.
8903
8904 Note:
8905
8906 The metaclass hint "metaclass" is consumed by the rest of the
8907 type machinery, and is never passed to "__init_subclass__"
8908 implementations. The actual metaclass (rather than the explicit
8909 hint) can be accessed as "type(cls)".
8910
8911 Added in version 3.6.
8912
8913 When a class is created, "type.__new__()" scans the class variables
8914 and makes callbacks to those with a "__set_name__()" hook.
8915
8916 object.__set_name__(self, owner, name)
8917
8918 Automatically called at the time the owning class *owner* is
8919 created. The object has been assigned to *name* in that class:
8920
8921 class A:
8922 x = C() # Automatically calls: x.__set_name__(A, 'x')
8923
8924 If the class variable is assigned after the class is created,
8925 "__set_name__()" will not be called automatically. If needed,
8926 "__set_name__()" can be called directly:
8927
8928 class A:
8929 pass
8930
8931 c = C()
8932 A.x = c # The hook is not called
8933 c.__set_name__(A, 'x') # Manually invoke the hook
8934
8935 See Creating the class object for more details.
8936
8937 Added in version 3.6.
8938
8939
8940 Metaclasses
8941 -----------
8942
8943 By default, classes are constructed using "type()". The class body is
8944 executed in a new namespace and the class name is bound locally to the
8945 result of "type(name, bases, namespace)".
8946
8947 The class creation process can be customized by passing the
8948 "metaclass" keyword argument in the class definition line, or by
8949 inheriting from an existing class that included such an argument. In
8950 the following example, both "MyClass" and "MySubclass" are instances
8951 of "Meta":
8952
8953 class Meta(type):
8954 pass
8955
8956 class MyClass(metaclass=Meta):
8957 pass
8958
8959 class MySubclass(MyClass):
8960 pass
8961
8962 Any other keyword arguments that are specified in the class definition
8963 are passed through to all metaclass operations described below.
8964
8965 When a class definition is executed, the following steps occur:
8966
8967 * MRO entries are resolved;
8968
8969 * the appropriate metaclass is determined;
8970
8971 * the class namespace is prepared;
8972
8973 * the class body is executed;
8974
8975 * the class object is created.
8976
8977
8978 Resolving MRO entries
8979 ---------------------
8980
8981 object.__mro_entries__(self, bases)
8982
8983 If a base that appears in a class definition is not an instance of
8984 "type", then an "__mro_entries__()" method is searched on the base.
8985 If an "__mro_entries__()" method is found, the base is substituted
8986 with the result of a call to "__mro_entries__()" when creating the
8987 class. The method is called with the original bases tuple passed to
8988 the *bases* parameter, and must return a tuple of classes that will
8989 be used instead of the base. The returned tuple may be empty: in
8990 these cases, the original base is ignored.
8991
8992 See also:
8993
8994 "types.resolve_bases()"
8995 Dynamically resolve bases that are not instances of "type".
8996
8997 "types.get_original_bases()"
8998 Retrieve a class’s “original bases” prior to modifications by
8999 "__mro_entries__()".
9000
9001 **PEP 560**
9002 Core support for typing module and generic types.
9003
9004
9005 Determining the appropriate metaclass
9006 -------------------------------------
9007
9008 The appropriate metaclass for a class definition is determined as
9009 follows:
9010
9011 * if no bases and no explicit metaclass are given, then "type()" is
9012 used;
9013
9014 * if an explicit metaclass is given and it is *not* an instance of
9015 "type()", then it is used directly as the metaclass;
9016
9017 * if an instance of "type()" is given as the explicit metaclass, or
9018 bases are defined, then the most derived metaclass is used.
9019
9020 The most derived metaclass is selected from the explicitly specified
9021 metaclass (if any) and the metaclasses (i.e. "type(cls)") of all
9022 specified base classes. The most derived metaclass is one which is a
9023 subtype of *all* of these candidate metaclasses. If none of the
9024 candidate metaclasses meets that criterion, then the class definition
9025 will fail with "TypeError".
9026
9027
9028 Preparing the class namespace
9029 -----------------------------
9030
9031 Once the appropriate metaclass has been identified, then the class
9032 namespace is prepared. If the metaclass has a "__prepare__" attribute,
9033 it is called as "namespace = metaclass.__prepare__(name, bases,
9034 **kwds)" (where the additional keyword arguments, if any, come from
9035 the class definition). The "__prepare__" method should be implemented
9036 as a "classmethod". The namespace returned by "__prepare__" is passed
9037 in to "__new__", but when the final class object is created the
9038 namespace is copied into a new "dict".
9039
9040 If the metaclass has no "__prepare__" attribute, then the class
9041 namespace is initialised as an empty ordered mapping.
9042
9043 See also:
9044
9045 **PEP 3115** - Metaclasses in Python 3000
9046 Introduced the "__prepare__" namespace hook
9047
9048
9049 Executing the class body
9050 ------------------------
9051
9052 The class body is executed (approximately) as "exec(body, globals(),
9053 namespace)". The key difference from a normal call to "exec()" is that
9054 lexical scoping allows the class body (including any methods) to
9055 reference names from the current and outer scopes when the class
9056 definition occurs inside a function.
9057
9058 However, even when the class definition occurs inside the function,
9059 methods defined inside the class still cannot see names defined at the
9060 class scope. Class variables must be accessed through the first
9061 parameter of instance or class methods, or through the implicit
9062 lexically scoped "__class__" reference described in the next section.
9063
9064
9065 Creating the class object
9066 -------------------------
9067
9068 Once the class namespace has been populated by executing the class
9069 body, the class object is created by calling "metaclass(name, bases,
9070 namespace, **kwds)" (the additional keywords passed here are the same
9071 as those passed to "__prepare__").
9072
9073 This class object is the one that will be referenced by the zero-
9074 argument form of "super()". "__class__" is an implicit closure
9075 reference created by the compiler if any methods in a class body refer
9076 to either "__class__" or "super". This allows the zero argument form
9077 of "super()" to correctly identify the class being defined based on
9078 lexical scoping, while the class or instance that was used to make the
9079 current call is identified based on the first argument passed to the
9080 method.
9081
9082 **CPython implementation detail:** In CPython 3.6 and later, the
9083 "__class__" cell is passed to the metaclass as a "__classcell__" entry
9084 in the class namespace. If present, this must be propagated up to the
9085 "type.__new__" call in order for the class to be initialised
9086 correctly. Failing to do so will result in a "RuntimeError" in Python
9087 3.8.
9088
9089 When using the default metaclass "type", or any metaclass that
9090 ultimately calls "type.__new__", the following additional
9091 customization steps are invoked after creating the class object:
9092
9093 1. The "type.__new__" method collects all of the attributes in the
9094 class namespace that define a "__set_name__()" method;
9095
9096 2. Those "__set_name__" methods are called with the class being
9097 defined and the assigned name of that particular attribute;
9098
9099 3. The "__init_subclass__()" hook is called on the immediate parent of
9100 the new class in its method resolution order.
9101
9102 After the class object is created, it is passed to the class
9103 decorators included in the class definition (if any) and the resulting
9104 object is bound in the local namespace as the defined class.
9105
9106 When a new class is created by "type.__new__", the object provided as
9107 the namespace parameter is copied to a new ordered mapping and the
9108 original object is discarded. The new copy is wrapped in a read-only
9109 proxy, which becomes the "__dict__" attribute of the class object.
9110
9111 See also:
9112
9113 **PEP 3135** - New super
9114 Describes the implicit "__class__" closure reference
9115
9116
9117 Uses for metaclasses
9118 --------------------
9119
9120 The potential uses for metaclasses are boundless. Some ideas that have
9121 been explored include enum, logging, interface checking, automatic
9122 delegation, automatic property creation, proxies, frameworks, and
9123 automatic resource locking/synchronization.
9124
9125
9126 Customizing instance and subclass checks
9127 ========================================
9128
9129 The following methods are used to override the default behavior of the
9130 "isinstance()" and "issubclass()" built-in functions.
9131
9132 In particular, the metaclass "abc.ABCMeta" implements these methods in
9133 order to allow the addition of Abstract Base Classes (ABCs) as
9134 “virtual base classes” to any class or type (including built-in
9135 types), including other ABCs.
9136
9137 type.__instancecheck__(self, instance)
9138
9139 Return true if *instance* should be considered a (direct or
9140 indirect) instance of *class*. If defined, called to implement
9141 "isinstance(instance, class)".
9142
9143 type.__subclasscheck__(self, subclass)
9144
9145 Return true if *subclass* should be considered a (direct or
9146 indirect) subclass of *class*. If defined, called to implement
9147 "issubclass(subclass, class)".
9148
9149 Note that these methods are looked up on the type (metaclass) of a
9150 class. They cannot be defined as class methods in the actual class.
9151 This is consistent with the lookup of special methods that are called
9152 on instances, only in this case the instance is itself a class.
9153
9154 See also:
9155
9156 **PEP 3119** - Introducing Abstract Base Classes
9157 Includes the specification for customizing "isinstance()" and
9158 "issubclass()" behavior through "__instancecheck__()" and
9159 "__subclasscheck__()", with motivation for this functionality in
9160 the context of adding Abstract Base Classes (see the "abc"
9161 module) to the language.
9162
9163
9164 Emulating generic types
9165 =======================
9166
9167 When using *type annotations*, it is often useful to *parameterize* a
9168 *generic type* using Python’s square-brackets notation. For example,
9169 the annotation "list[int]" might be used to signify a "list" in which
9170 all the elements are of type "int".
9171
9172 See also:
9173
9174 **PEP 484** - Type Hints
9175 Introducing Python’s framework for type annotations
9176
9177 Generic Alias Types
9178 Documentation for objects representing parameterized generic
9179 classes
9180
9181 Generics, user-defined generics and "typing.Generic"
9182 Documentation on how to implement generic classes that can be
9183 parameterized at runtime and understood by static type-checkers.
9184
9185 A class can *generally* only be parameterized if it defines the
9186 special class method "__class_getitem__()".
9187
9188 classmethod object.__class_getitem__(cls, key)
9189
9190 Return an object representing the specialization of a generic class
9191 by type arguments found in *key*.
9192
9193 When defined on a class, "__class_getitem__()" is automatically a
9194 class method. As such, there is no need for it to be decorated with
9195 "@classmethod" when it is defined.
9196
9197
9198 The purpose of *__class_getitem__*
9199 ----------------------------------
9200
9201 The purpose of "__class_getitem__()" is to allow runtime
9202 parameterization of standard-library generic classes in order to more
9203 easily apply *type hints* to these classes.
9204
9205 To implement custom generic classes that can be parameterized at
9206 runtime and understood by static type-checkers, users should either
9207 inherit from a standard library class that already implements
9208 "__class_getitem__()", or inherit from "typing.Generic", which has its
9209 own implementation of "__class_getitem__()".
9210
9211 Custom implementations of "__class_getitem__()" on classes defined
9212 outside of the standard library may not be understood by third-party
9213 type-checkers such as mypy. Using "__class_getitem__()" on any class
9214 for purposes other than type hinting is discouraged.
9215
9216
9217 *__class_getitem__* versus *__getitem__*
9218 ----------------------------------------
9219
9220 Usually, the subscription of an object using square brackets will call
9221 the "__getitem__()" instance method defined on the object’s class.
9222 However, if the object being subscribed is itself a class, the class
9223 method "__class_getitem__()" may be called instead.
9224 "__class_getitem__()" should return a GenericAlias object if it is
9225 properly defined.
9226
9227 Presented with the *expression* "obj[x]", the Python interpreter
9228 follows something like the following process to decide whether
9229 "__getitem__()" or "__class_getitem__()" should be called:
9230
9231 from inspect import isclass
9232
9233 def subscribe(obj, x):
9234 """Return the result of the expression 'obj[x]'"""
9235
9236 class_of_obj = type(obj)
9237
9238 # If the class of obj defines __getitem__,
9239 # call class_of_obj.__getitem__(obj, x)
9240 if hasattr(class_of_obj, '__getitem__'):
9241 return class_of_obj.__getitem__(obj, x)
9242
9243 # Else, if obj is a class and defines __class_getitem__,
9244 # call obj.__class_getitem__(x)
9245 elif isclass(obj) and hasattr(obj, '__class_getitem__'):
9246 return obj.__class_getitem__(x)
9247
9248 # Else, raise an exception
9249 else:
9250 raise TypeError(
9251 f"'{class_of_obj.__name__}' object is not subscriptable"
9252 )
9253
9254 In Python, all classes are themselves instances of other classes. The
9255 class of a class is known as that class’s *metaclass*, and most
9256 classes have the "type" class as their metaclass. "type" does not
9257 define "__getitem__()", meaning that expressions such as "list[int]",
9258 "dict[str, float]" and "tuple[str, bytes]" all result in
9259 "__class_getitem__()" being called:
9260
9261 >>> # list has class "type" as its metaclass, like most classes:
9262 >>> type(list)
9263 <class 'type'>
9264 >>> type(dict) == type(list) == type(tuple) == type(str) == type(bytes)
9265 True
9266 >>> # "list[int]" calls "list.__class_getitem__(int)"
9267 >>> list[int]
9268 list[int]
9269 >>> # list.__class_getitem__ returns a GenericAlias object:
9270 >>> type(list[int])
9271 <class 'types.GenericAlias'>
9272
9273 However, if a class has a custom metaclass that defines
9274 "__getitem__()", subscribing the class may result in different
9275 behaviour. An example of this can be found in the "enum" module:
9276
9277 >>> from enum import Enum
9278 >>> class Menu(Enum):
9279 ... """A breakfast menu"""
9280 ... SPAM = 'spam'
9281 ... BACON = 'bacon'
9282 ...
9283 >>> # Enum classes have a custom metaclass:
9284 >>> type(Menu)
9285 <class 'enum.EnumMeta'>
9286 >>> # EnumMeta defines __getitem__,
9287 >>> # so __class_getitem__ is not called,
9288 >>> # and the result is not a GenericAlias object:
9289 >>> Menu['SPAM']
9290 <Menu.SPAM: 'spam'>
9291 >>> type(Menu['SPAM'])
9292 <enum 'Menu'>
9293
9294 See also:
9295
9296 **PEP 560** - Core Support for typing module and generic types
9297 Introducing "__class_getitem__()", and outlining when a
9298 subscription results in "__class_getitem__()" being called
9299 instead of "__getitem__()"
9300
9301
9302 Emulating callable objects
9303 ==========================
9304
9305 object.__call__(self[, args...])
9306
9307 Called when the instance is “called” as a function; if this method
9308 is defined, "x(arg1, arg2, ...)" roughly translates to
9309 "type(x).__call__(x, arg1, ...)". The "object" class itself does
9310 not provide this method.
9311
9312
9313 Emulating container types
9314 =========================
9315
9316 The following methods can be defined to implement container objects.
9317 None of them are provided by the "object" class itself. Containers
9318 usually are *sequences* (such as "lists" or "tuples") or *mappings*
9319 (like *dictionaries*), but can represent other containers as well.
9320 The first set of methods is used either to emulate a sequence or to
9321 emulate a mapping; the difference is that for a sequence, the
9322 allowable keys should be the integers *k* for which "0 <= k < N" where
9323 *N* is the length of the sequence, or "slice" objects, which define a
9324 range of items. It is also recommended that mappings provide the
9325 methods "keys()", "values()", "items()", "get()", "clear()",
9326 "setdefault()", "pop()", "popitem()", "copy()", and "update()"
9327 behaving similar to those for Python’s standard "dictionary" objects.
9328 The "collections.abc" module provides a "MutableMapping" *abstract
9329 base class* to help create those methods from a base set of
9330 "__getitem__()", "__setitem__()", "__delitem__()", and "keys()".
9331
9332 Mutable sequences should provide methods "append()", "clear()",
9333 "count()", "extend()", "index()", "insert()", "pop()", "remove()", and
9334 "reverse()", like Python standard "list" objects. Finally, sequence
9335 types should implement addition (meaning concatenation) and
9336 multiplication (meaning repetition) by defining the methods
9337 "__add__()", "__radd__()", "__iadd__()", "__mul__()", "__rmul__()" and
9338 "__imul__()" described below; they should not define other numerical
9339 operators.
9340
9341 It is recommended that both mappings and sequences implement the
9342 "__contains__()" method to allow efficient use of the "in" operator;
9343 for mappings, "in" should search the mapping’s keys; for sequences, it
9344 should search through the values. It is further recommended that both
9345 mappings and sequences implement the "__iter__()" method to allow
9346 efficient iteration through the container; for mappings, "__iter__()"
9347 should iterate through the object’s keys; for sequences, it should
9348 iterate through the values.
9349
9350 object.__len__(self)
9351
9352 Called to implement the built-in function "len()". Should return
9353 the length of the object, an integer ">=" 0. Also, an object that
9354 doesn’t define a "__bool__()" method and whose "__len__()" method
9355 returns zero is considered to be false in a Boolean context.
9356
9357 **CPython implementation detail:** In CPython, the length is
9358 required to be at most "sys.maxsize". If the length is larger than
9359 "sys.maxsize" some features (such as "len()") may raise
9360 "OverflowError". To prevent raising "OverflowError" by truth value
9361 testing, an object must define a "__bool__()" method.
9362
9363 object.__length_hint__(self)
9364
9365 Called to implement "operator.length_hint()". Should return an
9366 estimated length for the object (which may be greater or less than
9367 the actual length). The length must be an integer ">=" 0. The
9368 return value may also be "NotImplemented", which is treated the
9369 same as if the "__length_hint__" method didn’t exist at all. This
9370 method is purely an optimization and is never required for
9371 correctness.
9372
9373 Added in version 3.4.
9374
9375 object.__getitem__(self, subscript)
9376
9377 Called to implement *subscription*, that is, "self[subscript]". See
9378 Subscriptions and slicings for details on the syntax.
9379
9380 There are two types of built-in objects that support subscription
9381 via "__getitem__()":
9382
9383 * **sequences**, where *subscript* (also called *index*) should be
9384 an integer or a "slice" object. See the sequence documentation
9385 for the expected behavior, including handling "slice" objects and
9386 negative indices.
9387
9388 * **mappings**, where *subscript* is also called the *key*. See
9389 mapping documentation for the expected behavior.
9390
9391 If *subscript* is of an inappropriate type, "__getitem__()" should
9392 raise "TypeError". If *subscript* has an inappropriate value,
9393 "__getitem__()" should raise an "LookupError" or one of its
9394 subclasses ("IndexError" for sequences; "KeyError" for mappings).
9395
9396 Note:
9397
9398 Slicing is handled by "__getitem__()", "__setitem__()", and
9399 "__delitem__()". A call like
9400
9401 a[1:2] = b
9402
9403 is translated to
9404
9405 a[slice(1, 2, None)] = b
9406
9407 and so forth. Missing slice items are always filled in with
9408 "None".
9409
9410 Note:
9411
9412 The sequence iteration protocol (used, for example, in "for"
9413 loops), expects that an "IndexError" will be raised for illegal
9414 indexes to allow proper detection of the end of a sequence.
9415
9416 Note:
9417
9418 When subscripting a *class*, the special class method
9419 "__class_getitem__()" may be called instead of "__getitem__()".
9420 See __class_getitem__ versus __getitem__ for more details.
9421
9422 object.__setitem__(self, key, value)
9423
9424 Called to implement assignment to "self[key]". Same note as for
9425 "__getitem__()". This should only be implemented for mappings if
9426 the objects support changes to the values for keys, or if new keys
9427 can be added, or for sequences if elements can be replaced. The
9428 same exceptions should be raised for improper *key* values as for
9429 the "__getitem__()" method.
9430
9431 object.__delitem__(self, key)
9432
9433 Called to implement deletion of "self[key]". Same note as for
9434 "__getitem__()". This should only be implemented for mappings if
9435 the objects support removal of keys, or for sequences if elements
9436 can be removed from the sequence. The same exceptions should be
9437 raised for improper *key* values as for the "__getitem__()" method.
9438
9439 object.__missing__(self, key)
9440
9441 Called by "dict"."__getitem__()" to implement "self[key]" for dict
9442 subclasses when key is not in the dictionary.
9443
9444 object.__iter__(self)
9445
9446 This method is called when an *iterator* is required for a
9447 container. This method should return a new iterator object that can
9448 iterate over all the objects in the container. For mappings, it
9449 should iterate over the keys of the container.
9450
9451 object.__reversed__(self)
9452
9453 Called (if present) by the "reversed()" built-in to implement
9454 reverse iteration. It should return a new iterator object that
9455 iterates over all the objects in the container in reverse order.
9456
9457 If the "__reversed__()" method is not provided, the "reversed()"
9458 built-in will fall back to using the sequence protocol ("__len__()"
9459 and "__getitem__()"). Objects that support the sequence protocol
9460 should only provide "__reversed__()" if they can provide an
9461 implementation that is more efficient than the one provided by
9462 "reversed()".
9463
9464 The membership test operators ("in" and "not in") are normally
9465 implemented as an iteration through a container. However, container
9466 objects can supply the following special method with a more efficient
9467 implementation, which also does not require the object be iterable.
9468
9469 object.__contains__(self, item)
9470
9471 Called to implement membership test operators. Should return true
9472 if *item* is in *self*, false otherwise. For mapping objects, this
9473 should consider the keys of the mapping rather than the values or
9474 the key-item pairs.
9475
9476 For objects that don’t define "__contains__()", the membership test
9477 first tries iteration via "__iter__()", then the old sequence
9478 iteration protocol via "__getitem__()", see this section in the
9479 language reference.
9480
9481
9482 Emulating numeric types
9483 =======================
9484
9485 The following methods can be defined to emulate numeric objects.
9486 Methods corresponding to operations that are not supported by the
9487 particular kind of number implemented (e.g., bitwise operations for
9488 non-integral numbers) should be left undefined.
9489
9490 object.__add__(self, other)
9491 object.__sub__(self, other)
9492 object.__mul__(self, other)
9493 object.__matmul__(self, other)
9494 object.__truediv__(self, other)
9495 object.__floordiv__(self, other)
9496 object.__mod__(self, other)
9497 object.__divmod__(self, other)
9498 object.__pow__(self, other[, modulo])
9499 object.__lshift__(self, other)
9500 object.__rshift__(self, other)
9501 object.__and__(self, other)
9502 object.__xor__(self, other)
9503 object.__or__(self, other)
9504
9505 These methods are called to implement the binary arithmetic
9506 operations ("+", "-", "*", "@", "/", "//", "%", "divmod()",
9507 "pow()", "**", "<<", ">>", "&", "^", "|"). For instance, to
9508 evaluate the expression "x + y", where *x* is an instance of a
9509 class that has an "__add__()" method, "type(x).__add__(x, y)" is
9510 called. The "__divmod__()" method should be the equivalent to
9511 using "__floordiv__()" and "__mod__()"; it should not be related to
9512 "__truediv__()". Note that "__pow__()" should be defined to accept
9513 an optional third argument if the three-argument version of the
9514 built-in "pow()" function is to be supported.
9515
9516 If one of those methods does not support the operation with the
9517 supplied arguments, it should return "NotImplemented".
9518
9519 object.__radd__(self, other)
9520 object.__rsub__(self, other)
9521 object.__rmul__(self, other)
9522 object.__rmatmul__(self, other)
9523 object.__rtruediv__(self, other)
9524 object.__rfloordiv__(self, other)
9525 object.__rmod__(self, other)
9526 object.__rdivmod__(self, other)
9527 object.__rpow__(self, other[, modulo])
9528 object.__rlshift__(self, other)
9529 object.__rrshift__(self, other)
9530 object.__rand__(self, other)
9531 object.__rxor__(self, other)
9532 object.__ror__(self, other)
9533
9534 These methods are called to implement the binary arithmetic
9535 operations ("+", "-", "*", "@", "/", "//", "%", "divmod()",
9536 "pow()", "**", "<<", ">>", "&", "^", "|") with reflected (swapped)
9537 operands. These functions are only called if the operands are of
9538 different types, when the left operand does not support the
9539 corresponding operation [3], or the right operand’s class is
9540 derived from the left operand’s class. [4] For instance, to
9541 evaluate the expression "x - y", where *y* is an instance of a
9542 class that has an "__rsub__()" method, "type(y).__rsub__(y, x)" is
9543 called if "type(x).__sub__(x, y)" returns "NotImplemented" or
9544 "type(y)" is a subclass of "type(x)". [5]
9545
9546 Note that "__rpow__()" should be defined to accept an optional
9547 third argument if the three-argument version of the built-in
9548 "pow()" function is to be supported.
9549
9550 Changed in version 3.14: Three-argument "pow()" now try calling
9551 "__rpow__()" if necessary. Previously it was only called in two-
9552 argument "pow()" and the binary power operator.
9553
9554 Note:
9555
9556 If the right operand’s type is a subclass of the left operand’s
9557 type and that subclass provides a different implementation of the
9558 reflected method for the operation, this method will be called
9559 before the left operand’s non-reflected method. This behavior
9560 allows subclasses to override their ancestors’ operations.
9561
9562 object.__iadd__(self, other)
9563 object.__isub__(self, other)
9564 object.__imul__(self, other)
9565 object.__imatmul__(self, other)
9566 object.__itruediv__(self, other)
9567 object.__ifloordiv__(self, other)
9568 object.__imod__(self, other)
9569 object.__ipow__(self, other[, modulo])
9570 object.__ilshift__(self, other)
9571 object.__irshift__(self, other)
9572 object.__iand__(self, other)
9573 object.__ixor__(self, other)
9574 object.__ior__(self, other)
9575
9576 These methods are called to implement the augmented arithmetic
9577 assignments ("+=", "-=", "*=", "@=", "/=", "//=", "%=", "**=",
9578 "<<=", ">>=", "&=", "^=", "|="). These methods should attempt to
9579 do the operation in-place (modifying *self*) and return the result
9580 (which could be, but does not have to be, *self*). If a specific
9581 method is not defined, or if that method returns "NotImplemented",
9582 the augmented assignment falls back to the normal methods. For
9583 instance, if *x* is an instance of a class with an "__iadd__()"
9584 method, "x += y" is equivalent to "x = x.__iadd__(y)" . If
9585 "__iadd__()" does not exist, or if "x.__iadd__(y)" returns
9586 "NotImplemented", "x.__add__(y)" and "y.__radd__(x)" are
9587 considered, as with the evaluation of "x + y". In certain
9588 situations, augmented assignment can result in unexpected errors
9589 (see Why does a_tuple[i] += [‘item’] raise an exception when the
9590 addition works?), but this behavior is in fact part of the data
9591 model.
9592
9593 object.__neg__(self)
9594 object.__pos__(self)
9595 object.__abs__(self)
9596 object.__invert__(self)
9597
9598 Called to implement the unary arithmetic operations ("-", "+",
9599 "abs()" and "~").
9600
9601 object.__complex__(self)
9602 object.__int__(self)
9603 object.__float__(self)
9604
9605 Called to implement the built-in functions "complex()", "int()" and
9606 "float()". Should return a value of the appropriate type.
9607
9608 object.__index__(self)
9609
9610 Called to implement "operator.index()", and whenever Python needs
9611 to losslessly convert the numeric object to an integer object (such
9612 as in slicing, or in the built-in "bin()", "hex()" and "oct()"
9613 functions). Presence of this method indicates that the numeric
9614 object is an integer type. Must return an integer.
9615
9616 If "__int__()", "__float__()" and "__complex__()" are not defined
9617 then corresponding built-in functions "int()", "float()" and
9618 "complex()" fall back to "__index__()".
9619
9620 object.__round__(self[, ndigits])
9621 object.__trunc__(self)
9622 object.__floor__(self)
9623 object.__ceil__(self)
9624
9625 Called to implement the built-in function "round()" and "math"
9626 functions "trunc()", "floor()" and "ceil()". Unless *ndigits* is
9627 passed to "__round__()" all these methods should return the value
9628 of the object truncated to an "Integral" (typically an "int").
9629
9630 Changed in version 3.14: "int()" no longer delegates to the
9631 "__trunc__()" method.
9632
9633
9634 With Statement Context Managers
9635 ===============================
9636
9637 A *context manager* is an object that defines the runtime context to
9638 be established when executing a "with" statement. The context manager
9639 handles the entry into, and the exit from, the desired runtime context
9640 for the execution of the block of code. Context managers are normally
9641 invoked using the "with" statement (described in section The with
9642 statement), but can also be used by directly invoking their methods.
9643
9644 Typical uses of context managers include saving and restoring various
9645 kinds of global state, locking and unlocking resources, closing opened
9646 files, etc.
9647
9648 For more information on context managers, see Context Manager Types.
9649 The "object" class itself does not provide the context manager
9650 methods.
9651
9652 object.__enter__(self)
9653
9654 Enter the runtime context related to this object. The "with"
9655 statement will bind this method’s return value to the target(s)
9656 specified in the "as" clause of the statement, if any.
9657
9658 object.__exit__(self, exc_type, exc_value, traceback)
9659
9660 Exit the runtime context related to this object. The parameters
9661 describe the exception that caused the context to be exited. If the
9662 context was exited without an exception, all three arguments will
9663 be "None".
9664
9665 If an exception is supplied, and the method wishes to suppress the
9666 exception (i.e., prevent it from being propagated), it should
9667 return a true value. Otherwise, the exception will be processed
9668 normally upon exit from this method.
9669
9670 Note that "__exit__()" methods should not reraise the passed-in
9671 exception; this is the caller’s responsibility.
9672
9673 See also:
9674
9675 **PEP 343** - The “with” statement
9676 The specification, background, and examples for the Python "with"
9677 statement.
9678
9679
9680 Customizing positional arguments in class pattern matching
9681 ==========================================================
9682
9683 When using a class name in a pattern, positional arguments in the
9684 pattern are not allowed by default, i.e. "case MyClass(x, y)" is
9685 typically invalid without special support in "MyClass". To be able to
9686 use that kind of pattern, the class needs to define a *__match_args__*
9687 attribute.
9688
9689 object.__match_args__
9690
9691 This class variable can be assigned a tuple of strings. When this
9692 class is used in a class pattern with positional arguments, each
9693 positional argument will be converted into a keyword argument,
9694 using the corresponding value in *__match_args__* as the keyword.
9695 The absence of this attribute is equivalent to setting it to "()".
9696
9697 For example, if "MyClass.__match_args__" is "("left", "center",
9698 "right")" that means that "case MyClass(x, y)" is equivalent to "case
9699 MyClass(left=x, center=y)". Note that the number of arguments in the
9700 pattern must be smaller than or equal to the number of elements in
9701 *__match_args__*; if it is larger, the pattern match attempt will
9702 raise a "TypeError".
9703
9704 Added in version 3.10.
9705
9706 See also:
9707
9708 **PEP 634** - Structural Pattern Matching
9709 The specification for the Python "match" statement.
9710
9711
9712 Emulating buffer types
9713 ======================
9714
9715 The buffer protocol provides a way for Python objects to expose
9716 efficient access to a low-level memory array. This protocol is
9717 implemented by builtin types such as "bytes" and "memoryview", and
9718 third-party libraries may define additional buffer types.
9719
9720 While buffer types are usually implemented in C, it is also possible
9721 to implement the protocol in Python.
9722
9723 object.__buffer__(self, flags)
9724
9725 Called when a buffer is requested from *self* (for example, by the
9726 "memoryview" constructor). The *flags* argument is an integer
9727 representing the kind of buffer requested, affecting for example
9728 whether the returned buffer is read-only or writable.
9729 "inspect.BufferFlags" provides a convenient way to interpret the
9730 flags. The method must return a "memoryview" object.
9731
9732 **Thread safety:** In *free-threaded* Python, implementations must
9733 manage any internal export counter using atomic operations. The
9734 method must be safe to call concurrently from multiple threads, and
9735 the returned buffer’s underlying data must remain valid until the
9736 corresponding "__release_buffer__()" call completes. See Thread
9737 safety for memoryview objects for details.
9738
9739 object.__release_buffer__(self, buffer)
9740
9741 Called when a buffer is no longer needed. The *buffer* argument is
9742 a "memoryview" object that was previously returned by
9743 "__buffer__()". The method must release any resources associated
9744 with the buffer. This method should return "None".
9745
9746 **Thread safety:** In *free-threaded* Python, any export counter
9747 decrement must use atomic operations. Resource cleanup must be
9748 thread-safe, as the final release may race with concurrent releases
9749 from other threads.
9750
9751 Buffer objects that do not need to perform any cleanup are not
9752 required to implement this method.
9753
9754 Added in version 3.12.
9755
9756 See also:
9757
9758 **PEP 688** - Making the buffer protocol accessible in Python
9759 Introduces the Python "__buffer__" and "__release_buffer__"
9760 methods.
9761
9762 "collections.abc.Buffer"
9763 ABC for buffer types.
9764
9765
9766 Annotations
9767 ===========
9768
9769 Functions, classes, and modules may contain *annotations*, which are a
9770 way to associate information (usually *type hints*) with a symbol.
9771
9772 object.__annotations__
9773
9774 This attribute contains the annotations for an object. It is lazily
9775 evaluated, so accessing the attribute may execute arbitrary code
9776 and raise exceptions. If evaluation is successful, the attribute is
9777 set to a dictionary mapping from variable names to annotations.
9778
9779 Changed in version 3.14: Annotations are now lazily evaluated.
9780
9781 object.__annotate__(format)
9782
9783 An *annotate function*. Returns a new dictionary object mapping
9784 attribute/parameter names to their annotation values.
9785
9786 Takes a format parameter specifying the format in which annotations
9787 values should be provided. It must be a member of the
9788 "annotationlib.Format" enum, or an integer with a value
9789 corresponding to a member of the enum.
9790
9791 If an annotate function doesn’t support the requested format, it
9792 must raise "NotImplementedError". Annotate functions must always
9793 support "VALUE" format; they must not raise "NotImplementedError()"
9794 when called with this format.
9795
9796 When called with "VALUE" format, an annotate function may raise
9797 "NameError"; it must not raise "NameError" when called requesting
9798 any other format.
9799
9800 If an object does not have any annotations, "__annotate__" should
9801 preferably be set to "None" (it can’t be deleted), rather than set
9802 to a function that returns an empty dict.
9803
9804 Added in version 3.14.
9805
9806 See also:
9807
9808 **PEP 649** — Deferred evaluation of annotation using descriptors
9809 Introduces lazy evaluation of annotations and the "__annotate__"
9810 function.
9811
9812
9813 Special method lookup
9814 =====================
9815
9816 For custom classes, implicit invocations of special methods are only
9817 guaranteed to work correctly if defined on an object’s type, not in
9818 the object’s instance dictionary. That behaviour is the reason why
9819 the following code raises an exception:
9820
9821 >>> class C:
9822 ... pass
9823 ...
9824 >>> c = C()
9825 >>> c.__len__ = lambda: 5
9826 >>> len(c)
9827 Traceback (most recent call last):
9828 File "<stdin>", line 1, in <module>
9829 TypeError: object of type 'C' has no len()
9830
9831 The rationale behind this behaviour lies with a number of special
9832 methods such as "__hash__()" and "__repr__()" that are implemented by
9833 all objects, including type objects. If the implicit lookup of these
9834 methods used the conventional lookup process, they would fail when
9835 invoked on the type object itself:
9836
9837 >>> 1 .__hash__() == hash(1)
9838 True
9839 >>> int.__hash__() == hash(int)
9840 Traceback (most recent call last):
9841 File "<stdin>", line 1, in <module>
9842 TypeError: descriptor '__hash__' of 'int' object needs an argument
9843
9844 Incorrectly attempting to invoke an unbound method of a class in this
9845 way is sometimes referred to as ‘metaclass confusion’, and is avoided
9846 by bypassing the instance when looking up special methods:
9847
9848 >>> type(1).__hash__(1) == hash(1)
9849 True
9850 >>> type(int).__hash__(int) == hash(int)
9851 True
9852
9853 In addition to bypassing any instance attributes in the interest of
9854 correctness, implicit special method lookup generally also bypasses
9855 the "__getattribute__()" method even of the object’s metaclass:
9856
9857 >>> class Meta(type):
9858 ... def __getattribute__(*args):
9859 ... print("Metaclass getattribute invoked")
9860 ... return type.__getattribute__(*args)
9861 ...
9862 >>> class C(object, metaclass=Meta):
9863 ... def __len__(self):
9864 ... return 10
9865 ... def __getattribute__(*args):
9866 ... print("Class getattribute invoked")
9867 ... return object.__getattribute__(*args)
9868 ...
9869 >>> c = C()
9870 >>> c.__len__() # Explicit lookup via instance
9871 Class getattribute invoked
9872 10
9873 >>> type(c).__len__(c) # Explicit lookup via type
9874 Metaclass getattribute invoked
9875 10
9876 >>> len(c) # Implicit lookup
9877 10
9878
9879 Bypassing the "__getattribute__()" machinery in this fashion provides
9880 significant scope for speed optimisations within the interpreter, at
9881 the cost of some flexibility in the handling of special methods (the
9882 special method *must* be set on the class object itself in order to be
9883 consistently invoked by the interpreter).
9884 ''',
9885 'string-methods': r'''String Methods
9886 **************
9887
9888 Strings implement all of the common sequence operations, along with
9889 the additional methods described below.
9890
9891 Strings also support two styles of string formatting, one providing a
9892 large degree of flexibility and customization (see "str.format()",
9893 Format string syntax and Custom string formatting) and the other based
9894 on C "printf" style formatting that handles a narrower range of types
9895 and is slightly harder to use correctly, but is often faster for the
9896 cases it can handle (printf-style String Formatting).
9897
9898 The Text Processing Services section of the standard library covers a
9899 number of other modules that provide various text related utilities
9900 (including regular expression support in the "re" module).
9901
9902 str.capitalize()
9903
9904 Return a copy of the string with its first character capitalized
9905 and the rest lowercased.
9906
9907 Changed in version 3.8: The first character is now put into
9908 titlecase rather than uppercase. This means that characters like
9909 digraphs will only have their first letter capitalized, instead of
9910 the full character.
9911
9912 str.casefold()
9913
9914 Return a casefolded copy of the string. Casefolded strings may be
9915 used for caseless matching.
9916
9917 Casefolding is similar to lowercasing but more aggressive because
9918 it is intended to remove all case distinctions in a string. For
9919 example, the German lowercase letter "'ß'" is equivalent to ""ss"".
9920 Since it is already lowercase, "lower()" would do nothing to "'ß'";
9921 "casefold()" converts it to ""ss"". For example:
9922
9923 >>> 'straße'.lower()
9924 'straße'
9925 >>> 'straße'.casefold()
9926 'strasse'
9927
9928 The casefolding algorithm is described in section 3.13 ‘Default
9929 Case Folding’ of the Unicode Standard.
9930
9931 Added in version 3.3.
9932
9933 str.center(width, fillchar=' ', /)
9934
9935 Return centered in a string of length *width*. Padding is done
9936 using the specified *fillchar* (default is an ASCII space). The
9937 original string is returned if *width* is less than or equal to
9938 "len(s)". For example:
9939
9940 >>> 'Python'.center(10)
9941 ' Python '
9942 >>> 'Python'.center(10, '-')
9943 '--Python--'
9944 >>> 'Python'.center(4)
9945 'Python'
9946
9947 str.count(sub[, start[, end]])
9948
9949 Return the number of non-overlapping occurrences of substring *sub*
9950 in the range [*start*, *end*]. Optional arguments *start* and
9951 *end* are interpreted as in slice notation.
9952
9953 If *sub* is empty, returns the number of empty strings between
9954 characters which is the length of the string plus one. For example:
9955
9956 >>> 'spam, spam, spam'.count('spam')
9957 3
9958 >>> 'spam, spam, spam'.count('spam', 5)
9959 2
9960 >>> 'spam, spam, spam'.count('spam', 5, 10)
9961 1
9962 >>> 'spam, spam, spam'.count('eggs')
9963 0
9964 >>> 'spam, spam, spam'.count('')
9965 17
9966
9967 str.encode(encoding='utf-8', errors='strict')
9968
9969 Return the string encoded to "bytes".
9970
9971 *encoding* defaults to "'utf-8'"; see Standard Encodings for
9972 possible values.
9973
9974 *errors* controls how encoding errors are handled. If "'strict'"
9975 (the default), a "UnicodeError" exception is raised. Other possible
9976 values are "'ignore'", "'replace'", "'xmlcharrefreplace'",
9977 "'backslashreplace'" and any other name registered via
9978 "codecs.register_error()". See Error Handlers for details.
9979
9980 For performance reasons, the value of *errors* is not checked for
9981 validity unless an encoding error actually occurs, Python
9982 Development Mode is enabled or a debug build is used. For example:
9983
9984 >>> encoded_str_to_bytes = 'Python'.encode()
9985 >>> type(encoded_str_to_bytes)
9986 <class 'bytes'>
9987 >>> encoded_str_to_bytes
9988 b'Python'
9989
9990 Changed in version 3.1: Added support for keyword arguments.
9991
9992 Changed in version 3.9: The value of the *errors* argument is now
9993 checked in Python Development Mode and in debug mode.
9994
9995 str.endswith(suffix[, start[, end]])
9996
9997 Return "True" if the string ends with the specified *suffix*,
9998 otherwise return "False". *suffix* can also be a tuple of suffixes
9999 to look for. With optional *start*, test beginning at that
10000 position. With optional *end*, stop comparing at that position.
10001 Using *start* and *end* is equivalent to
10002 "str[start:end].endswith(suffix)". For example:
10003
10004 >>> 'Python'.endswith('on')
10005 True
10006 >>> 'a tuple of suffixes'.endswith(('at', 'in'))
10007 False
10008 >>> 'a tuple of suffixes'.endswith(('at', 'es'))
10009 True
10010 >>> 'Python is amazing'.endswith('is', 0, 9)
10011 True
10012
10013 See also "startswith()" and "removesuffix()".
10014
10015 str.expandtabs(tabsize=8)
10016
10017 Return a copy of the string where all tab characters are replaced
10018 by one or more spaces, depending on the current column and the
10019 given tab size. Tab positions occur every *tabsize* characters
10020 (default is 8, giving tab positions at columns 0, 8, 16 and so on).
10021 To expand the string, the current column is set to zero and the
10022 string is examined character by character. If the character is a
10023 tab ("\t"), one or more space characters are inserted in the result
10024 until the current column is equal to the next tab position. (The
10025 tab character itself is not copied.) If the character is a newline
10026 ("\n") or return ("\r"), it is copied and the current column is
10027 reset to zero. Any other character is copied unchanged and the
10028 current column is incremented by one regardless of how the
10029 character is represented when printed. For example:
10030
10031 >>> '01\t012\t0123\t01234'.expandtabs()
10032 '01 012 0123 01234'
10033 >>> '01\t012\t0123\t01234'.expandtabs(4)
10034 '01 012 0123 01234'
10035 >>> print('01\t012\n0123\t01234'.expandtabs(4))
10036 01 012
10037 0123 01234
10038
10039 str.find(sub[, start[, end]])
10040
10041 Return the lowest index in the string where substring *sub* is
10042 found within the slice "s[start:end]". Optional arguments *start*
10043 and *end* are interpreted as in slice notation. Return "-1" if
10044 *sub* is not found. For example:
10045
10046 >>> 'spam, spam, spam'.find('sp')
10047 0
10048 >>> 'spam, spam, spam'.find('sp', 5)
10049 6
10050
10051 See also "rfind()" and "index()".
10052
10053 Note:
10054
10055 The "find()" method should be used only if you need to know the
10056 position of *sub*. To check if *sub* is a substring or not, use
10057 the "in" operator:
10058
10059 >>> 'Py' in 'Python'
10060 True
10061
10062 str.format(*args, **kwargs)
10063
10064 Perform a string formatting operation. The string on which this
10065 method is called can contain literal text or replacement fields
10066 delimited by braces "{}". Each replacement field contains either
10067 the numeric index of a positional argument, or the name of a
10068 keyword argument. Returns a copy of the string where each
10069 replacement field is replaced with the string value of the
10070 corresponding argument. For example:
10071
10072 >>> "The sum of 1 + 2 is {0}".format(1+2)
10073 'The sum of 1 + 2 is 3'
10074 >>> "The sum of {a} + {b} is {answer}".format(answer=1+2, a=1, b=2)
10075 'The sum of 1 + 2 is 3'
10076 >>> "{1} expects the {0} Inquisition!".format("Spanish", "Nobody")
10077 'Nobody expects the Spanish Inquisition!'
10078
10079 See Format string syntax for a description of the various
10080 formatting options that can be specified in format strings.
10081
10082 Note:
10083
10084 When formatting a number ("int", "float", "complex",
10085 "decimal.Decimal" and subclasses) with the "n" type (ex:
10086 "'{:n}'.format(1234)"), the function temporarily sets the
10087 "LC_CTYPE" locale to the "LC_NUMERIC" locale to decode
10088 "decimal_point" and "thousands_sep" fields of "localeconv()" if
10089 they are non-ASCII or longer than 1 byte, and the "LC_NUMERIC"
10090 locale is different than the "LC_CTYPE" locale. This temporary
10091 change affects other threads.
10092
10093 Changed in version 3.7: When formatting a number with the "n" type,
10094 the function sets temporarily the "LC_CTYPE" locale to the
10095 "LC_NUMERIC" locale in some cases.
10096
10097 str.format_map(mapping, /)
10098
10099 Similar to "str.format(**mapping)", except that "mapping" is used
10100 directly and not copied to a "dict". This is useful if for example
10101 "mapping" is a dict subclass:
10102
10103 >>> class Default(dict):
10104 ... def __missing__(self, key):
10105 ... return key
10106 ...
10107 >>> '{name} was born in {country}'.format_map(Default(name='Guido'))
10108 'Guido was born in country'
10109
10110 Added in version 3.2.
10111
10112 str.index(sub[, start[, end]])
10113
10114 Like "find()", but raise "ValueError" when the substring is not
10115 found. For example:
10116
10117 >>> 'spam, spam, spam'.index('spam')
10118 0
10119 >>> 'spam, spam, spam'.index('eggs')
10120 Traceback (most recent call last):
10121 File "<python-input-0>", line 1, in <module>
10122 'spam, spam, spam'.index('eggs')
10123 ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
10124 ValueError: substring not found
10125
10126 See also "rindex()".
10127
10128 str.isalnum()
10129
10130 Return "True" if all characters in the string are alphanumeric and
10131 there is at least one character, "False" otherwise. A character
10132 "c" is alphanumeric if one of the following returns "True":
10133 "c.isalpha()", "c.isdecimal()", "c.isdigit()", or "c.isnumeric()".
10134 For example:
10135
10136 >>> 'abc123'.isalnum()
10137 True
10138 >>> 'abc123!@#'.isalnum()
10139 False
10140 >>> ''.isalnum()
10141 False
10142 >>> ' '.isalnum()
10143 False
10144
10145 str.isalpha()
10146
10147 Return "True" if all characters in the string are alphabetic and
10148 there is at least one character, "False" otherwise. Alphabetic
10149 characters are those characters defined in the Unicode character
10150 database as “Letter”, i.e., those with general category property
10151 being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is
10152 different from the Alphabetic property defined in the section 4.10
10153 ‘Letters, Alphabetic, and Ideographic’ of the Unicode Standard. For
10154 example:
10155
10156 >>> 'Letters and spaces'.isalpha()
10157 False
10158 >>> 'LettersOnly'.isalpha()
10159 True
10160 >>> 'µ'.isalpha() # non-ASCII characters can be considered alphabetical too
10161 True
10162
10163 See Unicode Properties.
10164
10165 str.isascii()
10166
10167 Return "True" if the string is empty or all characters in the
10168 string are ASCII, "False" otherwise. ASCII characters have code
10169 points in the range U+0000-U+007F. For example:
10170
10171 >>> 'ASCII characters'.isascii()
10172 True
10173 >>> 'µ'.isascii()
10174 False
10175
10176 Added in version 3.7.
10177
10178 str.isdecimal()
10179
10180 Return "True" if all characters in the string are decimal
10181 characters and there is at least one character, "False" otherwise.
10182 Decimal characters are those that can be used to form numbers in
10183 base 10, such as U+0660, ARABIC-INDIC DIGIT ZERO. Formally a
10184 decimal character is a character in the Unicode General Category
10185 “Nd”. For example:
10186
10187 >>> '0123456789'.isdecimal()
10188 True
10189 >>> '٠١٢٣٤٥٦٧٨٩'.isdecimal() # Arabic-Indic digits zero to nine
10190 True
10191 >>> 'alphabetic'.isdecimal()
10192 False
10193
10194 str.isdigit()
10195
10196 Return "True" if all characters in the string are digits and there
10197 is at least one character, "False" otherwise. Digits include
10198 decimal characters and digits that need special handling, such as
10199 the compatibility superscript digits. This covers digits which
10200 cannot be used to form numbers in base 10, like the Kharosthi
10201 numbers. Formally, a digit is a character that has the property
10202 value Numeric_Type=Digit or Numeric_Type=Decimal.
10203
10204 str.isidentifier()
10205
10206 Return "True" if the string is a valid identifier according to the
10207 language definition, section Names (identifiers and keywords).
10208
10209 "keyword.iskeyword()" can be used to test whether string "s" is a
10210 reserved identifier, such as "def" and "class".
10211
10212 Example:
10213
10214 >>> from keyword import iskeyword
10215
10216 >>> 'hello'.isidentifier(), iskeyword('hello')
10217 (True, False)
10218 >>> 'def'.isidentifier(), iskeyword('def')
10219 (True, True)
10220
10221 str.islower()
10222
10223 Return "True" if all cased characters [4] in the string are
10224 lowercase and there is at least one cased character, "False"
10225 otherwise.
10226
10227 str.isnumeric()
10228
10229 Return "True" if all characters in the string are numeric
10230 characters, and there is at least one character, "False" otherwise.
10231 Numeric characters include digit characters, and all characters
10232 that have the Unicode numeric value property, e.g. U+2155, VULGAR
10233 FRACTION ONE FIFTH. Formally, numeric characters are those with
10234 the property value Numeric_Type=Digit, Numeric_Type=Decimal or
10235 Numeric_Type=Numeric. For example:
10236
10237 >>> '0123456789'.isnumeric()
10238 True
10239 >>> '٠١٢٣٤٥٦٧٨٩'.isnumeric() # Arabic-indic digit zero to nine
10240 True
10241 >>> '⅕'.isnumeric() # Vulgar fraction one fifth
10242 True
10243 >>> '²'.isdecimal(), '²'.isdigit(), '²'.isnumeric()
10244 (False, True, True)
10245
10246 See also "isdecimal()" and "isdigit()". Numeric characters are a
10247 superset of decimal numbers.
10248
10249 str.isprintable()
10250
10251 Return "True" if all characters in the string are printable,
10252 "False" if it contains at least one non-printable character.
10253
10254 Here “printable” means the character is suitable for "repr()" to
10255 use in its output; “non-printable” means that "repr()" on built-in
10256 types will hex-escape the character. It has no bearing on the
10257 handling of strings written to "sys.stdout" or "sys.stderr".
10258
10259 The printable characters are those which in the Unicode character
10260 database (see "unicodedata") have a general category in group
10261 Letter, Mark, Number, Punctuation, or Symbol (L, M, N, P, or S);
10262 plus the ASCII space 0x20. Nonprintable characters are those in
10263 group Separator or Other (Z or C), except the ASCII space.
10264
10265 For example:
10266
10267 >>> ''.isprintable(), ' '.isprintable()
10268 (True, True)
10269 >>> '\t'.isprintable(), '\n'.isprintable()
10270 (False, False)
10271
10272 See also "isspace()".
10273
10274 str.isspace()
10275
10276 Return "True" if there are only whitespace characters in the string
10277 and there is at least one character, "False" otherwise.
10278
10279 For example:
10280
10281 >>> ''.isspace()
10282 False
10283 >>> ' '.isspace()
10284 True
10285 >>> '\t\n'.isspace() # TAB and BREAK LINE
10286 True
10287 >>> '\u3000'.isspace() # IDEOGRAPHIC SPACE
10288 True
10289
10290 A character is *whitespace* if in the Unicode character database
10291 (see "unicodedata"), either its general category is "Zs"
10292 (“Separator, space”), or its bidirectional class is one of "WS",
10293 "B", or "S".
10294
10295 See also "isprintable()".
10296
10297 str.istitle()
10298
10299 Return "True" if the string is a titlecased string and there is at
10300 least one character, for example uppercase characters may only
10301 follow uncased characters and lowercase characters only cased ones.
10302 Return "False" otherwise.
10303
10304 For example:
10305
10306 >>> 'Spam, Spam, Spam'.istitle()
10307 True
10308 >>> 'spam, spam, spam'.istitle()
10309 False
10310 >>> 'SPAM, SPAM, SPAM'.istitle()
10311 False
10312
10313 See also "title()".
10314
10315 str.isupper()
10316
10317 Return "True" if all cased characters [4] in the string are
10318 uppercase and there is at least one cased character, "False"
10319 otherwise.
10320
10321 >>> 'BANANA'.isupper()
10322 True
10323 >>> 'banana'.isupper()
10324 False
10325 >>> 'baNana'.isupper()
10326 False
10327 >>> ' '.isupper()
10328 False
10329
10330 str.join(iterable, /)
10331
10332 Return a string which is the concatenation of the strings in
10333 *iterable*. A "TypeError" will be raised if there are any non-
10334 string values in *iterable*, including "bytes" objects. The
10335 separator between elements is the string providing this method. For
10336 example:
10337
10338 >>> ', '.join(['spam', 'spam', 'spam'])
10339 'spam, spam, spam'
10340 >>> '-'.join('Python')
10341 'P-y-t-h-o-n'
10342
10343 See also "split()".
10344
10345 str.ljust(width, fillchar=' ', /)
10346
10347 Return the string left justified in a string of length *width*.
10348 Padding is done using the specified *fillchar* (default is an ASCII
10349 space). The original string is returned if *width* is less than or
10350 equal to "len(s)".
10351
10352 For example:
10353
10354 >>> 'Python'.ljust(10)
10355 'Python '
10356 >>> 'Python'.ljust(10, '.')
10357 'Python....'
10358 >>> 'Monty Python'.ljust(10, '.')
10359 'Monty Python'
10360
10361 See also "rjust()".
10362
10363 str.lower()
10364
10365 Return a copy of the string with all the cased characters [4]
10366 converted to lowercase. For example:
10367
10368 >>> 'Lower Method Example'.lower()
10369 'lower method example'
10370
10371 The lowercasing algorithm used is described in section 3.13
10372 ‘Default Case Folding’ of the Unicode Standard.
10373
10374 str.lstrip(chars=None, /)
10375
10376 Return a copy of the string with leading characters removed. The
10377 *chars* argument is a string specifying the set of characters to be
10378 removed. If omitted or "None", the *chars* argument defaults to
10379 removing whitespace. The *chars* argument is not a prefix; rather,
10380 all combinations of its values are stripped:
10381
10382 >>> ' spacious '.lstrip()
10383 'spacious '
10384 >>> 'www.example.com'.lstrip('cmowz.')
10385 'example.com'
10386
10387 See "str.removeprefix()" for a method that will remove a single
10388 prefix string rather than all of a set of characters. For example:
10389
10390 >>> 'Arthur: three!'.lstrip('Arthur: ')
10391 'ee!'
10392 >>> 'Arthur: three!'.removeprefix('Arthur: ')
10393 'three!'
10394
10395 static str.maketrans(dict, /)
10396 static str.maketrans(from, to, remove='', /)
10397
10398 This static method returns a translation table usable for
10399 "str.translate()".
10400
10401 If there is only one argument, it must be a dictionary mapping
10402 Unicode ordinals (integers) or characters (strings of length 1) to
10403 Unicode ordinals, strings (of arbitrary lengths) or "None".
10404 Character keys will then be converted to ordinals.
10405
10406 If there are two arguments, they must be strings of equal length,
10407 and in the resulting dictionary, each character in *from* will be
10408 mapped to the character at the same position in *to*. If there is
10409 a third argument, it must be a string, whose characters will be
10410 mapped to "None" in the result.
10411
10412 str.partition(sep, /)
10413
10414 Split the string at the first occurrence of *sep*, and return a
10415 3-tuple containing the part before the separator, the separator
10416 itself, and the part after the separator. If the separator is not
10417 found, return a 3-tuple containing the string itself, followed by
10418 two empty strings.
10419
10420 For example:
10421
10422 >>> 'Monty Python'.partition(' ')
10423 ('Monty', ' ', 'Python')
10424 >>> "Monty Python's Flying Circus".partition(' ')
10425 ('Monty', ' ', "Python's Flying Circus")
10426 >>> 'Monty Python'.partition('-')
10427 ('Monty Python', '', '')
10428
10429 See also "rpartition()".
10430
10431 str.removeprefix(prefix, /)
10432
10433 If the string starts with the *prefix* string, return
10434 "string[len(prefix):]". Otherwise, return a copy of the original
10435 string:
10436
10437 >>> 'TestHook'.removeprefix('Test')
10438 'Hook'
10439 >>> 'BaseTestCase'.removeprefix('Test')
10440 'BaseTestCase'
10441
10442 Added in version 3.9.
10443
10444 See also "removesuffix()" and "startswith()".
10445
10446 str.removesuffix(suffix, /)
10447
10448 If the string ends with the *suffix* string and that *suffix* is
10449 not empty, return "string[:-len(suffix)]". Otherwise, return a copy
10450 of the original string:
10451
10452 >>> 'MiscTests'.removesuffix('Tests')
10453 'Misc'
10454 >>> 'TmpDirMixin'.removesuffix('Tests')
10455 'TmpDirMixin'
10456
10457 Added in version 3.9.
10458
10459 See also "removeprefix()" and "endswith()".
10460
10461 str.replace(old, new, /, count=-1)
10462
10463 Return a copy of the string with all occurrences of substring *old*
10464 replaced by *new*. If *count* is given, only the first *count*
10465 occurrences are replaced. If *count* is not specified or "-1", then
10466 all occurrences are replaced. For example:
10467
10468 >>> 'spam, spam, spam'.replace('spam', 'eggs')
10469 'eggs, eggs, eggs'
10470 >>> 'spam, spam, spam'.replace('spam', 'eggs', 1)
10471 'eggs, spam, spam'
10472
10473 Changed in version 3.13: *count* is now supported as a keyword
10474 argument.
10475
10476 str.rfind(sub[, start[, end]])
10477
10478 Return the highest index in the string where substring *sub* is
10479 found, such that *sub* is contained within "s[start:end]".
10480 Optional arguments *start* and *end* are interpreted as in slice
10481 notation. Return "-1" on failure. For example:
10482
10483 >>> 'spam, spam, spam'.rfind('sp')
10484 12
10485 >>> 'spam, spam, spam'.rfind('sp', 0, 10)
10486 6
10487
10488 See also "find()" and "rindex()".
10489
10490 str.rindex(sub[, start[, end]])
10491
10492 Like "rfind()" but raises "ValueError" when the substring *sub* is
10493 not found. For example:
10494
10495 >>> 'spam, spam, spam'.rindex('spam')
10496 12
10497 >>> 'spam, spam, spam'.rindex('eggs')
10498 Traceback (most recent call last):
10499 File "<stdin-0>", line 1, in <module>
10500 'spam, spam, spam'.rindex('eggs')
10501 ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
10502 ValueError: substring not found
10503
10504 See also "index()" and "find()".
10505
10506 str.rjust(width, fillchar=' ', /)
10507
10508 Return the string right justified in a string of length *width*.
10509 Padding is done using the specified *fillchar* (default is an ASCII
10510 space). The original string is returned if *width* is less than or
10511 equal to "len(s)".
10512
10513 For example:
10514
10515 >>> 'Python'.rjust(10)
10516 ' Python'
10517 >>> 'Python'.rjust(10, '.')
10518 '....Python'
10519 >>> 'Monty Python'.rjust(10, '.')
10520 'Monty Python'
10521
10522 See also "ljust()" and "zfill()".
10523
10524 str.rpartition(sep, /)
10525
10526 Split the string at the last occurrence of *sep*, and return a
10527 3-tuple containing the part before the separator, the separator
10528 itself, and the part after the separator. If the separator is not
10529 found, return a 3-tuple containing two empty strings, followed by
10530 the string itself.
10531
10532 For example:
10533
10534 >>> 'Monty Python'.rpartition(' ')
10535 ('Monty', ' ', 'Python')
10536 >>> "Monty Python's Flying Circus".rpartition(' ')
10537 ("Monty Python's Flying", ' ', 'Circus')
10538 >>> 'Monty Python'.rpartition('-')
10539 ('', '', 'Monty Python')
10540
10541 See also "partition()".
10542
10543 str.rsplit(sep=None, maxsplit=-1)
10544
10545 Return a list of the words in the string, using *sep* as the
10546 delimiter string. If *maxsplit* is given, at most *maxsplit* splits
10547 are done, the *rightmost* ones. If *sep* is not specified or
10548 "None", any whitespace string is a separator. Except for splitting
10549 from the right, "rsplit()" behaves like "split()" which is
10550 described in detail below.
10551
10552 str.rstrip(chars=None, /)
10553
10554 Return a copy of the string with trailing characters removed. The
10555 *chars* argument is a string specifying the set of characters to be
10556 removed. If omitted or "None", the *chars* argument defaults to
10557 removing whitespace. The *chars* argument is not a suffix; rather,
10558 all combinations of its values are stripped. For example:
10559
10560 >>> ' spacious '.rstrip()
10561 ' spacious'
10562 >>> 'mississippi'.rstrip('ipz')
10563 'mississ'
10564
10565 See "removesuffix()" for a method that will remove a single suffix
10566 string rather than all of a set of characters. For example:
10567
10568 >>> 'Monty Python'.rstrip(' Python')
10569 'M'
10570 >>> 'Monty Python'.removesuffix(' Python')
10571 'Monty'
10572
10573 See also "strip()".
10574
10575 str.split(sep=None, maxsplit=-1)
10576
10577 Return a list of the words in the string, using *sep* as the
10578 delimiter string. If *maxsplit* is given, at most *maxsplit*
10579 splits are done (thus, the list will have at most "maxsplit+1"
10580 elements). If *maxsplit* is not specified or "-1", then there is
10581 no limit on the number of splits (all possible splits are made).
10582
10583 If *sep* is given, consecutive delimiters are not grouped together
10584 and are deemed to delimit empty strings (for example,
10585 "'1,,2'.split(',')" returns "['1', '', '2']"). The *sep* argument
10586 may consist of multiple characters as a single delimiter (to split
10587 with multiple delimiters, use "re.split()"). Splitting an empty
10588 string with a specified separator returns "['']".
10589
10590 For example:
10591
10592 >>> '1,2,3'.split(',')
10593 ['1', '2', '3']
10594 >>> '1,2,3'.split(',', maxsplit=1)
10595 ['1', '2,3']
10596 >>> '1,2,,3,'.split(',')
10597 ['1', '2', '', '3', '']
10598 >>> '1<>2<>3<4'.split('<>')
10599 ['1', '2', '3<4']
10600
10601 If *sep* is not specified or is "None", a different splitting
10602 algorithm is applied: runs of consecutive whitespace are regarded
10603 as a single separator, and the result will contain no empty strings
10604 at the start or end if the string has leading or trailing
10605 whitespace. Consequently, splitting an empty string or a string
10606 consisting of just whitespace with a "None" separator returns "[]".
10607
10608 For example:
10609
10610 >>> '1 2 3'.split()
10611 ['1', '2', '3']
10612 >>> '1 2 3'.split(maxsplit=1)
10613 ['1', '2 3']
10614 >>> ' 1 2 3 '.split()
10615 ['1', '2', '3']
10616
10617 If *sep* is not specified or is "None" and *maxsplit* is "0", only
10618 leading runs of consecutive whitespace are considered.
10619
10620 For example:
10621
10622 >>> "".split(None, 0)
10623 []
10624 >>> " ".split(None, 0)
10625 []
10626 >>> " foo ".split(maxsplit=0)
10627 ['foo ']
10628
10629 See also "join()".
10630
10631 str.splitlines(keepends=False)
10632
10633 Return a list of the lines in the string, breaking at line
10634 boundaries. Line breaks are not included in the resulting list
10635 unless *keepends* is given and true.
10636
10637 This method splits on the following line boundaries. In
10638 particular, the boundaries are a superset of *universal newlines*.
10639
10640 +-------------------------+-------------------------------+
10641 | Representation | Description |
10642 |=========================|===============================|
10643 | "\n" | Line Feed |
10644 +-------------------------+-------------------------------+
10645 | "\r" | Carriage Return |
10646 +-------------------------+-------------------------------+
10647 | "\r\n" | Carriage Return + Line Feed |
10648 +-------------------------+-------------------------------+
10649 | "\v" or "\x0b" | Line Tabulation |
10650 +-------------------------+-------------------------------+
10651 | "\f" or "\x0c" | Form Feed |
10652 +-------------------------+-------------------------------+
10653 | "\x1c" | File Separator |
10654 +-------------------------+-------------------------------+
10655 | "\x1d" | Group Separator |
10656 +-------------------------+-------------------------------+
10657 | "\x1e" | Record Separator |
10658 +-------------------------+-------------------------------+
10659 | "\x85" | Next Line (C1 Control Code) |
10660 +-------------------------+-------------------------------+
10661 | "\u2028" | Line Separator |
10662 +-------------------------+-------------------------------+
10663 | "\u2029" | Paragraph Separator |
10664 +-------------------------+-------------------------------+
10665
10666 Changed in version 3.2: "\v" and "\f" added to list of line
10667 boundaries.
10668
10669 For example:
10670
10671 >>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
10672 ['ab c', '', 'de fg', 'kl']
10673 >>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
10674 ['ab c\n', '\n', 'de fg\r', 'kl\r\n']
10675
10676 Unlike "split()" when a delimiter string *sep* is given, this
10677 method returns an empty list for the empty string, and a terminal
10678 line break does not result in an extra line:
10679
10680 >>> "".splitlines()
10681 []
10682 >>> "One line\n".splitlines()
10683 ['One line']
10684
10685 For comparison, "split('\n')" gives:
10686
10687 >>> ''.split('\n')
10688 ['']
10689 >>> 'Two lines\n'.split('\n')
10690 ['Two lines', '']
10691
10692 str.startswith(prefix[, start[, end]])
10693
10694 Return "True" if string starts with the *prefix*, otherwise return
10695 "False". *prefix* can also be a tuple of prefixes to look for.
10696 With optional *start*, test string beginning at that position.
10697 With optional *end*, stop comparing string at that position.
10698
10699 For example:
10700
10701 >>> 'Python'.startswith('Py')
10702 True
10703 >>> 'a tuple of prefixes'.startswith(('at', 'a'))
10704 True
10705 >>> 'Python is amazing'.startswith('is', 7)
10706 True
10707
10708 See also "endswith()" and "removeprefix()".
10709
10710 str.strip(chars=None, /)
10711
10712 Return a copy of the string with the leading and trailing
10713 characters removed. The *chars* argument is a string specifying the
10714 set of characters to be removed. If omitted or "None", the *chars*
10715 argument defaults to removing whitespace. The *chars* argument is
10716 not a prefix or suffix; rather, all combinations of its values are
10717 stripped.
10718
10719 For example:
10720
10721 >>> ' spacious '.strip()
10722 'spacious'
10723 >>> 'www.example.com'.strip('cmowz.')
10724 'example'
10725
10726 The outermost leading and trailing *chars* argument values are
10727 stripped from the string. Characters are removed from the leading
10728 end until reaching a string character that is not contained in the
10729 set of characters in *chars*. A similar action takes place on the
10730 trailing end.
10731
10732 For example:
10733
10734 >>> comment_string = '#....... Section 3.2.1 Issue #32 .......'
10735 >>> comment_string.strip('.#! ')
10736 'Section 3.2.1 Issue #32'
10737
10738 See also "rstrip()".
10739
10740 str.swapcase()
10741
10742 Return a copy of the string with uppercase characters converted to
10743 lowercase and vice versa. For example:
10744
10745 >>> 'Hello World'.swapcase()
10746 'hELLO wORLD'
10747
10748 Note that it is not necessarily true that "s.swapcase().swapcase()
10749 == s". For example:
10750
10751 >>> 'straße'.swapcase().swapcase()
10752 'strasse'
10753
10754 See also "str.lower()" and "str.upper()".
10755
10756 str.title()
10757
10758 Return a titlecased version of the string where words start with an
10759 uppercase character and the remaining characters are lowercase.
10760
10761 For example:
10762
10763 >>> 'Hello world'.title()
10764 'Hello World'
10765
10766 The algorithm uses a simple language-independent definition of a
10767 word as groups of consecutive letters. The definition works in
10768 many contexts but it means that apostrophes in contractions and
10769 possessives form word boundaries, which may not be the desired
10770 result:
10771
10772 >>> "they're bill's friends from the UK".title()
10773 "They'Re Bill'S Friends From The Uk"
10774
10775 The "string.capwords()" function does not have this problem, as it
10776 splits words on spaces only.
10777
10778 Alternatively, a workaround for apostrophes can be constructed
10779 using regular expressions:
10780
10781 >>> import re
10782 >>> def titlecase(s):
10783 ... return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
10784 ... lambda mo: mo.group(0).capitalize(),
10785 ... s)
10786 ...
10787 >>> titlecase("they're bill's friends.")
10788 "They're Bill's Friends."
10789
10790 See also "istitle()".
10791
10792 str.translate(table, /)
10793
10794 Return a copy of the string in which each character has been mapped
10795 through the given translation table. The table must be an object
10796 that implements indexing via "__getitem__()", typically a *mapping*
10797 or *sequence*. When indexed by a Unicode ordinal (an integer), the
10798 table object can do any of the following: return a Unicode ordinal
10799 or a string, to map the character to one or more other characters;
10800 return "None", to delete the character from the return string; or
10801 raise a "LookupError" exception, to map the character to itself.
10802
10803 You can use "str.maketrans()" to create a translation map from
10804 character-to-character mappings in different formats.
10805
10806 See also the "codecs" module for a more flexible approach to custom
10807 character mappings.
10808
10809 str.upper()
10810
10811 Return a copy of the string with all the cased characters [4]
10812 converted to uppercase. Note that "s.upper().isupper()" might be
10813 "False" if "s" contains uncased characters or if the Unicode
10814 category of the resulting character(s) is not “Lu” (Letter,
10815 uppercase), but e.g. “Lt” (Letter, titlecase).
10816
10817 The uppercasing algorithm used is described in section 3.13
10818 ‘Default Case Folding’ of the Unicode Standard.
10819
10820 str.zfill(width, /)
10821
10822 Return a copy of the string left filled with ASCII "'0'" digits to
10823 make a string of length *width*. A leading sign prefix
10824 ("'+'"/"'-'") is handled by inserting the padding *after* the sign
10825 character rather than before. The original string is returned if
10826 *width* is less than or equal to "len(s)".
10827
10828 For example:
10829
10830 >>> "42".zfill(5)
10831 '00042'
10832 >>> "-42".zfill(5)
10833 '-0042'
10834
10835 See also "rjust()".
10836 ''',
10837 'strings': '''String and Bytes literals
10838 *************************
10839
10840 String literals are text enclosed in single quotes ("'") or double
10841 quotes ("""). For example:
10842
10843 "spam"
10844 'eggs'
10845
10846 The quote used to start the literal also terminates it, so a string
10847 literal can only contain the other quote (except with escape
10848 sequences, see below). For example:
10849
10850 'Say "Hello", please.'
10851 "Don't do that!"
10852
10853 Except for this limitation, the choice of quote character ("'" or """)
10854 does not affect how the literal is parsed.
10855
10856 Inside a string literal, the backslash ("\\") character introduces an
10857 *escape sequence*, which has special meaning depending on the
10858 character after the backslash. For example, "\\"" denotes the double
10859 quote character, and does *not* end the string:
10860
10861 >>> print("Say \\"Hello\\" to everyone!")
10862 Say "Hello" to everyone!
10863
10864 See escape sequences below for a full list of such sequences, and more
10865 details.
10866
10867
10868 Triple-quoted strings
10869 =====================
10870
10871 Strings can also be enclosed in matching groups of three single or
10872 double quotes. These are generally referred to as *triple-quoted
10873 strings*:
10874
10875 """This is a triple-quoted string."""
10876
10877 In triple-quoted literals, unescaped quotes are allowed (and are
10878 retained), except that three unescaped quotes in a row terminate the
10879 literal, if they are of the same kind ("'" or """) used at the start:
10880
10881 """This string has "quotes" inside."""
10882
10883 Unescaped newlines are also allowed and retained:
10884
10885 \'\'\'This triple-quoted string
10886 continues on the next line.\'\'\'
10887
10888
10889 String prefixes
10890 ===============
10891
10892 String literals can have an optional *prefix* that influences how the
10893 content of the literal is parsed, for example:
10894
10895 b"data"
10896 f'{result=}'
10897
10898 The allowed prefixes are:
10899
10900 * "b": Bytes literal
10901
10902 * "r": Raw string
10903
10904 * "f": Formatted string literal (“f-string”)
10905
10906 * "t": Template string literal (“t-string”)
10907
10908 * "u": No effect (allowed for backwards compatibility)
10909
10910 See the linked sections for details on each type.
10911
10912 Prefixes are case-insensitive (for example, ‘"B"’ works the same as
10913 ‘"b"’). The ‘"r"’ prefix can be combined with ‘"f"’, ‘"t"’ or ‘"b"’,
10914 so ‘"fr"’, ‘"rf"’, ‘"tr"’, ‘"rt"’, ‘"br"’, and ‘"rb"’ are also valid
10915 prefixes.
10916
10917 Added in version 3.3: The "'rb'" prefix of raw bytes literals has been
10918 added as a synonym of "'br'".Support for the unicode legacy literal
10919 ("u'value'") was reintroduced to simplify the maintenance of dual
10920 Python 2.x and 3.x codebases. See **PEP 414** for more information.
10921
10922
10923 Formal grammar
10924 ==============
10925
10926 String literals, except “f-strings” and “t-strings”, are described by
10927 the following lexical definitions.
10928
10929 These definitions use negative lookaheads ("!") to indicate that an
10930 ending quote ends the literal.
10931
10932 STRING: [stringprefix] (stringcontent)
10933 stringprefix: <("r" | "u" | "b" | "br" | "rb"), case-insensitive>
10934 stringcontent:
10935 | "\'\'\'" ( !"\'\'\'" longstringitem)* "\'\'\'"
10936 | '"""' ( !'"""' longstringitem)* '"""'
10937 | "'" ( !"'" stringitem)* "'"
10938 | '"' ( !'"' stringitem)* '"'
10939 stringitem: stringchar | stringescapeseq
10940 stringchar: <any source_character, except backslash and newline>
10941 longstringitem: stringitem | newline
10942 stringescapeseq: "\\" <any source_character>
10943
10944 Note that as in all lexical definitions, whitespace is significant. In
10945 particular, the prefix (if any) must be immediately followed by the
10946 starting quote.
10947
10948
10949 Escape sequences
10950 ================
10951
10952 Unless an ‘"r"’ or ‘"R"’ prefix is present, escape sequences in string
10953 and bytes literals are interpreted according to rules similar to those
10954 used by Standard C. The recognized escape sequences are:
10955
10956 +----------------------------------------------------+----------------------------------------------------+
10957 | Escape Sequence | Meaning |
10958 |====================================================|====================================================|
10959 | "\\"<newline> | Ignored end of line |
10960 +----------------------------------------------------+----------------------------------------------------+
10961 | "\\\\" | Backslash |
10962 +----------------------------------------------------+----------------------------------------------------+
10963 | "\\'" | Single quote |
10964 +----------------------------------------------------+----------------------------------------------------+
10965 | "\\"" | Double quote |
10966 +----------------------------------------------------+----------------------------------------------------+
10967 | "\\a" | ASCII Bell (BEL) |
10968 +----------------------------------------------------+----------------------------------------------------+
10969 | "\\b" | ASCII Backspace (BS) |
10970 +----------------------------------------------------+----------------------------------------------------+
10971 | "\\f" | ASCII Formfeed (FF) |
10972 +----------------------------------------------------+----------------------------------------------------+
10973 | "\\n" | ASCII Linefeed (LF) |
10974 +----------------------------------------------------+----------------------------------------------------+
10975 | "\\r" | ASCII Carriage Return (CR) |
10976 +----------------------------------------------------+----------------------------------------------------+
10977 | "\\t" | ASCII Horizontal Tab (TAB) |
10978 +----------------------------------------------------+----------------------------------------------------+
10979 | "\\v" | ASCII Vertical Tab (VT) |
10980 +----------------------------------------------------+----------------------------------------------------+
10981 | "\\*ooo*" | Octal character |
10982 +----------------------------------------------------+----------------------------------------------------+
10983 | "\\x*hh*" | Hexadecimal character |
10984 +----------------------------------------------------+----------------------------------------------------+
10985 | "\\N{*name*}" | Named Unicode character |
10986 +----------------------------------------------------+----------------------------------------------------+
10987 | "\\u*xxxx*" | Hexadecimal Unicode character |
10988 +----------------------------------------------------+----------------------------------------------------+
10989 | "\\U*xxxxxxxx*" | Hexadecimal Unicode character |
10990 +----------------------------------------------------+----------------------------------------------------+
10991
10992
10993 Ignored end of line
10994 -------------------
10995
10996 A backslash can be added at the end of a line to ignore the newline:
10997
10998 >>> 'This string will not include \\
10999 ... backslashes or newline characters.'
11000 'This string will not include backslashes or newline characters.'
11001
11002 The same result can be achieved using triple-quoted strings, or
11003 parentheses and string literal concatenation.
11004
11005
11006 Escaped characters
11007 ------------------
11008
11009 To include a backslash in a non-raw Python string literal, it must be
11010 doubled. The "\\\\" escape sequence denotes a single backslash
11011 character:
11012
11013 >>> print('C:\\\\Program Files')
11014 C:\\Program Files
11015
11016 Similarly, the "\\'" and "\\"" sequences denote the single and double
11017 quote character, respectively:
11018
11019 >>> print('\\' and \\"')
11020 ' and "
11021
11022
11023 Octal character
11024 ---------------
11025
11026 The sequence "\\*ooo*" denotes a *character* with the octal (base 8)
11027 value *ooo*:
11028
11029 >>> '\\120'
11030 'P'
11031
11032 Up to three octal digits (0 through 7) are accepted.
11033
11034 In a bytes literal, *character* means a *byte* with the given value.
11035 In a string literal, it means a Unicode character with the given
11036 value.
11037
11038 Changed in version 3.11: Octal escapes with value larger than "0o377"
11039 (255) produce a "DeprecationWarning".
11040
11041 Changed in version 3.12: Octal escapes with value larger than "0o377"
11042 (255) produce a "SyntaxWarning". In a future Python version they will
11043 raise a "SyntaxError".
11044
11045
11046 Hexadecimal character
11047 ---------------------
11048
11049 The sequence "\\x*hh*" denotes a *character* with the hex (base 16)
11050 value *hh*:
11051
11052 >>> '\\x50'
11053 'P'
11054
11055 Unlike in Standard C, exactly two hex digits are required.
11056
11057 In a bytes literal, *character* means a *byte* with the given value.
11058 In a string literal, it means a Unicode character with the given
11059 value.
11060
11061
11062 Named Unicode character
11063 -----------------------
11064
11065 The sequence "\\N{*name*}" denotes a Unicode character with the given
11066 *name*:
11067
11068 >>> '\\N{LATIN CAPITAL LETTER P}'
11069 'P'
11070 >>> '\\N{SNAKE}'
11071 '🐍'
11072
11073 This sequence cannot appear in bytes literals.
11074
11075 Changed in version 3.3: Support for name aliases has been added.
11076
11077
11078 Hexadecimal Unicode characters
11079 ------------------------------
11080
11081 These sequences "\\u*xxxx*" and "\\U*xxxxxxxx*" denote the Unicode
11082 character with the given hex (base 16) value. Exactly four digits are
11083 required for "\\u"; exactly eight digits are required for "\\U". The
11084 latter can encode any Unicode character.
11085
11086 >>> '\\u1234'
11087 'ሴ'
11088 >>> '\\U0001f40d'
11089 '🐍'
11090
11091 These sequences cannot appear in bytes literals.
11092
11093
11094 Unrecognized escape sequences
11095 -----------------------------
11096
11097 Unlike in Standard C, all unrecognized escape sequences are left in
11098 the string unchanged, that is, *the backslash is left in the result*:
11099
11100 >>> print('\\q')
11101 \\q
11102 >>> list('\\q')
11103 ['\\\\', 'q']
11104
11105 Note that for bytes literals, the escape sequences only recognized in
11106 string literals ("\\N...", "\\u...", "\\U...") fall into the category of
11107 unrecognized escapes.
11108
11109 Changed in version 3.6: Unrecognized escape sequences produce a
11110 "DeprecationWarning".
11111
11112 Changed in version 3.12: Unrecognized escape sequences produce a
11113 "SyntaxWarning". In a future Python version they will raise a
11114 "SyntaxError".
11115
11116
11117 Bytes literals
11118 ==============
11119
11120 *Bytes literals* are always prefixed with ‘"b"’ or ‘"B"’; they produce
11121 an instance of the "bytes" type instead of the "str" type. They may
11122 only contain ASCII characters; bytes with a numeric value of 128 or
11123 greater must be expressed with escape sequences (typically Hexadecimal
11124 character or Octal character):
11125
11126 >>> b'\\x89PNG\\r\\n\\x1a\\n'
11127 b'\\x89PNG\\r\\n\\x1a\\n'
11128 >>> list(b'\\x89PNG\\r\\n\\x1a\\n')
11129 [137, 80, 78, 71, 13, 10, 26, 10]
11130
11131 Similarly, a zero byte must be expressed using an escape sequence
11132 (typically "\\0" or "\\x00").
11133
11134
11135 Raw string literals
11136 ===================
11137
11138 Both string and bytes literals may optionally be prefixed with a
11139 letter ‘"r"’ or ‘"R"’; such constructs are called *raw string
11140 literals* and *raw bytes literals* respectively and treat backslashes
11141 as literal characters. As a result, in raw string literals, escape
11142 sequences are not treated specially:
11143
11144 >>> r'\\d{4}-\\d{2}-\\d{2}'
11145 '\\\\d{4}-\\\\d{2}-\\\\d{2}'
11146
11147 Even in a raw literal, quotes can be escaped with a backslash, but the
11148 backslash remains in the result; for example, "r"\\""" is a valid
11149 string literal consisting of two characters: a backslash and a double
11150 quote; "r"\\"" is not a valid string literal (even a raw string cannot
11151 end in an odd number of backslashes). Specifically, *a raw literal
11152 cannot end in a single backslash* (since the backslash would escape
11153 the following quote character). Note also that a single backslash
11154 followed by a newline is interpreted as those two characters as part
11155 of the literal, *not* as a line continuation.
11156
11157
11158 f-strings
11159 =========
11160
11161 Added in version 3.6.
11162
11163 Changed in version 3.7: The "await" and "async for" can be used in
11164 expressions within f-strings.
11165
11166 Changed in version 3.8: Added the debug specifier ("=")
11167
11168 Changed in version 3.12: Many restrictions on expressions within
11169 f-strings have been removed. Notably, nested strings, comments, and
11170 backslashes are now permitted.
11171
11172 A *formatted string literal* or *f-string* is a string literal that is
11173 prefixed with ‘"f"’ or ‘"F"’. Unlike other string literals, f-strings
11174 do not have a constant value. They may contain *replacement fields*
11175 delimited by curly braces "{}". Replacement fields contain expressions
11176 which are evaluated at run time. For example:
11177
11178 >>> who = 'nobody'
11179 >>> nationality = 'Spanish'
11180 >>> f'{who.title()} expects the {nationality} Inquisition!'
11181 'Nobody expects the Spanish Inquisition!'
11182
11183 Any doubled curly braces ("{{" or "}}") outside replacement fields are
11184 replaced with the corresponding single curly brace:
11185
11186 >>> print(f'{{...}}')
11187 {...}
11188
11189 Other characters outside replacement fields are treated like in
11190 ordinary string literals. This means that escape sequences are decoded
11191 (except when a literal is also marked as a raw string), and newlines
11192 are possible in triple-quoted f-strings:
11193
11194 >>> name = 'Galahad'
11195 >>> favorite_color = 'blue'
11196 >>> print(f'{name}:\\t{favorite_color}')
11197 Galahad: blue
11198 >>> print(rf"C:\\Users\\{name}")
11199 C:\\Users\\Galahad
11200 >>> print(f\'\'\'Three shall be the number of the counting
11201 ... and the number of the counting shall be three.\'\'\')
11202 Three shall be the number of the counting
11203 and the number of the counting shall be three.
11204
11205 Expressions in formatted string literals are treated like regular
11206 Python expressions. Each expression is evaluated in the context where
11207 the formatted string literal appears, in order from left to right. An
11208 empty expression is not allowed, and both "lambda" and assignment
11209 expressions ":=" must be surrounded by explicit parentheses:
11210
11211 >>> f'{(half := 1/2)}, {half * 42}'
11212 '0.5, 21.0'
11213
11214 Reusing the outer f-string quoting type inside a replacement field is
11215 permitted:
11216
11217 >>> a = dict(x=2)
11218 >>> f"abc {a["x"]} def"
11219 'abc 2 def'
11220
11221 Backslashes are also allowed in replacement fields and are evaluated
11222 the same way as in any other context:
11223
11224 >>> a = ["a", "b", "c"]
11225 >>> print(f"List a contains:\\n{"\\n".join(a)}")
11226 List a contains:
11227 a
11228 b
11229 c
11230
11231 It is possible to nest f-strings:
11232
11233 >>> name = 'world'
11234 >>> f'Repeated:{f' hello {name}' * 3}'
11235 'Repeated: hello world hello world hello world'
11236
11237 Portable Python programs should not use more than 5 levels of nesting.
11238
11239 **CPython implementation detail:** CPython does not limit nesting of
11240 f-strings.
11241
11242 Replacement expressions can contain newlines in both single-quoted and
11243 triple-quoted f-strings and they can contain comments. Everything that
11244 comes after a "#" inside a replacement field is a comment (even
11245 closing braces and quotes). This means that replacement fields with
11246 comments must be closed in a different line:
11247
11248 >>> a = 2
11249 >>> f"abc{a # This comment }" continues until the end of the line
11250 ... + 3}"
11251 'abc5'
11252
11253 After the expression, replacement fields may optionally contain:
11254
11255 * a *debug specifier* – an equal sign ("="), optionally surrounded by
11256 whitespace on one or both sides;
11257
11258 * a *conversion specifier* – "!s", "!r" or "!a"; and/or
11259
11260 * a *format specifier* prefixed with a colon (":").
11261
11262 See the Standard Library section on f-strings for details on how these
11263 fields are evaluated.
11264
11265 As that section explains, *format specifiers* are passed as the second
11266 argument to the "format()" function to format a replacement field
11267 value. For example, they can be used to specify a field width and
11268 padding characters using the Format Specification Mini-Language:
11269
11270 >>> number = 14.3
11271 >>> f'{number:20.7f}'
11272 ' 14.3000000'
11273
11274 Top-level format specifiers may include nested replacement fields:
11275
11276 >>> field_size = 20
11277 >>> precision = 7
11278 >>> f'{number:{field_size}.{precision}f}'
11279 ' 14.3000000'
11280
11281 These nested fields may include their own conversion fields and format
11282 specifiers:
11283
11284 >>> number = 3
11285 >>> f'{number:{field_size}}'
11286 ' 3'
11287 >>> f'{number:{field_size:05}}'
11288 '00000000000000000003'
11289
11290 However, these nested fields may not include more deeply nested
11291 replacement fields.
11292
11293 Formatted string literals cannot be used as *docstrings*, even if they
11294 do not include expressions:
11295
11296 >>> def foo():
11297 ... f"Not a docstring"
11298 ...
11299 >>> print(foo.__doc__)
11300 None
11301
11302 See also:
11303
11304 * **PEP 498** – Literal String Interpolation
11305
11306 * **PEP 701** – Syntactic formalization of f-strings
11307
11308 * "str.format()", which uses a related format string mechanism.
11309
11310
11311 t-strings
11312 =========
11313
11314 Added in version 3.14.
11315
11316 A *template string literal* or *t-string* is a string literal that is
11317 prefixed with ‘"t"’ or ‘"T"’. These strings follow the same syntax
11318 rules as formatted string literals. For differences in evaluation
11319 rules, see the Standard Library section on t-strings
11320
11321
11322 Formal grammar for f-strings
11323 ============================
11324
11325 F-strings are handled partly by the *lexical analyzer*, which produces
11326 the tokens "FSTRING_START", "FSTRING_MIDDLE" and "FSTRING_END", and
11327 partly by the parser, which handles expressions in the replacement
11328 field. The exact way the work is split is a CPython implementation
11329 detail.
11330
11331 Correspondingly, the f-string grammar is a mix of lexical and
11332 syntactic definitions.
11333
11334 Whitespace is significant in these situations:
11335
11336 * There may be no whitespace in "FSTRING_START" (between the prefix
11337 and quote).
11338
11339 * Whitespace in "FSTRING_MIDDLE" is part of the literal string
11340 contents.
11341
11342 * In "fstring_replacement_field", if "f_debug_specifier" is present,
11343 all whitespace after the opening brace until the
11344 "f_debug_specifier", as well as whitespace immediately following
11345 "f_debug_specifier", is retained as part of the expression.
11346
11347 **CPython implementation detail:** The expression is not handled in
11348 the tokenization phase; it is retrieved from the source code using
11349 locations of the "{" token and the token after "=".
11350
11351 The "FSTRING_MIDDLE" definition uses negative lookaheads ("!") to
11352 indicate special characters (backslash, newline, "{", "}") and
11353 sequences ("f_quote").
11354
11355 fstring: FSTRING_START fstring_middle* FSTRING_END
11356
11357 FSTRING_START: fstringprefix ("'" | '"' | "\'\'\'" | '"""')
11358 FSTRING_END: f_quote
11359 fstringprefix: <("f" | "fr" | "rf"), case-insensitive>
11360 f_debug_specifier: '='
11361 f_quote: <the quote character(s) used in FSTRING_START>
11362
11363 fstring_middle:
11364 | fstring_replacement_field
11365 | FSTRING_MIDDLE
11366 FSTRING_MIDDLE:
11367 | (!"\\" !newline !'{' !'}' !f_quote) source_character
11368 | stringescapeseq
11369 | "{{"
11370 | "}}"
11371 | <newline, in triple-quoted f-strings only>
11372 fstring_replacement_field:
11373 | '{' f_expression [f_debug_specifier] [fstring_conversion]
11374 [fstring_full_format_spec] '}'
11375 fstring_conversion:
11376 | "!" ("s" | "r" | "a")
11377 fstring_full_format_spec:
11378 | ':' fstring_format_spec*
11379 fstring_format_spec:
11380 | FSTRING_MIDDLE
11381 | fstring_replacement_field
11382 f_expression:
11383 | ','.(conditional_expression | "*" or_expr)+ [","]
11384 | yield_expression
11385
11386 Note:
11387
11388 In the above grammar snippet, the "f_quote" and "FSTRING_MIDDLE"
11389 rules are context-sensitive – they depend on the contents of
11390 "FSTRING_START" of the nearest enclosing "fstring".Constructing a
11391 more traditional formal grammar from this template is left as an
11392 exercise for the reader.
11393
11394 The grammar for t-strings is identical to the one for f-strings, with
11395 *t* instead of *f* at the beginning of rule and token names and in the
11396 prefix.
11397
11398 tstring: TSTRING_START tstring_middle* TSTRING_END
11399
11400 <rest of the t-string grammar is omitted; see above>
11401 ''',
11402 'subscriptions': r'''Subscriptions and slicings
11403 **************************
11404
11405 The *subscription* syntax is usually used for selecting an element
11406 from a container – for example, to get a value from a "dict":
11407
11408 >>> digits_by_name = {'one': 1, 'two': 2}
11409 >>> digits_by_name['two'] # Subscripting a dictionary using the key 'two'
11410 2
11411
11412 In the subscription syntax, the object being subscribed – a primary –
11413 is followed by a *subscript* in square brackets. In the simplest case,
11414 the subscript is a single expression.
11415
11416 Depending on the type of the object being subscribed, the subscript is
11417 sometimes called a *key* (for mappings), *index* (for sequences), or
11418 *type argument* (for *generic types*). Syntactically, these are all
11419 equivalent:
11420
11421 >>> colors = ['red', 'blue', 'green', 'black']
11422 >>> colors[3] # Subscripting a list using the index 3
11423 'black'
11424
11425 >>> list[str] # Parameterizing the list type using the type argument str
11426 list[str]
11427
11428 At runtime, the interpreter will evaluate the primary and the
11429 subscript, and call the primary’s "__getitem__()" or
11430 "__class_getitem__()" *special method* with the subscript as argument.
11431 For more details on which of these methods is called, see
11432 __class_getitem__ versus __getitem__.
11433
11434 To show how subscription works, we can define a custom object that
11435 implements "__getitem__()" and prints out the value of the subscript:
11436
11437 >>> class SubscriptionDemo:
11438 ... def __getitem__(self, key):
11439 ... print(f'subscripted with: {key!r}')
11440 ...
11441 >>> demo = SubscriptionDemo()
11442 >>> demo[1]
11443 subscripted with: 1
11444 >>> demo['a' * 3]
11445 subscripted with: 'aaa'
11446
11447 See "__getitem__()" documentation for how built-in types handle
11448 subscription.
11449
11450 Subscriptions may also be used as targets in assignment or deletion
11451 statements. In these cases, the interpreter will call the subscripted
11452 object’s "__setitem__()" or "__delitem__()" *special method*,
11453 respectively, instead of "__getitem__()".
11454
11455 >>> colors = ['red', 'blue', 'green', 'black']
11456 >>> colors[3] = 'white' # Setting item at index
11457 >>> colors
11458 ['red', 'blue', 'green', 'white']
11459 >>> del colors[3] # Deleting item at index 3
11460 >>> colors
11461 ['red', 'blue', 'green']
11462
11463 All advanced forms of *subscript* documented in the following sections
11464 are also usable for assignment and deletion.
11465
11466
11467 Slicings
11468 ========
11469
11470 A more advanced form of subscription, *slicing*, is commonly used to
11471 extract a portion of a sequence. In this form, the subscript is a
11472 *slice*: up to three expressions separated by colons. Any of the
11473 expressions may be omitted, but a slice must contain at least one
11474 colon:
11475
11476 >>> number_names = ['zero', 'one', 'two', 'three', 'four', 'five']
11477 >>> number_names[1:3]
11478 ['one', 'two']
11479 >>> number_names[1:]
11480 ['one', 'two', 'three', 'four', 'five']
11481 >>> number_names[:3]
11482 ['zero', 'one', 'two']
11483 >>> number_names[:]
11484 ['zero', 'one', 'two', 'three', 'four', 'five']
11485 >>> number_names[::2]
11486 ['zero', 'two', 'four']
11487 >>> number_names[:-3]
11488 ['zero', 'one', 'two']
11489 >>> del number_names[4:]
11490 >>> number_names
11491 ['zero', 'one', 'two', 'three']
11492
11493 When a slice is evaluated, the interpreter constructs a "slice" object
11494 whose "start", "stop" and "step" attributes, respectively, are the
11495 results of the expressions between the colons. Any missing expression
11496 evaluates to "None". This "slice" object is then passed to the
11497 "__getitem__()" or "__class_getitem__()" *special method*, as above.
11498
11499 # continuing with the SubscriptionDemo instance defined above:
11500 >>> demo[2:3]
11501 subscripted with: slice(2, 3, None)
11502 >>> demo[::'spam']
11503 subscripted with: slice(None, None, 'spam')
11504
11505
11506 Comma-separated subscripts
11507 ==========================
11508
11509 The subscript can also be given as two or more comma-separated
11510 expressions or slices:
11511
11512 # continuing with the SubscriptionDemo instance defined above:
11513 >>> demo[1, 2, 3]
11514 subscripted with: (1, 2, 3)
11515 >>> demo[1:2, 3]
11516 subscripted with: (slice(1, 2, None), 3)
11517
11518 This form is commonly used with numerical libraries for slicing multi-
11519 dimensional data. In this case, the interpreter constructs a "tuple"
11520 of the results of the expressions or slices, and passes this tuple to
11521 the "__getitem__()" or "__class_getitem__()" *special method*, as
11522 above.
11523
11524 The subscript may also be given as a single expression or slice
11525 followed by a comma, to specify a one-element tuple:
11526
11527 >>> demo['spam',]
11528 subscripted with: ('spam',)
11529
11530
11531 “Starred” subscriptions
11532 =======================
11533
11534 Added in version 3.11: Expressions in *tuple_slices* may be starred.
11535 See **PEP 646**.
11536
11537 The subscript can also contain a starred expression. In this case, the
11538 interpreter unpacks the result into a tuple, and passes this tuple to
11539 "__getitem__()" or "__class_getitem__()":
11540
11541 # continuing with the SubscriptionDemo instance defined above:
11542 >>> demo[*range(10)]
11543 subscripted with: (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
11544
11545 Starred expressions may be combined with comma-separated expressions
11546 and slices:
11547
11548 >>> demo['a', 'b', *range(3), 'c']
11549 subscripted with: ('a', 'b', 0, 1, 2, 'c')
11550
11551
11552 Formal subscription grammar
11553 ===========================
11554
11555 subscription: primary '[' subscript ']'
11556 subscript: single_subscript | tuple_subscript
11557 single_subscript: proper_slice | assignment_expression
11558 proper_slice: [expression] ":" [expression] [ ":" [expression] ]
11559 tuple_subscript: ','.(single_subscript | starred_expression)+ [',']
11560
11561 Recall that the "|" operator denotes ordered choice. Specifically, in
11562 "subscript", if both alternatives would match, the first
11563 ("single_subscript") has priority.
11564 ''',
11565 'truth': r'''Truth Value Testing
11566 *******************
11567
11568 Any object can be tested for truth value, for use in an "if" or
11569 "while" condition or as operand of the Boolean operations below.
11570
11571 By default, an object is considered true unless its class defines
11572 either a "__bool__()" method that returns "False" or a "__len__()"
11573 method that returns zero, when called with the object. [1] If one of
11574 the methods raises an exception when called, the exception is
11575 propagated and the object does not have a truth value (for example,
11576 "NotImplemented"). Here are most of the built-in objects considered
11577 false:
11578
11579 * constants defined to be false: "None" and "False"
11580
11581 * zero of any numeric type: "0", "0.0", "0j", "Decimal(0)",
11582 "Fraction(0, 1)"
11583
11584 * empty sequences and collections: "''", "()", "[]", "{}", "set()",
11585 "range(0)"
11586
11587 Operations and built-in functions that have a Boolean result always
11588 return "0" or "False" for false and "1" or "True" for true, unless
11589 otherwise stated. (Important exception: the Boolean operations "or"
11590 and "and" always return one of their operands.)
11591 ''',
11592 'try': r'''The "try" statement
11593 *******************
11594
11595 The "try" statement specifies exception handlers and/or cleanup code
11596 for a group of statements:
11597
11598 try_stmt: try1_stmt | try2_stmt | try3_stmt
11599 try1_stmt: "try" ":" suite
11600 ("except" [expression ["as" identifier]] ":" suite)+
11601 ["else" ":" suite]
11602 ["finally" ":" suite]
11603 try2_stmt: "try" ":" suite
11604 ("except" "*" expression ["as" identifier] ":" suite)+
11605 ["else" ":" suite]
11606 ["finally" ":" suite]
11607 try3_stmt: "try" ":" suite
11608 "finally" ":" suite
11609
11610 Additional information on exceptions can be found in section
11611 Exceptions, and information on using the "raise" statement to generate
11612 exceptions may be found in section The raise statement.
11613
11614 Changed in version 3.14: Support for optionally dropping grouping
11615 parentheses when using multiple exception types. See **PEP 758**.
11616
11617
11618 "except" clause
11619 ===============
11620
11621 The "except" clause(s) specify one or more exception handlers. When no
11622 exception occurs in the "try" clause, no exception handler is
11623 executed. When an exception occurs in the "try" suite, a search for an
11624 exception handler is started. This search inspects the "except"
11625 clauses in turn until one is found that matches the exception. An
11626 expression-less "except" clause, if present, must be last; it matches
11627 any exception.
11628
11629 For an "except" clause with an expression, the expression must
11630 evaluate to an exception type or a tuple of exception types.
11631 Parentheses can be dropped if multiple exception types are provided
11632 and the "as" clause is not used. The raised exception matches an
11633 "except" clause whose expression evaluates to the class or a *non-
11634 virtual base class* of the exception object, or to a tuple that
11635 contains such a class.
11636
11637 If no "except" clause matches the exception, the search for an
11638 exception handler continues in the surrounding code and on the
11639 invocation stack. [1]
11640
11641 If the evaluation of an expression in the header of an "except" clause
11642 raises an exception, the original search for a handler is canceled and
11643 a search starts for the new exception in the surrounding code and on
11644 the call stack (it is treated as if the entire "try" statement raised
11645 the exception).
11646
11647 When a matching "except" clause is found, the exception is assigned to
11648 the target specified after the "as" keyword in that "except" clause,
11649 if present, and the "except" clause’s suite is executed. All "except"
11650 clauses must have an executable block. When the end of this block is
11651 reached, execution continues normally after the entire "try"
11652 statement. (This means that if two nested handlers exist for the same
11653 exception, and the exception occurs in the "try" clause of the inner
11654 handler, the outer handler will not handle the exception.)
11655
11656 When an exception has been assigned using "as target", it is cleared
11657 at the end of the "except" clause. This is as if
11658
11659 except E as N:
11660 foo
11661
11662 was translated to
11663
11664 except E as N:
11665 try:
11666 foo
11667 finally:
11668 del N
11669
11670 This means the exception must be assigned to a different name to be
11671 able to refer to it after the "except" clause. Exceptions are cleared
11672 because with the traceback attached to them, they form a reference
11673 cycle with the stack frame, keeping all locals in that frame alive
11674 until the next garbage collection occurs.
11675
11676 Before an "except" clause’s suite is executed, the exception is stored
11677 in the "sys" module, where it can be accessed from within the body of
11678 the "except" clause by calling "sys.exception()". When leaving an
11679 exception handler, the exception stored in the "sys" module is reset
11680 to its previous value:
11681
11682 >>> print(sys.exception())
11683 None
11684 >>> try:
11685 ... raise TypeError
11686 ... except:
11687 ... print(repr(sys.exception()))
11688 ... try:
11689 ... raise ValueError
11690 ... except:
11691 ... print(repr(sys.exception()))
11692 ... print(repr(sys.exception()))
11693 ...
11694 TypeError()
11695 ValueError()
11696 TypeError()
11697 >>> print(sys.exception())
11698 None
11699
11700
11701 "except*" clause
11702 ================
11703
11704 The "except*" clause(s) specify one or more handlers for groups of
11705 exceptions ("BaseExceptionGroup" instances). A "try" statement can
11706 have either "except" or "except*" clauses, but not both. The exception
11707 type for matching is mandatory in the case of "except*", so "except*:"
11708 is a syntax error. The type is interpreted as in the case of "except",
11709 but matching is performed on the exceptions contained in the group
11710 that is being handled. An "TypeError" is raised if a matching type is
11711 a subclass of "BaseExceptionGroup", because that would have ambiguous
11712 semantics.
11713
11714 When an exception group is raised in the try block, each "except*"
11715 clause splits (see "split()") it into the subgroups of matching and
11716 non-matching exceptions. If the matching subgroup is not empty, it
11717 becomes the handled exception (the value returned from
11718 "sys.exception()") and assigned to the target of the "except*" clause
11719 (if there is one). Then, the body of the "except*" clause executes. If
11720 the non-matching subgroup is not empty, it is processed by the next
11721 "except*" in the same manner. This continues until all exceptions in
11722 the group have been matched, or the last "except*" clause has run.
11723
11724 After all "except*" clauses execute, the group of unhandled exceptions
11725 is merged with any exceptions that were raised or re-raised from
11726 within "except*" clauses. This merged exception group propagates on.:
11727
11728 >>> try:
11729 ... raise ExceptionGroup("eg",
11730 ... [ValueError(1), TypeError(2), OSError(3), OSError(4)])
11731 ... except* TypeError as e:
11732 ... print(f'caught {type(e)} with nested {e.exceptions}')
11733 ... except* OSError as e:
11734 ... print(f'caught {type(e)} with nested {e.exceptions}')
11735 ...
11736 caught <class 'ExceptionGroup'> with nested (TypeError(2),)
11737 caught <class 'ExceptionGroup'> with nested (OSError(3), OSError(4))
11738 + Exception Group Traceback (most recent call last):
11739 | File "<doctest default[0]>", line 2, in <module>
11740 | raise ExceptionGroup("eg",
11741 | [ValueError(1), TypeError(2), OSError(3), OSError(4)])
11742 | ExceptionGroup: eg (1 sub-exception)
11743 +-+---------------- 1 ----------------
11744 | ValueError: 1
11745 +------------------------------------
11746
11747 If the exception raised from the "try" block is not an exception group
11748 and its type matches one of the "except*" clauses, it is caught and
11749 wrapped by an exception group with an empty message string. This
11750 ensures that the type of the target "e" is consistently
11751 "BaseExceptionGroup":
11752
11753 >>> try:
11754 ... raise BlockingIOError
11755 ... except* BlockingIOError as e:
11756 ... print(repr(e))
11757 ...
11758 ExceptionGroup('', (BlockingIOError(),))
11759
11760 "break", "continue" and "return" cannot appear in an "except*" clause.
11761
11762
11763 "else" clause
11764 =============
11765
11766 The optional "else" clause is executed if the control flow leaves the
11767 "try" suite, no exception was raised, and no "return", "continue", or
11768 "break" statement was executed. Exceptions in the "else" clause are
11769 not handled by the preceding "except" clauses.
11770
11771
11772 "finally" clause
11773 ================
11774
11775 If "finally" is present, it specifies a ‘cleanup’ handler. The "try"
11776 clause is executed, including any "except" and "else" clauses. If an
11777 exception occurs in any of the clauses and is not handled, the
11778 exception is temporarily saved. The "finally" clause is executed. If
11779 there is a saved exception it is re-raised at the end of the "finally"
11780 clause. If the "finally" clause raises another exception, the saved
11781 exception is set as the context of the new exception. If the "finally"
11782 clause executes a "return", "break" or "continue" statement, the saved
11783 exception is discarded. For example, this function returns 42.
11784
11785 def f():
11786 try:
11787 1/0
11788 finally:
11789 return 42
11790
11791 The exception information is not available to the program during
11792 execution of the "finally" clause.
11793
11794 When a "return", "break" or "continue" statement is executed in the
11795 "try" suite of a "try"…"finally" statement, the "finally" clause is
11796 also executed ‘on the way out.’
11797
11798 The return value of a function is determined by the last "return"
11799 statement executed. Since the "finally" clause always executes, a
11800 "return" statement executed in the "finally" clause will always be the
11801 last one executed. The following function returns ‘finally’.
11802
11803 def foo():
11804 try:
11805 return 'try'
11806 finally:
11807 return 'finally'
11808
11809 Changed in version 3.8: Prior to Python 3.8, a "continue" statement
11810 was illegal in the "finally" clause due to a problem with the
11811 implementation.
11812
11813 Changed in version 3.14: The compiler emits a "SyntaxWarning" when a
11814 "return", "break" or "continue" appears in a "finally" block (see
11815 **PEP 765**).
11816 ''',
11817 'types': r'''The standard type hierarchy
11818 ***************************
11819
11820 Below is a list of the types that are built into Python. Extension
11821 modules (written in C, Java, or other languages, depending on the
11822 implementation) can define additional types. Future versions of
11823 Python may add types to the type hierarchy (e.g., rational numbers,
11824 efficiently stored arrays of integers, etc.), although such additions
11825 will often be provided via the standard library instead.
11826
11827 Some of the type descriptions below contain a paragraph listing
11828 ‘special attributes.’ These are attributes that provide access to the
11829 implementation and are not intended for general use. Their definition
11830 may change in the future.
11831
11832
11833 None
11834 ====
11835
11836 This type has a single value. There is a single object with this
11837 value. This object is accessed through the built-in name "None". It is
11838 used to signify the absence of a value in many situations, e.g., it is
11839 returned from functions that don’t explicitly return anything. Its
11840 truth value is false.
11841
11842
11843 NotImplemented
11844 ==============
11845
11846 This type has a single value. There is a single object with this
11847 value. This object is accessed through the built-in name
11848 "NotImplemented". Numeric methods and rich comparison methods should
11849 return this value if they do not implement the operation for the
11850 operands provided. (The interpreter will then try the reflected
11851 operation, or some other fallback, depending on the operator.) It
11852 should not be evaluated in a boolean context.
11853
11854 See Implementing the arithmetic operations for more details.
11855
11856 Changed in version 3.9: Evaluating "NotImplemented" in a boolean
11857 context was deprecated.
11858
11859 Changed in version 3.14: Evaluating "NotImplemented" in a boolean
11860 context now raises a "TypeError". It previously evaluated to "True"
11861 and emitted a "DeprecationWarning" since Python 3.9.
11862
11863
11864 Ellipsis
11865 ========
11866
11867 This type has a single value. There is a single object with this
11868 value. This object is accessed through the literal "..." or the built-
11869 in name "Ellipsis". Its truth value is true.
11870
11871
11872 "numbers.Number"
11873 ================
11874
11875 These are created by numeric literals and returned as results by
11876 arithmetic operators and arithmetic built-in functions. Numeric
11877 objects are immutable; once created their value never changes. Python
11878 numbers are of course strongly related to mathematical numbers, but
11879 subject to the limitations of numerical representation in computers.
11880
11881 The string representations of the numeric classes, computed by
11882 "__repr__()" and "__str__()", have the following properties:
11883
11884 * They are valid numeric literals which, when passed to their class
11885 constructor, produce an object having the value of the original
11886 numeric.
11887
11888 * The representation is in base 10, when possible.
11889
11890 * Leading zeros, possibly excepting a single zero before a decimal
11891 point, are not shown.
11892
11893 * Trailing zeros, possibly excepting a single zero after a decimal
11894 point, are not shown.
11895
11896 * A sign is shown only when the number is negative.
11897
11898 Python distinguishes between integers, floating-point numbers, and
11899 complex numbers:
11900
11901
11902 "numbers.Integral"
11903 ------------------
11904
11905 These represent elements from the mathematical set of integers
11906 (positive and negative).
11907
11908 Note:
11909
11910 The rules for integer representation are intended to give the most
11911 meaningful interpretation of shift and mask operations involving
11912 negative integers.
11913
11914 There are two types of integers:
11915
11916 Integers ("int")
11917 These represent numbers in an unlimited range, subject to available
11918 (virtual) memory only. For the purpose of shift and mask
11919 operations, a binary representation is assumed, and negative
11920 numbers are represented in a variant of 2’s complement which gives
11921 the illusion of an infinite string of sign bits extending to the
11922 left.
11923
11924 Booleans ("bool")
11925 These represent the truth values False and True. The two objects
11926 representing the values "False" and "True" are the only Boolean
11927 objects. The Boolean type is a subtype of the integer type, and
11928 Boolean values behave like the values 0 and 1, respectively, in
11929 almost all contexts, the exception being that when converted to a
11930 string, the strings ""False"" or ""True"" are returned,
11931 respectively.
11932
11933
11934 "numbers.Real" ("float")
11935 ------------------------
11936
11937 These represent machine-level double precision floating-point numbers.
11938 You are at the mercy of the underlying machine architecture (and C or
11939 Java implementation) for the accepted range and handling of overflow.
11940 Python does not support single-precision floating-point numbers; the
11941 savings in processor and memory usage that are usually the reason for
11942 using these are dwarfed by the overhead of using objects in Python, so
11943 there is no reason to complicate the language with two kinds of
11944 floating-point numbers.
11945
11946
11947 "numbers.Complex" ("complex")
11948 -----------------------------
11949
11950 These represent complex numbers as a pair of machine-level double
11951 precision floating-point numbers. The same caveats apply as for
11952 floating-point numbers. The real and imaginary parts of a complex
11953 number "z" can be retrieved through the read-only attributes "z.real"
11954 and "z.imag".
11955
11956
11957 Sequences
11958 =========
11959
11960 These represent finite ordered sets indexed by non-negative numbers.
11961 The built-in function "len()" returns the number of items of a
11962 sequence. When the length of a sequence is *n*, the index set contains
11963 the numbers 0, 1, …, *n*-1. Item *i* of sequence *a* is selected by
11964 "a[i]". Some sequences, including built-in sequences, interpret
11965 negative subscripts by adding the sequence length. For example,
11966 "a[-2]" equals "a[n-2]", the second to last item of sequence a with
11967 length "n".
11968
11969 The resulting value must be a nonnegative integer less than the number
11970 of items in the sequence. If it is not, an "IndexError" is raised.
11971
11972 Sequences also support slicing: "a[start:stop]" selects all items with
11973 index *k* such that *start* "<=" *k* "<" *stop*. When used as an
11974 expression, a slice is a sequence of the same type. The comment above
11975 about negative subscripts also applies to negative slice positions.
11976 Note that no error is raised if a slice position is less than zero or
11977 larger than the length of the sequence.
11978
11979 If *start* is missing or "None", slicing behaves as if *start* was
11980 zero. If *stop* is missing or "None", slicing behaves as if *stop* was
11981 equal to the length of the sequence.
11982
11983 Some sequences also support “extended slicing” with a third “step”
11984 parameter: "a[i:j:k]" selects all items of *a* with index *x* where "x
11985 = i + n*k", *n* ">=" "0" and *i* "<=" *x* "<" *j*.
11986
11987 Sequences are distinguished according to their mutability:
11988
11989
11990 Immutable sequences
11991 -------------------
11992
11993 An object of an immutable sequence type cannot change once it is
11994 created. (If the object contains references to other objects, these
11995 other objects may be mutable and may be changed; however, the
11996 collection of objects directly referenced by an immutable object
11997 cannot change.)
11998
11999 The following types are immutable sequences:
12000
12001 Strings
12002 A string ("str") is a sequence of values that represent
12003 *characters*, or more formally, *Unicode code points*. All the code
12004 points in the range "0" to "0x10FFFF" can be represented in a
12005 string.
12006
12007 Python doesn’t have a dedicated *character* type. Instead, every
12008 code point in the string is represented as a string object with
12009 length "1".
12010
12011 The built-in function "ord()" converts a code point from its string
12012 form to an integer in the range "0" to "0x10FFFF"; "chr()" converts
12013 an integer in the range "0" to "0x10FFFF" to the corresponding
12014 length "1" string object. "str.encode()" can be used to convert a
12015 "str" to "bytes" using the given text encoding, and
12016 "bytes.decode()" can be used to achieve the opposite.
12017
12018 Tuples
12019 The items of a "tuple" are arbitrary Python objects. Tuples of two
12020 or more items are formed by comma-separated lists of expressions.
12021 A tuple of one item (a ‘singleton’) can be formed by affixing a
12022 comma to an expression (an expression by itself does not create a
12023 tuple, since parentheses must be usable for grouping of
12024 expressions). An empty tuple can be formed by an empty pair of
12025 parentheses.
12026
12027 Bytes
12028 A "bytes" object is an immutable array. The items are 8-bit bytes,
12029 represented by integers in the range 0 <= x < 256. Bytes literals
12030 (like "b'abc'") and the built-in "bytes()" constructor can be used
12031 to create bytes objects. Also, bytes objects can be decoded to
12032 strings via the "decode()" method.
12033
12034
12035 Mutable sequences
12036 -----------------
12037
12038 Mutable sequences can be changed after they are created. The
12039 subscription and slicing notations can be used as the target of
12040 assignment and "del" (delete) statements.
12041
12042 Note:
12043
12044 The "collections" and "array" module provide additional examples of
12045 mutable sequence types.
12046
12047 There are currently two intrinsic mutable sequence types:
12048
12049 Lists
12050 The items of a list are arbitrary Python objects. Lists are formed
12051 by placing a comma-separated list of expressions in square
12052 brackets. (Note that there are no special cases needed to form
12053 lists of length 0 or 1.)
12054
12055 Byte Arrays
12056 A bytearray object is a mutable array. They are created by the
12057 built-in "bytearray()" constructor. Aside from being mutable (and
12058 hence unhashable), byte arrays otherwise provide the same interface
12059 and functionality as immutable "bytes" objects.
12060
12061
12062 Set types
12063 =========
12064
12065 These represent unordered, finite sets of unique, immutable objects.
12066 As such, they cannot be indexed by any subscript. However, they can be
12067 iterated over, and the built-in function "len()" returns the number of
12068 items in a set. Common uses for sets are fast membership testing,
12069 removing duplicates from a sequence, and computing mathematical
12070 operations such as intersection, union, difference, and symmetric
12071 difference.
12072
12073 For set elements, the same immutability rules apply as for dictionary
12074 keys. Note that numeric types obey the normal rules for numeric
12075 comparison: if two numbers compare equal (e.g., "1" and "1.0"), only
12076 one of them can be contained in a set.
12077
12078 There are currently two intrinsic set types:
12079
12080 Sets
12081 These represent a mutable set. They are created by the built-in
12082 "set()" constructor and can be modified afterwards by several
12083 methods, such as "add()".
12084
12085 Frozen sets
12086 These represent an immutable set. They are created by the built-in
12087 "frozenset()" constructor. As a frozenset is immutable and
12088 *hashable*, it can be used again as an element of another set, or
12089 as a dictionary key.
12090
12091
12092 Mappings
12093 ========
12094
12095 These represent finite sets of objects indexed by arbitrary index
12096 sets. The subscript notation "a[k]" selects the item indexed by "k"
12097 from the mapping "a"; this can be used in expressions and as the
12098 target of assignments or "del" statements. The built-in function
12099 "len()" returns the number of items in a mapping.
12100
12101 There is currently a single intrinsic mapping type:
12102
12103
12104 Dictionaries
12105 ------------
12106
12107 These represent finite sets of objects indexed by nearly arbitrary
12108 values. The only types of values not acceptable as keys are values
12109 containing lists or dictionaries or other mutable types that are
12110 compared by value rather than by object identity, the reason being
12111 that the efficient implementation of dictionaries requires a key’s
12112 hash value to remain constant. Numeric types used for keys obey the
12113 normal rules for numeric comparison: if two numbers compare equal
12114 (e.g., "1" and "1.0") then they can be used interchangeably to index
12115 the same dictionary entry.
12116
12117 Dictionaries preserve insertion order, meaning that keys will be
12118 produced in the same order they were added sequentially over the
12119 dictionary. Replacing an existing key does not change the order,
12120 however removing a key and re-inserting it will add it to the end
12121 instead of keeping its old place.
12122
12123 Dictionaries are mutable; they can be created by the "{}" notation
12124 (see section Dictionary displays).
12125
12126 The extension modules "dbm.ndbm" and "dbm.gnu" provide additional
12127 examples of mapping types, as does the "collections" module.
12128
12129 Changed in version 3.7: Dictionaries did not preserve insertion order
12130 in versions of Python before 3.6. In CPython 3.6, insertion order was
12131 preserved, but it was considered an implementation detail at that time
12132 rather than a language guarantee.
12133
12134
12135 Callable types
12136 ==============
12137
12138 These are the types to which the function call operation (see section
12139 Calls) can be applied:
12140
12141
12142 User-defined functions
12143 ----------------------
12144
12145 A user-defined function object is created by a function definition
12146 (see section Function definitions). It should be called with an
12147 argument list containing the same number of items as the function’s
12148 formal parameter list.
12149
12150
12151 Special read-only attributes
12152 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
12153
12154 +----------------------------------------------------+----------------------------------------------------+
12155 | Attribute | Meaning |
12156 |====================================================|====================================================|
12157 | function.__builtins__ | A reference to the "dictionary" that holds the |
12158 | | function’s builtins namespace. Added in version |
12159 | | 3.10. |
12160 +----------------------------------------------------+----------------------------------------------------+
12161 | function.__globals__ | A reference to the "dictionary" that holds the |
12162 | | function’s global variables – the global namespace |
12163 | | of the module in which the function was defined. |
12164 +----------------------------------------------------+----------------------------------------------------+
12165 | function.__closure__ | "None" or a "tuple" of cells that contain bindings |
12166 | | for the names specified in the "co_freevars" |
12167 | | attribute of the function’s "code object". A cell |
12168 | | object has the attribute "cell_contents". This can |
12169 | | be used to get the value of the cell, as well as |
12170 | | set the value. |
12171 +----------------------------------------------------+----------------------------------------------------+
12172
12173
12174 Special writable attributes
12175 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
12176
12177 Most of these attributes check the type of the assigned value:
12178
12179 +----------------------------------------------------+----------------------------------------------------+
12180 | Attribute | Meaning |
12181 |====================================================|====================================================|
12182 | function.__doc__ | The function’s documentation string, or "None" if |
12183 | | unavailable. |
12184 +----------------------------------------------------+----------------------------------------------------+
12185 | function.__name__ | The function’s name. See also: "__name__ |
12186 | | attributes". |
12187 +----------------------------------------------------+----------------------------------------------------+
12188 | function.__qualname__ | The function’s *qualified name*. See also: |
12189 | | "__qualname__ attributes". Added in version 3.3. |
12190 +----------------------------------------------------+----------------------------------------------------+
12191 | function.__module__ | The name of the module the function was defined |
12192 | | in, or "None" if unavailable. |
12193 +----------------------------------------------------+----------------------------------------------------+
12194 | function.__defaults__ | A "tuple" containing default *parameter* values |
12195 | | for those parameters that have defaults, or "None" |
12196 | | if no parameters have a default value. |
12197 +----------------------------------------------------+----------------------------------------------------+
12198 | function.__code__ | The code object representing the compiled function |
12199 | | body. |
12200 +----------------------------------------------------+----------------------------------------------------+
12201 | function.__dict__ | The namespace supporting arbitrary function |
12202 | | attributes. See also: "__dict__ attributes". |
12203 +----------------------------------------------------+----------------------------------------------------+
12204 | function.__annotations__ | A "dictionary" containing annotations of |
12205 | | *parameters*. The keys of the dictionary are the |
12206 | | parameter names, and "'return'" for the return |
12207 | | annotation, if provided. See also: |
12208 | | "object.__annotations__". Changed in version |
12209 | | 3.14: Annotations are now lazily evaluated. See |
12210 | | **PEP 649**. |
12211 +----------------------------------------------------+----------------------------------------------------+
12212 | function.__annotate__ | The *annotate function* for this function, or |
12213 | | "None" if the function has no annotations. See |
12214 | | "object.__annotate__". Added in version 3.14. |
12215 +----------------------------------------------------+----------------------------------------------------+
12216 | function.__kwdefaults__ | A "dictionary" containing defaults for keyword- |
12217 | | only *parameters*. |
12218 +----------------------------------------------------+----------------------------------------------------+
12219 | function.__type_params__ | A "tuple" containing the type parameters of a |
12220 | | generic function. Added in version 3.12. |
12221 +----------------------------------------------------+----------------------------------------------------+
12222
12223 Function objects also support getting and setting arbitrary
12224 attributes, which can be used, for example, to attach metadata to
12225 functions. Regular attribute dot-notation is used to get and set such
12226 attributes.
12227
12228 **CPython implementation detail:** CPython’s current implementation
12229 only supports function attributes on user-defined functions. Function
12230 attributes on built-in functions may be supported in the future.
12231
12232 Additional information about a function’s definition can be retrieved
12233 from its code object (accessible via the "__code__" attribute).
12234
12235
12236 Instance methods
12237 ----------------
12238
12239 An instance method object combines a class, a class instance and any
12240 callable object (normally a user-defined function).
12241
12242 Special read-only attributes:
12243
12244 +----------------------------------------------------+----------------------------------------------------+
12245 | method.__self__ | Refers to the class instance object to which the |
12246 | | method is bound |
12247 +----------------------------------------------------+----------------------------------------------------+
12248 | method.__func__ | Refers to the original function object |
12249 +----------------------------------------------------+----------------------------------------------------+
12250 | method.__doc__ | The method’s documentation (same as |
12251 | | "method.__func__.__doc__"). A "string" if the |
12252 | | original function had a docstring, else "None". |
12253 +----------------------------------------------------+----------------------------------------------------+
12254 | method.__name__ | The name of the method (same as |
12255 | | "method.__func__.__name__") |
12256 +----------------------------------------------------+----------------------------------------------------+
12257 | method.__module__ | The name of the module the method was defined in, |
12258 | | or "None" if unavailable. |
12259 +----------------------------------------------------+----------------------------------------------------+
12260
12261 Methods also support accessing (but not setting) the arbitrary
12262 function attributes on the underlying function object.
12263
12264 User-defined method objects may be created when getting an attribute
12265 of a class (perhaps via an instance of that class), if that attribute
12266 is a user-defined function object or a "classmethod" object.
12267
12268 When an instance method object is created by retrieving a user-defined
12269 function object from a class via one of its instances, its "__self__"
12270 attribute is the instance, and the method object is said to be
12271 *bound*. The new method’s "__func__" attribute is the original
12272 function object.
12273
12274 When an instance method object is created by retrieving a
12275 "classmethod" object from a class or instance, its "__self__"
12276 attribute is the class itself, and its "__func__" attribute is the
12277 function object underlying the class method.
12278
12279 When an instance method object is called, the underlying function
12280 ("__func__") is called, inserting the class instance ("__self__") in
12281 front of the argument list. For instance, when "C" is a class which
12282 contains a definition for a function "f()", and "x" is an instance of
12283 "C", calling "x.f(1)" is equivalent to calling "C.f(x, 1)".
12284
12285 When an instance method object is derived from a "classmethod" object,
12286 the “class instance” stored in "__self__" will actually be the class
12287 itself, so that calling either "x.f(1)" or "C.f(1)" is equivalent to
12288 calling "f(C,1)" where "f" is the underlying function.
12289
12290 It is important to note that user-defined functions which are
12291 attributes of a class instance are not converted to bound methods;
12292 this *only* happens when the function is an attribute of the class.
12293
12294
12295 Generator functions
12296 -------------------
12297
12298 A function or method which uses the "yield" statement (see section The
12299 yield statement) is called a *generator function*. Such a function,
12300 when called, always returns an *iterator* object which can be used to
12301 execute the body of the function: calling the iterator’s
12302 "iterator.__next__()" method will cause the function to execute until
12303 it provides a value using the "yield" statement. When the function
12304 executes a "return" statement or falls off the end, a "StopIteration"
12305 exception is raised and the iterator will have reached the end of the
12306 set of values to be returned.
12307
12308
12309 Coroutine functions
12310 -------------------
12311
12312 A function or method which is defined using "async def" is called a
12313 *coroutine function*. Such a function, when called, returns a
12314 *coroutine* object. It may contain "await" expressions, as well as
12315 "async with" and "async for" statements. See also the Coroutine
12316 Objects section.
12317
12318
12319 Asynchronous generator functions
12320 --------------------------------
12321
12322 A function or method which is defined using "async def" and which uses
12323 the "yield" statement is called a *asynchronous generator function*.
12324 Such a function, when called, returns an *asynchronous iterator*
12325 object which can be used in an "async for" statement to execute the
12326 body of the function.
12327
12328 Calling the asynchronous iterator’s "aiterator.__anext__" method will
12329 return an *awaitable* which when awaited will execute until it
12330 provides a value using the "yield" expression. When the function
12331 executes an empty "return" statement or falls off the end, a
12332 "StopAsyncIteration" exception is raised and the asynchronous iterator
12333 will have reached the end of the set of values to be yielded.
12334
12335
12336 Built-in functions
12337 ------------------
12338
12339 A built-in function object is a wrapper around a C function. Examples
12340 of built-in functions are "len()" and "math.sin()" ("math" is a
12341 standard built-in module). The number and type of the arguments are
12342 determined by the C function. Special read-only attributes:
12343
12344 * "__doc__" is the function’s documentation string, or "None" if
12345 unavailable. See "function.__doc__".
12346
12347 * "__name__" is the function’s name. See "function.__name__".
12348
12349 * "__self__" is set to "None" (but see the next item).
12350
12351 * "__module__" is the name of the module the function was defined in
12352 or "None" if unavailable. See "function.__module__".
12353
12354
12355 Built-in methods
12356 ----------------
12357
12358 This is really a different disguise of a built-in function, this time
12359 containing an object passed to the C function as an implicit extra
12360 argument. An example of a built-in method is "alist.append()",
12361 assuming *alist* is a list object. In this case, the special read-only
12362 attribute "__self__" is set to the object denoted by *alist*. (The
12363 attribute has the same semantics as it does with "other instance
12364 methods".)
12365
12366
12367 Classes
12368 -------
12369
12370 Classes are callable. These objects normally act as factories for new
12371 instances of themselves, but variations are possible for class types
12372 that override "__new__()". The arguments of the call are passed to
12373 "__new__()" and, in the typical case, to "__init__()" to initialize
12374 the new instance.
12375
12376
12377 Class Instances
12378 ---------------
12379
12380 Instances of arbitrary classes can be made callable by defining a
12381 "__call__()" method in their class.
12382
12383
12384 Modules
12385 =======
12386
12387 Modules are a basic organizational unit of Python code, and are
12388 created by the import system as invoked either by the "import"
12389 statement, or by calling functions such as "importlib.import_module()"
12390 and built-in "__import__()". A module object has a namespace
12391 implemented by a "dictionary" object (this is the dictionary
12392 referenced by the "__globals__" attribute of functions defined in the
12393 module). Attribute references are translated to lookups in this
12394 dictionary, e.g., "m.x" is equivalent to "m.__dict__["x"]". A module
12395 object does not contain the code object used to initialize the module
12396 (since it isn’t needed once the initialization is done).
12397
12398 Attribute assignment updates the module’s namespace dictionary, e.g.,
12399 "m.x = 1" is equivalent to "m.__dict__["x"] = 1".
12400
12401
12402 Import-related attributes on module objects
12403 -------------------------------------------
12404
12405 Module objects have the following attributes that relate to the import
12406 system. When a module is created using the machinery associated with
12407 the import system, these attributes are filled in based on the
12408 module’s *spec*, before the *loader* executes and loads the module.
12409
12410 To create a module dynamically rather than using the import system,
12411 it’s recommended to use "importlib.util.module_from_spec()", which
12412 will set the various import-controlled attributes to appropriate
12413 values. It’s also possible to use the "types.ModuleType" constructor
12414 to create modules directly, but this technique is more error-prone, as
12415 most attributes must be manually set on the module object after it has
12416 been created when using this approach.
12417
12418 Caution:
12419
12420 With the exception of "__name__", it is **strongly** recommended
12421 that you rely on "__spec__" and its attributes instead of any of the
12422 other individual attributes listed in this subsection. Note that
12423 updating an attribute on "__spec__" will not update the
12424 corresponding attribute on the module itself:
12425
12426 >>> import typing
12427 >>> typing.__name__, typing.__spec__.name
12428 ('typing', 'typing')
12429 >>> typing.__spec__.name = 'spelling'
12430 >>> typing.__name__, typing.__spec__.name
12431 ('typing', 'spelling')
12432 >>> typing.__name__ = 'keyboard_smashing'
12433 >>> typing.__name__, typing.__spec__.name
12434 ('keyboard_smashing', 'spelling')
12435
12436 module.__name__
12437
12438 The name used to uniquely identify the module in the import system.
12439 For a directly executed module, this will be set to ""__main__"".
12440
12441 This attribute must be set to the fully qualified name of the
12442 module. It is expected to match the value of
12443 "module.__spec__.name".
12444
12445 module.__spec__
12446
12447 A record of the module’s import-system-related state.
12448
12449 Set to the "module spec" that was used when importing the module.
12450 See Module specs for more details.
12451
12452 Added in version 3.4.
12453
12454 module.__package__
12455
12456 The *package* a module belongs to.
12457
12458 If the module is top-level (that is, not a part of any specific
12459 package) then the attribute should be set to "''" (the empty
12460 string). Otherwise, it should be set to the name of the module’s
12461 package (which can be equal to "module.__name__" if the module
12462 itself is a package). See **PEP 366** for further details.
12463
12464 This attribute is used instead of "__name__" to calculate explicit
12465 relative imports for main modules. It defaults to "None" for
12466 modules created dynamically using the "types.ModuleType"
12467 constructor; use "importlib.util.module_from_spec()" instead to
12468 ensure the attribute is set to a "str".
12469
12470 It is **strongly** recommended that you use
12471 "module.__spec__.parent" instead of "module.__package__".
12472 "__package__" is now only used as a fallback if "__spec__.parent"
12473 is not set, and this fallback path is deprecated.
12474
12475 Changed in version 3.4: This attribute now defaults to "None" for
12476 modules created dynamically using the "types.ModuleType"
12477 constructor. Previously the attribute was optional.
12478
12479 Changed in version 3.6: The value of "__package__" is expected to
12480 be the same as "__spec__.parent". "__package__" is now only used as
12481 a fallback during import resolution if "__spec__.parent" is not
12482 defined.
12483
12484 Changed in version 3.10: "ImportWarning" is raised if an import
12485 resolution falls back to "__package__" instead of
12486 "__spec__.parent".
12487
12488 Changed in version 3.12: Raise "DeprecationWarning" instead of
12489 "ImportWarning" when falling back to "__package__" during import
12490 resolution.
12491
12492 Deprecated since version 3.13, will be removed in version 3.15:
12493 "__package__" will cease to be set or taken into consideration by
12494 the import system or standard library.
12495
12496 module.__loader__
12497
12498 The *loader* object that the import machinery used to load the
12499 module.
12500
12501 This attribute is mostly useful for introspection, but can be used
12502 for additional loader-specific functionality, for example getting
12503 data associated with a loader.
12504
12505 "__loader__" defaults to "None" for modules created dynamically
12506 using the "types.ModuleType" constructor; use
12507 "importlib.util.module_from_spec()" instead to ensure the attribute
12508 is set to a *loader* object.
12509
12510 It is **strongly** recommended that you use
12511 "module.__spec__.loader" instead of "module.__loader__".
12512
12513 Changed in version 3.4: This attribute now defaults to "None" for
12514 modules created dynamically using the "types.ModuleType"
12515 constructor. Previously the attribute was optional.
12516
12517 Deprecated since version 3.12, will be removed in version 3.16:
12518 Setting "__loader__" on a module while failing to set
12519 "__spec__.loader" is deprecated. In Python 3.16, "__loader__" will
12520 cease to be set or taken into consideration by the import system or
12521 the standard library.
12522
12523 module.__path__
12524
12525 A (possibly empty) *sequence* of strings enumerating the locations
12526 where the package’s submodules will be found. Non-package modules
12527 should not have a "__path__" attribute. See __path__ attributes on
12528 modules for more details.
12529
12530 It is **strongly** recommended that you use
12531 "module.__spec__.submodule_search_locations" instead of
12532 "module.__path__".
12533
12534 module.__file__
12535
12536 module.__cached__
12537
12538 "__file__" and "__cached__" are both optional attributes that may
12539 or may not be set. Both attributes should be a "str" when they are
12540 available.
12541
12542 "__file__" indicates the pathname of the file from which the module
12543 was loaded (if loaded from a file), or the pathname of the shared
12544 library file for extension modules loaded dynamically from a shared
12545 library. It might be missing for certain types of modules, such as
12546 C modules that are statically linked into the interpreter, and the
12547 import system may opt to leave it unset if it has no semantic
12548 meaning (for example, a module loaded from a database).
12549
12550 If "__file__" is set then the "__cached__" attribute might also be
12551 set, which is the path to any compiled version of the code (for
12552 example, a byte-compiled file). The file does not need to exist to
12553 set this attribute; the path can simply point to where the compiled
12554 file *would* exist (see **PEP 3147**).
12555
12556 Note that "__cached__" may be set even if "__file__" is not set.
12557 However, that scenario is quite atypical. Ultimately, the *loader*
12558 is what makes use of the module spec provided by the *finder* (from
12559 which "__file__" and "__cached__" are derived). So if a loader can
12560 load from a cached module but otherwise does not load from a file,
12561 that atypical scenario may be appropriate.
12562
12563 It is **strongly** recommended that you use
12564 "module.__spec__.cached" instead of "module.__cached__".
12565
12566 Deprecated since version 3.13, will be removed in version 3.15:
12567 Setting "__cached__" on a module while failing to set
12568 "__spec__.cached" is deprecated. In Python 3.15, "__cached__" will
12569 cease to be set or taken into consideration by the import system or
12570 standard library.
12571
12572
12573 Other writable attributes on module objects
12574 -------------------------------------------
12575
12576 As well as the import-related attributes listed above, module objects
12577 also have the following writable attributes:
12578
12579 module.__doc__
12580
12581 The module’s documentation string, or "None" if unavailable. See
12582 also: "__doc__ attributes".
12583
12584 module.__annotations__
12585
12586 A dictionary containing *variable annotations* collected during
12587 module body execution. For best practices on working with
12588 "__annotations__", see "annotationlib".
12589
12590 Changed in version 3.14: Annotations are now lazily evaluated. See
12591 **PEP 649**.
12592
12593 module.__annotate__
12594
12595 The *annotate function* for this module, or "None" if the module
12596 has no annotations. See also: "__annotate__" attributes.
12597
12598 Added in version 3.14.
12599
12600
12601 Module dictionaries
12602 -------------------
12603
12604 Module objects also have the following special read-only attribute:
12605
12606 module.__dict__
12607
12608 The module’s namespace as a dictionary object. Uniquely among the
12609 attributes listed here, "__dict__" cannot be accessed as a global
12610 variable from within a module; it can only be accessed as an
12611 attribute on module objects.
12612
12613 **CPython implementation detail:** Because of the way CPython
12614 clears module dictionaries, the module dictionary will be cleared
12615 when the module falls out of scope even if the dictionary still has
12616 live references. To avoid this, copy the dictionary or keep the
12617 module around while using its dictionary directly.
12618
12619
12620 Custom classes
12621 ==============
12622
12623 Custom class types are typically created by class definitions (see
12624 section Class definitions). A class has a namespace implemented by a
12625 dictionary object. Class attribute references are translated to
12626 lookups in this dictionary, e.g., "C.x" is translated to
12627 "C.__dict__["x"]" (although there are a number of hooks which allow
12628 for other means of locating attributes). When the attribute name is
12629 not found there, the attribute search continues in the base classes.
12630 This search of the base classes uses the C3 method resolution order
12631 which behaves correctly even in the presence of ‘diamond’ inheritance
12632 structures where there are multiple inheritance paths leading back to
12633 a common ancestor. Additional details on the C3 MRO used by Python can
12634 be found at The Python 2.3 Method Resolution Order.
12635
12636 When a class attribute reference (for class "C", say) would yield a
12637 class method object, it is transformed into an instance method object
12638 whose "__self__" attribute is "C". When it would yield a
12639 "staticmethod" object, it is transformed into the object wrapped by
12640 the static method object. See section Implementing Descriptors for
12641 another way in which attributes retrieved from a class may differ from
12642 those actually contained in its "__dict__".
12643
12644 Class attribute assignments update the class’s dictionary, never the
12645 dictionary of a base class.
12646
12647 A class object can be called (see above) to yield a class instance
12648 (see below).
12649
12650
12651 Special attributes
12652 ------------------
12653
12654 +----------------------------------------------------+----------------------------------------------------+
12655 | Attribute | Meaning |
12656 |====================================================|====================================================|
12657 | type.__name__ | The class’s name. See also: "__name__ attributes". |
12658 +----------------------------------------------------+----------------------------------------------------+
12659 | type.__qualname__ | The class’s *qualified name*. See also: |
12660 | | "__qualname__ attributes". |
12661 +----------------------------------------------------+----------------------------------------------------+
12662 | type.__module__ | The name of the module in which the class was |
12663 | | defined. |
12664 +----------------------------------------------------+----------------------------------------------------+
12665 | type.__dict__ | A "mapping proxy" providing a read-only view of |
12666 | | the class’s namespace. See also: "__dict__ |
12667 | | attributes". |
12668 +----------------------------------------------------+----------------------------------------------------+
12669 | type.__bases__ | A "tuple" containing the class’s bases. In most |
12670 | | cases, for a class defined as "class X(A, B, C)", |
12671 | | "X.__bases__" will be exactly equal to "(A, B, |
12672 | | C)". |
12673 +----------------------------------------------------+----------------------------------------------------+
12674 | type.__base__ | **CPython implementation detail:** The single base |
12675 | | class in the inheritance chain that is responsible |
12676 | | for the memory layout of instances. This attribute |
12677 | | corresponds to "tp_base" at the C level. |
12678 +----------------------------------------------------+----------------------------------------------------+
12679 | type.__doc__ | The class’s documentation string, or "None" if |
12680 | | undefined. Not inherited by subclasses. |
12681 +----------------------------------------------------+----------------------------------------------------+
12682 | type.__annotations__ | A dictionary containing *variable annotations* |
12683 | | collected during class body execution. See also: |
12684 | | "__annotations__ attributes". For best practices |
12685 | | on working with "__annotations__", please see |
12686 | | "annotationlib". Use |
12687 | | "annotationlib.get_annotations()" instead of |
12688 | | accessing this attribute directly. Warning: |
12689 | | Accessing the "__annotations__" attribute directly |
12690 | | on a class object may return annotations for the |
12691 | | wrong class, specifically in certain cases where |
12692 | | the class, its base class, or a metaclass is |
12693 | | defined under "from __future__ import |
12694 | | annotations". See **749** for details.This |
12695 | | attribute does not exist on certain builtin |
12696 | | classes. On user-defined classes without |
12697 | | "__annotations__", it is an empty dictionary. |
12698 | | Changed in version 3.14: Annotations are now |
12699 | | lazily evaluated. See **PEP 649**. |
12700 +----------------------------------------------------+----------------------------------------------------+
12701 | type.__annotate__() | The *annotate function* for this class, or "None" |
12702 | | if the class has no annotations. See also: |
12703 | | "__annotate__ attributes". Added in version 3.14. |
12704 +----------------------------------------------------+----------------------------------------------------+
12705 | type.__type_params__ | A "tuple" containing the type parameters of a |
12706 | | generic class. Added in version 3.12. |
12707 +----------------------------------------------------+----------------------------------------------------+
12708 | type.__static_attributes__ | A "tuple" containing names of attributes of this |
12709 | | class which are assigned through "self.X" from any |
12710 | | function in its body. Added in version 3.13. |
12711 +----------------------------------------------------+----------------------------------------------------+
12712 | type.__firstlineno__ | The line number of the first line of the class |
12713 | | definition, including decorators. Setting the |
12714 | | "__module__" attribute removes the |
12715 | | "__firstlineno__" item from the type’s dictionary. |
12716 | | Added in version 3.13. |
12717 +----------------------------------------------------+----------------------------------------------------+
12718 | type.__mro__ | The "tuple" of classes that are considered when |
12719 | | looking for base classes during method resolution. |
12720 +----------------------------------------------------+----------------------------------------------------+
12721
12722
12723 Special methods
12724 ---------------
12725
12726 In addition to the special attributes described above, all Python
12727 classes also have the following two methods available:
12728
12729 type.mro()
12730
12731 This method can be overridden by a metaclass to customize the
12732 method resolution order for its instances. It is called at class
12733 instantiation, and its result is stored in "__mro__".
12734
12735 type.__subclasses__()
12736
12737 Each class keeps a list of weak references to its immediate
12738 subclasses. This method returns a list of all those references
12739 still alive. The list is in definition order. Example:
12740
12741 >>> class A: pass
12742 >>> class B(A): pass
12743 >>> A.__subclasses__()
12744 [<class 'B'>]
12745
12746
12747 Class instances
12748 ===============
12749
12750 A class instance is created by calling a class object (see above). A
12751 class instance has a namespace implemented as a dictionary which is
12752 the first place in which attribute references are searched. When an
12753 attribute is not found there, and the instance’s class has an
12754 attribute by that name, the search continues with the class
12755 attributes. If a class attribute is found that is a user-defined
12756 function object, it is transformed into an instance method object
12757 whose "__self__" attribute is the instance. Static method and class
12758 method objects are also transformed; see above under “Classes”. See
12759 section Implementing Descriptors for another way in which attributes
12760 of a class retrieved via its instances may differ from the objects
12761 actually stored in the class’s "__dict__". If no class attribute is
12762 found, and the object’s class has a "__getattr__()" method, that is
12763 called to satisfy the lookup.
12764
12765 Attribute assignments and deletions update the instance’s dictionary,
12766 never a class’s dictionary. If the class has a "__setattr__()" or
12767 "__delattr__()" method, this is called instead of updating the
12768 instance dictionary directly.
12769
12770 Class instances can pretend to be numbers, sequences, or mappings if
12771 they have methods with certain special names. See section Special
12772 method names.
12773
12774
12775 Special attributes
12776 ------------------
12777
12778 object.__class__
12779
12780 The class to which a class instance belongs.
12781
12782 object.__dict__
12783
12784 A dictionary or other mapping object used to store an object’s
12785 (writable) attributes. Not all instances have a "__dict__"
12786 attribute; see the section on __slots__ for more details.
12787
12788
12789 I/O objects (also known as file objects)
12790 ========================================
12791
12792 A *file object* represents an open file. Various shortcuts are
12793 available to create file objects: the "open()" built-in function, and
12794 also "os.popen()", "os.fdopen()", and the "makefile()" method of
12795 socket objects (and perhaps by other functions or methods provided by
12796 extension modules).
12797
12798 File objects implement common methods, listed below, to simplify usage
12799 in generic code. They are expected to be With Statement Context
12800 Managers.
12801
12802 The objects "sys.stdin", "sys.stdout" and "sys.stderr" are initialized
12803 to file objects corresponding to the interpreter’s standard input,
12804 output and error streams; they are all open in text mode and therefore
12805 follow the interface defined by the "io.TextIOBase" abstract class.
12806
12807 file.read(size=-1, /)
12808
12809 Retrieve up to *size* data from the file. As a convenience if
12810 *size* is unspecified or -1 retrieve all data available.
12811
12812 file.write(data, /)
12813
12814 Store *data* to the file.
12815
12816 file.close()
12817
12818 Flush any buffers and close the underlying file.
12819
12820
12821 Internal types
12822 ==============
12823
12824 A few types used internally by the interpreter are exposed to the
12825 user. Their definitions may change with future versions of the
12826 interpreter, but they are mentioned here for completeness.
12827
12828
12829 Code objects
12830 ------------
12831
12832 Code objects represent *byte-compiled* executable Python code, or
12833 *bytecode*. The difference between a code object and a function object
12834 is that the function object contains an explicit reference to the
12835 function’s globals (the module in which it was defined), while a code
12836 object contains no context; also the default argument values are
12837 stored in the function object, not in the code object (because they
12838 represent values calculated at run-time). Unlike function objects,
12839 code objects are immutable and contain no references (directly or
12840 indirectly) to mutable objects.
12841
12842
12843 Special read-only attributes
12844 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
12845
12846 +----------------------------------------------------+----------------------------------------------------+
12847 | codeobject.co_name | The function name |
12848 +----------------------------------------------------+----------------------------------------------------+
12849 | codeobject.co_qualname | The fully qualified function name Added in |
12850 | | version 3.11. |
12851 +----------------------------------------------------+----------------------------------------------------+
12852 | codeobject.co_argcount | The total number of positional *parameters* |
12853 | | (including positional-only parameters and |
12854 | | parameters with default values) that the function |
12855 | | has |
12856 +----------------------------------------------------+----------------------------------------------------+
12857 | codeobject.co_posonlyargcount | The number of positional-only *parameters* |
12858 | | (including arguments with default values) that the |
12859 | | function has |
12860 +----------------------------------------------------+----------------------------------------------------+
12861 | codeobject.co_kwonlyargcount | The number of keyword-only *parameters* (including |
12862 | | arguments with default values) that the function |
12863 | | has |
12864 +----------------------------------------------------+----------------------------------------------------+
12865 | codeobject.co_nlocals | The number of local variables used by the function |
12866 | | (including parameters) |
12867 +----------------------------------------------------+----------------------------------------------------+
12868 | codeobject.co_varnames | A "tuple" containing the names of the local |
12869 | | variables in the function (starting with the |
12870 | | parameter names) |
12871 +----------------------------------------------------+----------------------------------------------------+
12872 | codeobject.co_cellvars | A "tuple" containing the names of local variables |
12873 | | that are referenced from at least one *nested |
12874 | | scope* inside the function |
12875 +----------------------------------------------------+----------------------------------------------------+
12876 | codeobject.co_freevars | A "tuple" containing the names of *free (closure) |
12877 | | variables* that a *nested scope* references in an |
12878 | | outer scope. See also "function.__closure__". |
12879 | | Note: references to global and builtin names are |
12880 | | *not* included. |
12881 +----------------------------------------------------+----------------------------------------------------+
12882 | codeobject.co_code | A string representing the sequence of *bytecode* |
12883 | | instructions in the function |
12884 +----------------------------------------------------+----------------------------------------------------+
12885 | codeobject.co_consts | A "tuple" containing the literals used by the |
12886 | | *bytecode* in the function |
12887 +----------------------------------------------------+----------------------------------------------------+
12888 | codeobject.co_names | A "tuple" containing the names used by the |
12889 | | *bytecode* in the function |
12890 +----------------------------------------------------+----------------------------------------------------+
12891 | codeobject.co_filename | The name of the file from which the code was |
12892 | | compiled |
12893 +----------------------------------------------------+----------------------------------------------------+
12894 | codeobject.co_firstlineno | The line number of the first line of the function |
12895 +----------------------------------------------------+----------------------------------------------------+
12896 | codeobject.co_lnotab | A string encoding the mapping from *bytecode* |
12897 | | offsets to line numbers. For details, see the |
12898 | | source code of the interpreter. Deprecated since |
12899 | | version 3.12: This attribute of code objects is |
12900 | | deprecated, and may be removed in Python 3.15. |
12901 +----------------------------------------------------+----------------------------------------------------+
12902 | codeobject.co_stacksize | The required stack size of the code object |
12903 +----------------------------------------------------+----------------------------------------------------+
12904 | codeobject.co_flags | An "integer" encoding a number of flags for the |
12905 | | interpreter. |
12906 +----------------------------------------------------+----------------------------------------------------+
12907
12908 The following flag bits are defined for "co_flags": bit "0x04" is set
12909 if the function uses the "*arguments" syntax to accept an arbitrary
12910 number of positional arguments; bit "0x08" is set if the function uses
12911 the "**keywords" syntax to accept arbitrary keyword arguments; bit
12912 "0x20" is set if the function is a generator. See Code Objects Bit
12913 Flags for details on the semantics of each flags that might be
12914 present.
12915
12916 Future feature declarations (for example, "from __future__ import
12917 division") also use bits in "co_flags" to indicate whether a code
12918 object was compiled with a particular feature enabled. See
12919 "compiler_flag".
12920
12921 Other bits in "co_flags" are reserved for internal use.
12922
12923 If a code object represents a function and has a docstring, the
12924 "CO_HAS_DOCSTRING" bit is set in "co_flags" and the first item in
12925 "co_consts" is the docstring of the function.
12926
12927
12928 Methods on code objects
12929 ~~~~~~~~~~~~~~~~~~~~~~~
12930
12931 codeobject.co_positions()
12932
12933 Returns an iterable over the source code positions of each
12934 *bytecode* instruction in the code object.
12935
12936 The iterator returns "tuple"s containing the "(start_line,
12937 end_line, start_column, end_column)". The *i-th* tuple corresponds
12938 to the position of the source code that compiled to the *i-th* code
12939 unit. Column information is 0-indexed utf-8 byte offsets on the
12940 given source line.
12941
12942 This positional information can be missing. A non-exhaustive lists
12943 of cases where this may happen:
12944
12945 * Running the interpreter with "-X" "no_debug_ranges".
12946
12947 * Loading a pyc file compiled while using "-X" "no_debug_ranges".
12948
12949 * Position tuples corresponding to artificial instructions.
12950
12951 * Line and column numbers that can’t be represented due to
12952 implementation specific limitations.
12953
12954 When this occurs, some or all of the tuple elements can be "None".
12955
12956 Added in version 3.11.
12957
12958 Note:
12959
12960 This feature requires storing column positions in code objects
12961 which may result in a small increase of disk usage of compiled
12962 Python files or interpreter memory usage. To avoid storing the
12963 extra information and/or deactivate printing the extra traceback
12964 information, the "-X" "no_debug_ranges" command line flag or the
12965 "PYTHONNODEBUGRANGES" environment variable can be used.
12966
12967 codeobject.co_lines()
12968
12969 Returns an iterator that yields information about successive ranges
12970 of *bytecode*s. Each item yielded is a "(start, end, lineno)"
12971 "tuple":
12972
12973 * "start" (an "int") represents the offset (inclusive) of the start
12974 of the *bytecode* range
12975
12976 * "end" (an "int") represents the offset (exclusive) of the end of
12977 the *bytecode* range
12978
12979 * "lineno" is an "int" representing the line number of the
12980 *bytecode* range, or "None" if the bytecodes in the given range
12981 have no line number
12982
12983 The items yielded will have the following properties:
12984
12985 * The first range yielded will have a "start" of 0.
12986
12987 * The "(start, end)" ranges will be non-decreasing and consecutive.
12988 That is, for any pair of "tuple"s, the "start" of the second will
12989 be equal to the "end" of the first.
12990
12991 * No range will be backwards: "end >= start" for all triples.
12992
12993 * The last "tuple" yielded will have "end" equal to the size of the
12994 *bytecode*.
12995
12996 Zero-width ranges, where "start == end", are allowed. Zero-width
12997 ranges are used for lines that are present in the source code, but
12998 have been eliminated by the *bytecode* compiler.
12999
13000 Added in version 3.10.
13001
13002 See also:
13003
13004 **PEP 626** - Precise line numbers for debugging and other tools.
13005 The PEP that introduced the "co_lines()" method.
13006
13007 codeobject.replace(**kwargs)
13008
13009 Return a copy of the code object with new values for the specified
13010 fields.
13011
13012 Code objects are also supported by the generic function
13013 "copy.replace()".
13014
13015 Added in version 3.8.
13016
13017
13018 Frame objects
13019 -------------
13020
13021 Frame objects represent execution frames. They may occur in traceback
13022 objects, and are also passed to registered trace functions.
13023
13024
13025 Special read-only attributes
13026 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
13027
13028 +----------------------------------------------------+----------------------------------------------------+
13029 | frame.f_back | Points to the previous stack frame (towards the |
13030 | | caller), or "None" if this is the bottom stack |
13031 | | frame |
13032 +----------------------------------------------------+----------------------------------------------------+
13033 | frame.f_code | The code object being executed in this frame. |
13034 | | Accessing this attribute raises an auditing event |
13035 | | "object.__getattr__" with arguments "obj" and |
13036 | | ""f_code"". |
13037 +----------------------------------------------------+----------------------------------------------------+
13038 | frame.f_locals | The mapping used by the frame to look up local |
13039 | | variables. If the frame refers to an *optimized |
13040 | | scope*, this may return a write-through proxy |
13041 | | object. Changed in version 3.13: Return a proxy |
13042 | | for optimized scopes. |
13043 +----------------------------------------------------+----------------------------------------------------+
13044 | frame.f_globals | The dictionary used by the frame to look up global |
13045 | | variables |
13046 +----------------------------------------------------+----------------------------------------------------+
13047 | frame.f_builtins | The dictionary used by the frame to look up built- |
13048 | | in (intrinsic) names |
13049 +----------------------------------------------------+----------------------------------------------------+
13050 | frame.f_lasti | The “precise instruction” of the frame object |
13051 | | (this is an index into the *bytecode* string of |
13052 | | the code object) |
13053 +----------------------------------------------------+----------------------------------------------------+
13054 | frame.f_generator | The *generator* or *coroutine* object that owns |
13055 | | this frame, or "None" if the frame is a normal |
13056 | | function. Added in version 3.14. |
13057 +----------------------------------------------------+----------------------------------------------------+
13058
13059
13060 Special writable attributes
13061 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
13062
13063 +----------------------------------------------------+----------------------------------------------------+
13064 | frame.f_trace | If not "None", this is a function called for |
13065 | | various events during code execution (this is used |
13066 | | by debuggers). Normally an event is triggered for |
13067 | | each new source line (see "f_trace_lines"). |
13068 +----------------------------------------------------+----------------------------------------------------+
13069 | frame.f_trace_lines | Set this attribute to "False" to disable |
13070 | | triggering a tracing event for each source line. |
13071 +----------------------------------------------------+----------------------------------------------------+
13072 | frame.f_trace_opcodes | Set this attribute to "True" to allow per-opcode |
13073 | | events to be requested. Note that this may lead to |
13074 | | undefined interpreter behaviour if exceptions |
13075 | | raised by the trace function escape to the |
13076 | | function being traced. |
13077 +----------------------------------------------------+----------------------------------------------------+
13078 | frame.f_lineno | The current line number of the frame – writing to |
13079 | | this from within a trace function jumps to the |
13080 | | given line (only for the bottom-most frame). A |
13081 | | debugger can implement a Jump command (aka Set |
13082 | | Next Statement) by writing to this attribute. |
13083 +----------------------------------------------------+----------------------------------------------------+
13084
13085
13086 Frame object methods
13087 ~~~~~~~~~~~~~~~~~~~~
13088
13089 Frame objects support one method:
13090
13091 frame.clear()
13092
13093 This method clears all references to local variables held by the
13094 frame. Also, if the frame belonged to a *generator*, the generator
13095 is finalized. This helps break reference cycles involving frame
13096 objects (for example when catching an exception and storing its
13097 traceback for later use).
13098
13099 "RuntimeError" is raised if the frame is currently executing or
13100 suspended.
13101
13102 Added in version 3.4.
13103
13104 Changed in version 3.13: Attempting to clear a suspended frame
13105 raises "RuntimeError" (as has always been the case for executing
13106 frames).
13107
13108
13109 Traceback objects
13110 -----------------
13111
13112 Traceback objects represent the stack trace of an exception. A
13113 traceback object is implicitly created when an exception occurs, and
13114 may also be explicitly created by calling "types.TracebackType".
13115
13116 Changed in version 3.7: Traceback objects can now be explicitly
13117 instantiated from Python code.
13118
13119 For implicitly created tracebacks, when the search for an exception
13120 handler unwinds the execution stack, at each unwound level a traceback
13121 object is inserted in front of the current traceback. When an
13122 exception handler is entered, the stack trace is made available to the
13123 program. (See section The try statement.) It is accessible as the
13124 third item of the tuple returned by "sys.exc_info()", and as the
13125 "__traceback__" attribute of the caught exception.
13126
13127 When the program contains no suitable handler, the stack trace is
13128 written (nicely formatted) to the standard error stream; if the
13129 interpreter is interactive, it is also made available to the user as
13130 "sys.last_traceback".
13131
13132 For explicitly created tracebacks, it is up to the creator of the
13133 traceback to determine how the "tb_next" attributes should be linked
13134 to form a full stack trace.
13135
13136 Special read-only attributes:
13137
13138 +----------------------------------------------------+----------------------------------------------------+
13139 | traceback.tb_frame | Points to the execution frame of the current |
13140 | | level. Accessing this attribute raises an |
13141 | | auditing event "object.__getattr__" with arguments |
13142 | | "obj" and ""tb_frame"". |
13143 +----------------------------------------------------+----------------------------------------------------+
13144 | traceback.tb_lineno | Gives the line number where the exception occurred |
13145 +----------------------------------------------------+----------------------------------------------------+
13146 | traceback.tb_lasti | Indicates the “precise instruction”. |
13147 +----------------------------------------------------+----------------------------------------------------+
13148
13149 The line number and last instruction in the traceback may differ from
13150 the line number of its frame object if the exception occurred in a
13151 "try" statement with no matching except clause or with a "finally"
13152 clause.
13153
13154 traceback.tb_next
13155
13156 The special writable attribute "tb_next" is the next level in the
13157 stack trace (towards the frame where the exception occurred), or
13158 "None" if there is no next level.
13159
13160 Changed in version 3.7: This attribute is now writable
13161
13162
13163 Slice objects
13164 -------------
13165
13166 Slice objects are used to represent slices for "__getitem__()"
13167 methods. They are also created by the built-in "slice()" function.
13168
13169 Special read-only attributes: "start" is the lower bound; "stop" is
13170 the upper bound; "step" is the step value; each is "None" if omitted.
13171 These attributes can have any type.
13172
13173 Slice objects support one method:
13174
13175 slice.indices(self, length)
13176
13177 This method takes a single integer argument *length* and computes
13178 information about the slice that the slice object would describe if
13179 applied to a sequence of *length* items. It returns a tuple of
13180 three integers; respectively these are the *start* and *stop*
13181 indices and the *step* or stride length of the slice. Missing or
13182 out-of-bounds indices are handled in a manner consistent with
13183 regular slices.
13184
13185
13186 Static method objects
13187 ---------------------
13188
13189 Static method objects provide a way of defeating the transformation of
13190 function objects to method objects described above. A static method
13191 object is a wrapper around any other object, usually a user-defined
13192 method object. When a static method object is retrieved from a class
13193 or a class instance, the object actually returned is the wrapped
13194 object, which is not subject to any further transformation. Static
13195 method objects are also callable. Static method objects are created by
13196 the built-in "staticmethod()" constructor.
13197
13198
13199 Class method objects
13200 --------------------
13201
13202 A class method object, like a static method object, is a wrapper
13203 around another object that alters the way in which that object is
13204 retrieved from classes and class instances. The behaviour of class
13205 method objects upon such retrieval is described above, under “instance
13206 methods”. Class method objects are created by the built-in
13207 "classmethod()" constructor.
13208 ''',
13209 'typesfunctions': r'''Functions
13210 *********
13211
13212 Function objects are created by function definitions. The only
13213 operation on a function object is to call it: "func(argument-list)".
13214
13215 There are really two flavors of function objects: built-in functions
13216 and user-defined functions. Both support the same operation (to call
13217 the function), but the implementation is different, hence the
13218 different object types.
13219
13220 See Function definitions for more information.
13221 ''',
13222 'typesmapping': r'''Mapping Types — "dict"
13223 **********************
13224
13225 A *mapping* object maps *hashable* values to arbitrary objects.
13226 Mappings are mutable objects. There is currently only one standard
13227 mapping type, the *dictionary*. (For other containers see the built-
13228 in "list", "set", and "tuple" classes, and the "collections" module.)
13229
13230 A dictionary’s keys are *almost* arbitrary values. Values that are
13231 not *hashable*, that is, values containing lists, dictionaries or
13232 other mutable types (that are compared by value rather than by object
13233 identity) may not be used as keys. Values that compare equal (such as
13234 "1", "1.0", and "True") can be used interchangeably to index the same
13235 dictionary entry.
13236
13237 class dict(**kwargs)
13238 class dict(mapping, /, **kwargs)
13239 class dict(iterable, /, **kwargs)
13240
13241 Return a new dictionary initialized from an optional positional
13242 argument and a possibly empty set of keyword arguments.
13243
13244 Dictionaries can be created by several means:
13245
13246 * Use a comma-separated list of "key: value" pairs within braces:
13247 "{'jack': 4098, 'sjoerd': 4127}" or "{4098: 'jack', 4127:
13248 'sjoerd'}"
13249
13250 * Use a dict comprehension: "{}", "{x: x ** 2 for x in range(10)}"
13251
13252 * Use the type constructor: "dict()", "dict([('foo', 100), ('bar',
13253 200)])", "dict(foo=100, bar=200)"
13254
13255 If no positional argument is given, an empty dictionary is created.
13256 If a positional argument is given and it defines a "keys()" method,
13257 a dictionary is created by calling "__getitem__()" on the argument
13258 with each returned key from the method. Otherwise, the positional
13259 argument must be an *iterable* object. Each item in the iterable
13260 must itself be an iterable with exactly two elements. The first
13261 element of each item becomes a key in the new dictionary, and the
13262 second element the corresponding value. If a key occurs more than
13263 once, the last value for that key becomes the corresponding value
13264 in the new dictionary.
13265
13266 If keyword arguments are given, the keyword arguments and their
13267 values are added to the dictionary created from the positional
13268 argument. If a key being added is already present, the value from
13269 the keyword argument replaces the value from the positional
13270 argument.
13271
13272 Dictionaries compare equal if and only if they have the same "(key,
13273 value)" pairs (regardless of ordering). Order comparisons (‘<’,
13274 ‘<=’, ‘>=’, ‘>’) raise "TypeError". To illustrate dictionary
13275 creation and equality, the following examples all return a
13276 dictionary equal to "{"one": 1, "two": 2, "three": 3}":
13277
13278 >>> a = dict(one=1, two=2, three=3)
13279 >>> b = {'one': 1, 'two': 2, 'three': 3}
13280 >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
13281 >>> d = dict([('two', 2), ('one', 1), ('three', 3)])
13282 >>> e = dict({'three': 3, 'one': 1, 'two': 2})
13283 >>> f = dict({'one': 1, 'three': 3}, two=2)
13284 >>> a == b == c == d == e == f
13285 True
13286
13287 Providing keyword arguments as in the first example only works for
13288 keys that are valid Python identifiers. Otherwise, any valid keys
13289 can be used.
13290
13291 Dictionaries preserve insertion order. Note that updating a key
13292 does not affect the order. Keys added after deletion are inserted
13293 at the end.
13294
13295 >>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
13296 >>> d
13297 {'one': 1, 'two': 2, 'three': 3, 'four': 4}
13298 >>> list(d)
13299 ['one', 'two', 'three', 'four']
13300 >>> list(d.values())
13301 [1, 2, 3, 4]
13302 >>> d["one"] = 42
13303 >>> d
13304 {'one': 42, 'two': 2, 'three': 3, 'four': 4}
13305 >>> del d["two"]
13306 >>> d["two"] = None
13307 >>> d
13308 {'one': 42, 'three': 3, 'four': 4, 'two': None}
13309
13310 Changed in version 3.7: Dictionary order is guaranteed to be
13311 insertion order. This behavior was an implementation detail of
13312 CPython from 3.6.
13313
13314 These are the operations that dictionaries support (and therefore,
13315 custom mapping types should support too):
13316
13317 list(d)
13318
13319 Return a list of all the keys used in the dictionary *d*.
13320
13321 len(d)
13322
13323 Return the number of items in the dictionary *d*.
13324
13325 d[key]
13326
13327 Return the item of *d* with key *key*. Raises a "KeyError" if
13328 *key* is not in the map.
13329
13330 If a subclass of dict defines a method "__missing__()" and *key*
13331 is not present, the "d[key]" operation calls that method with
13332 the key *key* as argument. The "d[key]" operation then returns
13333 or raises whatever is returned or raised by the
13334 "__missing__(key)" call. No other operations or methods invoke
13335 "__missing__()". If "__missing__()" is not defined, "KeyError"
13336 is raised. "__missing__()" must be a method; it cannot be an
13337 instance variable:
13338
13339 >>> class Counter(dict):
13340 ... def __missing__(self, key):
13341 ... return 0
13342 ...
13343 >>> c = Counter()
13344 >>> c['red']
13345 0
13346 >>> c['red'] += 1
13347 >>> c['red']
13348 1
13349
13350 The example above shows part of the implementation of
13351 "collections.Counter". A different "__missing__()" method is
13352 used by "collections.defaultdict".
13353
13354 d[key] = value
13355
13356 Set "d[key]" to *value*.
13357
13358 del d[key]
13359
13360 Remove "d[key]" from *d*. Raises a "KeyError" if *key* is not
13361 in the map.
13362
13363 key in d
13364
13365 Return "True" if *d* has a key *key*, else "False".
13366
13367 key not in d
13368
13369 Equivalent to "not key in d".
13370
13371 iter(d)
13372
13373 Return an iterator over the keys of the dictionary. This is a
13374 shortcut for "iter(d.keys())".
13375
13376 clear()
13377
13378 Remove all items from the dictionary.
13379
13380 copy()
13381
13382 Return a shallow copy of the dictionary.
13383
13384 classmethod fromkeys(iterable, value=None, /)
13385
13386 Create a new dictionary with keys from *iterable* and values set
13387 to *value*.
13388
13389 "fromkeys()" is a class method that returns a new dictionary.
13390 *value* defaults to "None". All of the values refer to just a
13391 single instance, so it generally doesn’t make sense for *value*
13392 to be a mutable object such as an empty list. To get distinct
13393 values, use a dict comprehension instead.
13394
13395 get(key, default=None, /)
13396
13397 Return the value for *key* if *key* is in the dictionary, else
13398 *default*. If *default* is not given, it defaults to "None", so
13399 that this method never raises a "KeyError".
13400
13401 items()
13402
13403 Return a new view of the dictionary’s items ("(key, value)"
13404 pairs). See the documentation of view objects.
13405
13406 keys()
13407
13408 Return a new view of the dictionary’s keys. See the
13409 documentation of view objects.
13410
13411 pop(key, /)
13412 pop(key, default, /)
13413
13414 If *key* is in the dictionary, remove it and return its value,
13415 else return *default*. If *default* is not given and *key* is
13416 not in the dictionary, a "KeyError" is raised.
13417
13418 popitem()
13419
13420 Remove and return a "(key, value)" pair from the dictionary.
13421 Pairs are returned in LIFO (last-in, first-out) order.
13422
13423 "popitem()" is useful to destructively iterate over a
13424 dictionary, as often used in set algorithms. If the dictionary
13425 is empty, calling "popitem()" raises a "KeyError".
13426
13427 Changed in version 3.7: LIFO order is now guaranteed. In prior
13428 versions, "popitem()" would return an arbitrary key/value pair.
13429
13430 reversed(d)
13431
13432 Return a reverse iterator over the keys of the dictionary. This
13433 is a shortcut for "reversed(d.keys())".
13434
13435 Added in version 3.8.
13436
13437 setdefault(key, default=None, /)
13438
13439 If *key* is in the dictionary, return its value. If not, insert
13440 *key* with a value of *default* and return *default*. *default*
13441 defaults to "None".
13442
13443 update(**kwargs)
13444 update(mapping, /, **kwargs)
13445 update(iterable, /, **kwargs)
13446
13447 Update the dictionary with the key/value pairs from *mapping* or
13448 *iterable* and *kwargs*, overwriting existing keys. Return
13449 "None".
13450
13451 "update()" accepts either another object with a "keys()" method
13452 (in which case "__getitem__()" is called with every key returned
13453 from the method) or an iterable of key/value pairs (as tuples or
13454 other iterables of length two). If keyword arguments are
13455 specified, the dictionary is then updated with those key/value
13456 pairs: "d.update(red=1, blue=2)".
13457
13458 values()
13459
13460 Return a new view of the dictionary’s values. See the
13461 documentation of view objects.
13462
13463 An equality comparison between one "dict.values()" view and
13464 another will always return "False". This also applies when
13465 comparing "dict.values()" to itself:
13466
13467 >>> d = {'a': 1}
13468 >>> d.values() == d.values()
13469 False
13470
13471 d | other
13472
13473 Create a new dictionary with the merged keys and values of *d*
13474 and *other*, which must both be dictionaries. The values of
13475 *other* take priority when *d* and *other* share keys.
13476
13477 Added in version 3.9.
13478
13479 d |= other
13480
13481 Update the dictionary *d* with keys and values from *other*,
13482 which may be either a *mapping* or an *iterable* of key/value
13483 pairs. The values of *other* take priority when *d* and *other*
13484 share keys.
13485
13486 Added in version 3.9.
13487
13488 Dictionaries and dictionary views are reversible.
13489
13490 >>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
13491 >>> d
13492 {'one': 1, 'two': 2, 'three': 3, 'four': 4}
13493 >>> list(reversed(d))
13494 ['four', 'three', 'two', 'one']
13495 >>> list(reversed(d.values()))
13496 [4, 3, 2, 1]
13497 >>> list(reversed(d.items()))
13498 [('four', 4), ('three', 3), ('two', 2), ('one', 1)]
13499
13500 Changed in version 3.8: Dictionaries are now reversible.
13501
13502 See also:
13503
13504 "types.MappingProxyType" can be used to create a read-only view of a
13505 "dict".
13506
13507 See also:
13508
13509 For detailed information on thread-safety guarantees for "dict"
13510 objects, see Thread safety for dict objects.
13511
13512
13513 Dictionary view objects
13514 =======================
13515
13516 The objects returned by "dict.keys()", "dict.values()" and
13517 "dict.items()" are *view objects*. They provide a dynamic view on the
13518 dictionary’s entries, which means that when the dictionary changes,
13519 the view reflects these changes.
13520
13521 Dictionary views can be iterated over to yield their respective data,
13522 and support membership tests:
13523
13524 len(dictview)
13525
13526 Return the number of entries in the dictionary.
13527
13528 iter(dictview)
13529
13530 Return an iterator over the keys, values or items (represented as
13531 tuples of "(key, value)") in the dictionary.
13532
13533 Keys and values are iterated over in insertion order. This allows
13534 the creation of "(value, key)" pairs using "zip()": "pairs =
13535 zip(d.values(), d.keys())". Another way to create the same list is
13536 "pairs = [(v, k) for (k, v) in d.items()]".
13537
13538 Iterating views while adding or deleting entries in the dictionary
13539 may raise a "RuntimeError" or fail to iterate over all entries.
13540
13541 Changed in version 3.7: Dictionary order is guaranteed to be
13542 insertion order.
13543
13544 x in dictview
13545
13546 Return "True" if *x* is in the underlying dictionary’s keys, values
13547 or items (in the latter case, *x* should be a "(key, value)"
13548 tuple).
13549
13550 reversed(dictview)
13551
13552 Return a reverse iterator over the keys, values or items of the
13553 dictionary. The view will be iterated in reverse order of the
13554 insertion.
13555
13556 Changed in version 3.8: Dictionary views are now reversible.
13557
13558 dictview.mapping
13559
13560 Return a "types.MappingProxyType" that wraps the original
13561 dictionary to which the view refers.
13562
13563 Added in version 3.10.
13564
13565 Keys views are set-like since their entries are unique and *hashable*.
13566 Items views also have set-like operations since the (key, value) pairs
13567 are unique and the keys are hashable. If all values in an items view
13568 are hashable as well, then the items view can interoperate with other
13569 sets. (Values views are not treated as set-like since the entries are
13570 generally not unique.) For set-like views, all of the operations
13571 defined for the abstract base class "collections.abc.Set" are
13572 available (for example, "==", "<", or "^"). While using set
13573 operators, set-like views accept any iterable as the other operand,
13574 unlike sets which only accept sets as the input.
13575
13576 An example of dictionary view usage:
13577
13578 >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
13579 >>> keys = dishes.keys()
13580 >>> values = dishes.values()
13581
13582 >>> # iteration
13583 >>> n = 0
13584 >>> for val in values:
13585 ... n += val
13586 ...
13587 >>> print(n)
13588 504
13589
13590 >>> # keys and values are iterated over in the same order (insertion order)
13591 >>> list(keys)
13592 ['eggs', 'sausage', 'bacon', 'spam']
13593 >>> list(values)
13594 [2, 1, 1, 500]
13595
13596 >>> # view objects are dynamic and reflect dict changes
13597 >>> del dishes['eggs']
13598 >>> del dishes['sausage']
13599 >>> list(keys)
13600 ['bacon', 'spam']
13601
13602 >>> # set operations
13603 >>> keys & {'eggs', 'bacon', 'salad'}
13604 {'bacon'}
13605 >>> keys ^ {'sausage', 'juice'} == {'juice', 'sausage', 'bacon', 'spam'}
13606 True
13607 >>> keys | ['juice', 'juice', 'juice'] == {'bacon', 'spam', 'juice'}
13608 True
13609
13610 >>> # get back a read-only proxy for the original dictionary
13611 >>> values.mapping
13612 mappingproxy({'bacon': 1, 'spam': 500})
13613 >>> values.mapping['spam']
13614 500
13615 ''',
13616 'typesmethods': r'''Methods
13617 *******
13618
13619 Methods are functions that are called using the attribute notation.
13620 There are two flavors: built-in methods (such as "append()" on lists)
13621 and class instance method. Built-in methods are described with the
13622 types that support them.
13623
13624 If you access a method (a function defined in a class namespace)
13625 through an instance, you get a special object: a *bound method* (also
13626 called instance method) object. When called, it will add the "self"
13627 argument to the argument list. Bound methods have two special read-
13628 only attributes: "m.__self__" is the object on which the method
13629 operates, and "m.__func__" is the function implementing the method.
13630 Calling "m(arg-1, arg-2, ..., arg-n)" is completely equivalent to
13631 calling "m.__func__(m.__self__, arg-1, arg-2, ..., arg-n)".
13632
13633 Like function objects, bound method objects support getting arbitrary
13634 attributes. However, since method attributes are actually stored on
13635 the underlying function object ("method.__func__"), setting method
13636 attributes on bound methods is disallowed. Attempting to set an
13637 attribute on a method results in an "AttributeError" being raised. In
13638 order to set a method attribute, you need to explicitly set it on the
13639 underlying function object:
13640
13641 >>> class C:
13642 ... def method(self):
13643 ... pass
13644 ...
13645 >>> c = C()
13646 >>> c.method.whoami = 'my name is method' # can't set on the method
13647 Traceback (most recent call last):
13648 File "<stdin>", line 1, in <module>
13649 AttributeError: 'method' object has no attribute 'whoami'
13650 >>> c.method.__func__.whoami = 'my name is method'
13651 >>> c.method.whoami
13652 'my name is method'
13653
13654 See Instance methods for more information.
13655 ''',
13656 'typesmodules': r'''Modules
13657 *******
13658
13659 The only special operation on a module is attribute access: "m.name",
13660 where *m* is a module and *name* accesses a name defined in *m*’s
13661 symbol table. Module attributes can be assigned to. (Note that the
13662 "import" statement is not, strictly speaking, an operation on a module
13663 object; "import foo" does not require a module object named *foo* to
13664 exist, rather it requires an (external) *definition* for a module
13665 named *foo* somewhere.)
13666
13667 A special attribute of every module is "__dict__". This is the
13668 dictionary containing the module’s symbol table. Modifying this
13669 dictionary will actually change the module’s symbol table, but direct
13670 assignment to the "__dict__" attribute is not possible (you can write
13671 "m.__dict__['a'] = 1", which defines "m.a" to be "1", but you can’t
13672 write "m.__dict__ = {}"). Modifying "__dict__" directly is not
13673 recommended.
13674
13675 Modules built into the interpreter are written like this: "<module
13676 'sys' (built-in)>". If loaded from a file, they are written as
13677 "<module 'os' from '/usr/local/lib/pythonX.Y/os.pyc'>".
13678 ''',
13679 'typesseq': r'''Sequence Types — "list", "tuple", "range"
13680 *****************************************
13681
13682 There are three basic sequence types: lists, tuples, and range
13683 objects. Additional sequence types tailored for processing of binary
13684 data and text strings are described in dedicated sections.
13685
13686
13687 Common Sequence Operations
13688 ==========================
13689
13690 The operations in the following table are supported by most sequence
13691 types, both mutable and immutable. The "collections.abc.Sequence" ABC
13692 is provided to make it easier to correctly implement these operations
13693 on custom sequence types.
13694
13695 This table lists the sequence operations sorted in ascending priority.
13696 In the table, *s* and *t* are sequences of the same type, *n*, *i*,
13697 *j* and *k* are integers and *x* is an arbitrary object that meets any
13698 type and value restrictions imposed by *s*.
13699
13700 The "in" and "not in" operations have the same priorities as the
13701 comparison operations. The "+" (concatenation) and "*" (repetition)
13702 operations have the same priority as the corresponding numeric
13703 operations. [3]
13704
13705 +----------------------------+----------------------------------+------------+
13706 | Operation | Result | Notes |
13707 |============================|==================================|============|
13708 | "x in s" | "True" if an item of *s* is | (1) |
13709 | | equal to *x*, else "False" | |
13710 +----------------------------+----------------------------------+------------+
13711 | "x not in s" | "False" if an item of *s* is | (1) |
13712 | | equal to *x*, else "True" | |
13713 +----------------------------+----------------------------------+------------+
13714 | "s + t" | the concatenation of *s* and *t* | (6)(7) |
13715 +----------------------------+----------------------------------+------------+
13716 | "s * n" or "n * s" | equivalent to adding *s* to | (2)(7) |
13717 | | itself *n* times | |
13718 +----------------------------+----------------------------------+------------+
13719 | "s[i]" | *i*th item of *s*, origin 0 | (3)(8) |
13720 +----------------------------+----------------------------------+------------+
13721 | "s[i:j]" | slice of *s* from *i* to *j* | (3)(4) |
13722 +----------------------------+----------------------------------+------------+
13723 | "s[i:j:k]" | slice of *s* from *i* to *j* | (3)(5) |
13724 | | with step *k* | |
13725 +----------------------------+----------------------------------+------------+
13726 | "len(s)" | length of *s* | |
13727 +----------------------------+----------------------------------+------------+
13728 | "min(s)" | smallest item of *s* | |
13729 +----------------------------+----------------------------------+------------+
13730 | "max(s)" | largest item of *s* | |
13731 +----------------------------+----------------------------------+------------+
13732
13733 Sequences of the same type also support comparisons. In particular,
13734 tuples and lists are compared lexicographically by comparing
13735 corresponding elements. This means that to compare equal, every
13736 element must compare equal and the two sequences must be of the same
13737 type and have the same length. (For full details see Comparisons in
13738 the language reference.)
13739
13740 Forward and reversed iterators over mutable sequences access values
13741 using an index. That index will continue to march forward (or
13742 backward) even if the underlying sequence is mutated. The iterator
13743 terminates only when an "IndexError" or a "StopIteration" is
13744 encountered (or when the index drops below zero).
13745
13746 Notes:
13747
13748 1. While the "in" and "not in" operations are used only for simple
13749 containment testing in the general case, some specialised sequences
13750 (such as "str", "bytes" and "bytearray") also use them for
13751 subsequence testing:
13752
13753 >>> "gg" in "eggs"
13754 True
13755
13756 2. Values of *n* less than "0" are treated as "0" (which yields an
13757 empty sequence of the same type as *s*). Note that items in the
13758 sequence *s* are not copied; they are referenced multiple times.
13759 This often haunts new Python programmers; consider:
13760
13761 >>> lists = [[]] * 3
13762 >>> lists
13763 [[], [], []]
13764 >>> lists[0].append(3)
13765 >>> lists
13766 [[3], [3], [3]]
13767
13768 What has happened is that "[[]]" is a one-element list containing
13769 an empty list, so all three elements of "[[]] * 3" are references
13770 to this single empty list. Modifying any of the elements of
13771 "lists" modifies this single list. You can create a list of
13772 different lists this way:
13773
13774 >>> lists = [[] for i in range(3)]
13775 >>> lists[0].append(3)
13776 >>> lists[1].append(5)
13777 >>> lists[2].append(7)
13778 >>> lists
13779 [[3], [5], [7]]
13780
13781 Further explanation is available in the FAQ entry How do I create a
13782 multidimensional list?.
13783
13784 3. If *i* or *j* is negative, the index is relative to the end of
13785 sequence *s*: "len(s) + i" or "len(s) + j" is substituted. But
13786 note that "-0" is still "0".
13787
13788 4. The slice of *s* from *i* to *j* is defined as the sequence of
13789 items with index *k* such that "i <= k < j".
13790
13791 * If *i* is omitted or "None", use "0".
13792
13793 * If *j* is omitted or "None", use "len(s)".
13794
13795 * If *i* or *j* is less than "-len(s)", use "0".
13796
13797 * If *i* or *j* is greater than "len(s)", use "len(s)".
13798
13799 * If *i* is greater than or equal to *j*, the slice is empty.
13800
13801 5. The slice of *s* from *i* to *j* with step *k* is defined as the
13802 sequence of items with index "x = i + n*k" such that "0 <= n <
13803 (j-i)/k". In other words, the indices are "i", "i+k", "i+2*k",
13804 "i+3*k" and so on, stopping when *j* is reached (but never
13805 including *j*). When *k* is positive, *i* and *j* are reduced to
13806 "len(s)" if they are greater. When *k* is negative, *i* and *j* are
13807 reduced to "len(s) - 1" if they are greater. If *i* or *j* are
13808 omitted or "None", they become “end” values (which end depends on
13809 the sign of *k*). Note, *k* cannot be zero. If *k* is "None", it
13810 is treated like "1".
13811
13812 6. Concatenating immutable sequences always results in a new object.
13813 This means that building up a sequence by repeated concatenation
13814 will have a quadratic runtime cost in the total sequence length.
13815 To get a linear runtime cost, you must switch to one of the
13816 alternatives below:
13817
13818 * if concatenating "str" objects, you can build a list and use
13819 "str.join()" at the end or else write to an "io.StringIO"
13820 instance and retrieve its value when complete
13821
13822 * if concatenating "bytes" objects, you can similarly use
13823 "bytes.join()" or "io.BytesIO", or you can do in-place
13824 concatenation with a "bytearray" object. "bytearray" objects are
13825 mutable and have an efficient overallocation mechanism
13826
13827 * if concatenating "tuple" objects, extend a "list" instead
13828
13829 * for other types, investigate the relevant class documentation
13830
13831 7. Some sequence types (such as "range") only support item sequences
13832 that follow specific patterns, and hence don’t support sequence
13833 concatenation or repetition.
13834
13835 8. An "IndexError" is raised if *i* is outside the sequence range.
13836
13837 -[ Sequence Methods ]-
13838
13839 Sequence types also support the following methods:
13840
13841 sequence.count(value, /)
13842
13843 Return the total number of occurrences of *value* in *sequence*.
13844
13845 sequence.index(value[, start[, stop]])
13846
13847 Return the index of the first occurrence of *value* in *sequence*.
13848
13849 Raises "ValueError" if *value* is not found in *sequence*.
13850
13851 The *start* or *stop* arguments allow for efficient searching of
13852 subsections of the sequence, beginning at *start* and ending at
13853 *stop*. This is roughly equivalent to "start +
13854 sequence[start:stop].index(value)", only without copying any data.
13855
13856 Caution:
13857
13858 Not all sequence types support passing the *start* and *stop*
13859 arguments.
13860
13861
13862 Immutable Sequence Types
13863 ========================
13864
13865 The only operation that immutable sequence types generally implement
13866 that is not also implemented by mutable sequence types is support for
13867 the "hash()" built-in.
13868
13869 This support allows immutable sequences, such as "tuple" instances, to
13870 be used as "dict" keys and stored in "set" and "frozenset" instances.
13871
13872 Attempting to hash an immutable sequence that contains unhashable
13873 values will result in "TypeError".
13874
13875
13876 Mutable Sequence Types
13877 ======================
13878
13879 The operations in the following table are defined on mutable sequence
13880 types. The "collections.abc.MutableSequence" ABC is provided to make
13881 it easier to correctly implement these operations on custom sequence
13882 types.
13883
13884 In the table *s* is an instance of a mutable sequence type, *t* is any
13885 iterable object and *x* is an arbitrary object that meets any type and
13886 value restrictions imposed by *s* (for example, "bytearray" only
13887 accepts integers that meet the value restriction "0 <= x <= 255").
13888
13889 +--------------------------------+----------------------------------+-----------------------+
13890 | Operation | Result | Notes |
13891 |================================|==================================|=======================|
13892 | "s[i] = x" | item *i* of *s* is replaced by | |
13893 | | *x* | |
13894 +--------------------------------+----------------------------------+-----------------------+
13895 | "del s[i]" | removes item *i* of *s* | |
13896 +--------------------------------+----------------------------------+-----------------------+
13897 | "s[i:j] = t" | slice of *s* from *i* to *j* is | |
13898 | | replaced by the contents of the | |
13899 | | iterable *t* | |
13900 +--------------------------------+----------------------------------+-----------------------+
13901 | "del s[i:j]" | removes the elements of "s[i:j]" | |
13902 | | from the list (same as "s[i:j] = | |
13903 | | []") | |
13904 +--------------------------------+----------------------------------+-----------------------+
13905 | "s[i:j:k] = t" | the elements of "s[i:j:k]" are | (1) |
13906 | | replaced by those of *t* | |
13907 +--------------------------------+----------------------------------+-----------------------+
13908 | "del s[i:j:k]" | removes the elements of | |
13909 | | "s[i:j:k]" from the list | |
13910 +--------------------------------+----------------------------------+-----------------------+
13911 | "s += t" | extends *s* with the contents of | |
13912 | | *t* (for the most part the same | |
13913 | | as "s[len(s):len(s)] = t") | |
13914 +--------------------------------+----------------------------------+-----------------------+
13915 | "s *= n" | updates *s* with its contents | (2) |
13916 | | repeated *n* times | |
13917 +--------------------------------+----------------------------------+-----------------------+
13918
13919 Notes:
13920
13921 1. If *k* is not equal to "1", *t* must have the same length as the
13922 slice it is replacing.
13923
13924 2. The value *n* is an integer, or an object implementing
13925 "__index__()". Zero and negative values of *n* clear the sequence.
13926 Items in the sequence are not copied; they are referenced multiple
13927 times, as explained for "s * n" under Common Sequence Operations.
13928
13929 -[ Mutable Sequence Methods ]-
13930
13931 Mutable sequence types also support the following methods:
13932
13933 sequence.append(value, /)
13934
13935 Append *value* to the end of the sequence. This is equivalent to
13936 writing "seq[len(seq):len(seq)] = [value]".
13937
13938 sequence.clear()
13939
13940 Added in version 3.3.
13941
13942 Remove all items from *sequence*. This is equivalent to writing
13943 "del sequence[:]".
13944
13945 sequence.copy()
13946
13947 Added in version 3.3.
13948
13949 Create a shallow copy of *sequence*. This is equivalent to writing
13950 "sequence[:]".
13951
13952 Hint:
13953
13954 The "copy()" method is not part of the "MutableSequence" "ABC",
13955 but most concrete mutable sequence types provide it.
13956
13957 sequence.extend(iterable, /)
13958
13959 Extend *sequence* with the contents of *iterable*. For the most
13960 part, this is the same as writing "seq[len(seq):len(seq)] =
13961 iterable".
13962
13963 sequence.insert(index, value, /)
13964
13965 Insert *value* into *sequence* at the given *index*. This is
13966 equivalent to writing "sequence[index:index] = [value]".
13967
13968 sequence.pop(index=-1, /)
13969
13970 Retrieve the item at *index* and also removes it from *sequence*.
13971 By default, the last item in *sequence* is removed and returned.
13972
13973 sequence.remove(value, /)
13974
13975 Remove the first item from *sequence* where "sequence[i] == value".
13976
13977 Raises "ValueError" if *value* is not found in *sequence*.
13978
13979 sequence.reverse()
13980
13981 Reverse the items of *sequence* in place. This method maintains
13982 economy of space when reversing a large sequence. To remind users
13983 that it operates by side-effect, it returns "None".
13984
13985
13986 Lists
13987 =====
13988
13989 Lists are mutable sequences, typically used to store collections of
13990 homogeneous items (where the precise degree of similarity will vary by
13991 application).
13992
13993 class list(iterable=(), /)
13994
13995 Lists may be constructed in several ways:
13996
13997 * Using a pair of square brackets to denote the empty list: "[]"
13998
13999 * Using square brackets, separating items with commas: "[a]", "[a,
14000 b, c]"
14001
14002 * Using a list comprehension: "[x for x in iterable]"
14003
14004 * Using the type constructor: "list()" or "list(iterable)"
14005
14006 The constructor builds a list whose items are the same and in the
14007 same order as *iterable*’s items. *iterable* may be either a
14008 sequence, a container that supports iteration, or an iterator
14009 object. If *iterable* is already a list, a copy is made and
14010 returned, similar to "iterable[:]". For example, "list('abc')"
14011 returns "['a', 'b', 'c']" and "list( (1, 2, 3) )" returns "[1, 2,
14012 3]". If no argument is given, the constructor creates a new empty
14013 list, "[]".
14014
14015 Many other operations also produce lists, including the "sorted()"
14016 built-in.
14017
14018 Lists implement all of the common and mutable sequence operations.
14019 Lists also provide the following additional method:
14020
14021 sort(*, key=None, reverse=False)
14022
14023 This method sorts the list in place, using only "<" comparisons
14024 between items. Exceptions are not suppressed - if any comparison
14025 operations fail, the entire sort operation will fail (and the
14026 list will likely be left in a partially modified state).
14027
14028 "sort()" accepts two arguments that can only be passed by
14029 keyword (keyword-only arguments):
14030
14031 *key* specifies a function of one argument that is used to
14032 extract a comparison key from each list element (for example,
14033 "key=str.lower"). The key corresponding to each item in the list
14034 is calculated once and then used for the entire sorting process.
14035 The default value of "None" means that list items are sorted
14036 directly without calculating a separate key value.
14037
14038 The "functools.cmp_to_key()" utility is available to convert a
14039 2.x style *cmp* function to a *key* function.
14040
14041 *reverse* is a boolean value. If set to "True", then the list
14042 elements are sorted as if each comparison were reversed.
14043
14044 This method modifies the sequence in place for economy of space
14045 when sorting a large sequence. To remind users that it operates
14046 by side effect, it does not return the sorted sequence (use
14047 "sorted()" to explicitly request a new sorted list instance).
14048
14049 The "sort()" method is guaranteed to be stable. A sort is
14050 stable if it guarantees not to change the relative order of
14051 elements that compare equal — this is helpful for sorting in
14052 multiple passes (for example, sort by department, then by salary
14053 grade).
14054
14055 For sorting examples and a brief sorting tutorial, see Sorting
14056 Techniques.
14057
14058 **CPython implementation detail:** While a list is being sorted,
14059 the effect of attempting to mutate, or even inspect, the list is
14060 undefined. The C implementation of Python makes the list appear
14061 empty for the duration, and raises "ValueError" if it can detect
14062 that the list has been mutated during a sort.
14063
14064 See also:
14065
14066 For detailed information on thread-safety guarantees for "list"
14067 objects, see Thread safety for list objects.
14068
14069
14070 Tuples
14071 ======
14072
14073 Tuples are immutable sequences, typically used to store collections of
14074 heterogeneous data (such as the 2-tuples produced by the "enumerate()"
14075 built-in). Tuples are also used for cases where an immutable sequence
14076 of homogeneous data is needed (such as allowing storage in a "set" or
14077 "dict" instance).
14078
14079 class tuple(iterable=(), /)
14080
14081 Tuples may be constructed in a number of ways:
14082
14083 * Using a pair of parentheses to denote the empty tuple: "()"
14084
14085 * Using a trailing comma for a singleton tuple: "a," or "(a,)"
14086
14087 * Separating items with commas: "a, b, c" or "(a, b, c)"
14088
14089 * Using the "tuple()" built-in: "tuple()" or "tuple(iterable)"
14090
14091 The constructor builds a tuple whose items are the same and in the
14092 same order as *iterable*’s items. *iterable* may be either a
14093 sequence, a container that supports iteration, or an iterator
14094 object. If *iterable* is already a tuple, it is returned
14095 unchanged. For example, "tuple('abc')" returns "('a', 'b', 'c')"
14096 and "tuple( [1, 2, 3] )" returns "(1, 2, 3)". If no argument is
14097 given, the constructor creates a new empty tuple, "()".
14098
14099 Note that it is actually the comma which makes a tuple, not the
14100 parentheses. The parentheses are optional, except in the empty
14101 tuple case, or when they are needed to avoid syntactic ambiguity.
14102 For example, "f(a, b, c)" is a function call with three arguments,
14103 while "f((a, b, c))" is a function call with a 3-tuple as the sole
14104 argument.
14105
14106 Tuples implement all of the common sequence operations.
14107
14108 For heterogeneous collections of data where access by name is clearer
14109 than access by index, "collections.namedtuple()" may be a more
14110 appropriate choice than a simple tuple object.
14111
14112
14113 Ranges
14114 ======
14115
14116 The "range" type represents an immutable sequence of numbers and is
14117 commonly used for looping a specific number of times in "for" loops.
14118
14119 class range(stop, /)
14120 class range(start, stop, step=1, /)
14121
14122 The arguments to the range constructor must be integers (either
14123 built-in "int" or any object that implements the "__index__()"
14124 special method). If the *step* argument is omitted, it defaults to
14125 "1". If the *start* argument is omitted, it defaults to "0". If
14126 *step* is zero, "ValueError" is raised.
14127
14128 For a positive *step*, the contents of a range "r" are determined
14129 by the formula "r[i] = start + step*i" where "i >= 0" and "r[i] <
14130 stop".
14131
14132 For a negative *step*, the contents of the range are still
14133 determined by the formula "r[i] = start + step*i", but the
14134 constraints are "i >= 0" and "r[i] > stop".
14135
14136 A range object will be empty if "r[0]" does not meet the value
14137 constraint. Ranges do support negative indices, but these are
14138 interpreted as indexing from the end of the sequence determined by
14139 the positive indices.
14140
14141 Ranges containing absolute values larger than "sys.maxsize" are
14142 permitted but some features (such as "len()") may raise
14143 "OverflowError".
14144
14145 Range examples:
14146
14147 >>> list(range(10))
14148 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
14149 >>> list(range(1, 11))
14150 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
14151 >>> list(range(0, 30, 5))
14152 [0, 5, 10, 15, 20, 25]
14153 >>> list(range(0, 10, 3))
14154 [0, 3, 6, 9]
14155 >>> list(range(0, -10, -1))
14156 [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
14157 >>> list(range(0))
14158 []
14159 >>> list(range(1, 0))
14160 []
14161
14162 Ranges implement all of the common sequence operations except
14163 concatenation and repetition (due to the fact that range objects
14164 can only represent sequences that follow a strict pattern and
14165 repetition and concatenation will usually violate that pattern).
14166
14167 start
14168
14169 The value of the *start* parameter (or "0" if the parameter was
14170 not supplied)
14171
14172 stop
14173
14174 The value of the *stop* parameter
14175
14176 step
14177
14178 The value of the *step* parameter (or "1" if the parameter was
14179 not supplied)
14180
14181 The advantage of the "range" type over a regular "list" or "tuple" is
14182 that a "range" object will always take the same (small) amount of
14183 memory, no matter the size of the range it represents (as it only
14184 stores the "start", "stop" and "step" values, calculating individual
14185 items and subranges as needed).
14186
14187 Range objects implement the "collections.abc.Sequence" ABC, and
14188 provide features such as containment tests, element index lookup,
14189 slicing and support for negative indices (see Sequence Types — list,
14190 tuple, range):
14191
14192 >>> r = range(0, 20, 2)
14193 >>> r
14194 range(0, 20, 2)
14195 >>> 11 in r
14196 False
14197 >>> 10 in r
14198 True
14199 >>> r.index(10)
14200 5
14201 >>> r[5]
14202 10
14203 >>> r[:5]
14204 range(0, 10, 2)
14205 >>> r[-1]
14206 18
14207
14208 Testing range objects for equality with "==" and "!=" compares them as
14209 sequences. That is, two range objects are considered equal if they
14210 represent the same sequence of values. (Note that two range objects
14211 that compare equal might have different "start", "stop" and "step"
14212 attributes, for example "range(0) == range(2, 1, 3)" or "range(0, 3,
14213 2) == range(0, 4, 2)".)
14214
14215 Changed in version 3.2: Implement the Sequence ABC. Support slicing
14216 and negative indices. Test "int" objects for membership in constant
14217 time instead of iterating through all items.
14218
14219 Changed in version 3.3: Define ‘==’ and ‘!=’ to compare range objects
14220 based on the sequence of values they define (instead of comparing
14221 based on object identity).Added the "start", "stop" and "step"
14222 attributes.
14223
14224 See also:
14225
14226 * The linspace recipe shows how to implement a lazy version of range
14227 suitable for floating-point applications.
14228 ''',
14229 'typesseq-mutable': r'''Mutable Sequence Types
14230 **********************
14231
14232 The operations in the following table are defined on mutable sequence
14233 types. The "collections.abc.MutableSequence" ABC is provided to make
14234 it easier to correctly implement these operations on custom sequence
14235 types.
14236
14237 In the table *s* is an instance of a mutable sequence type, *t* is any
14238 iterable object and *x* is an arbitrary object that meets any type and
14239 value restrictions imposed by *s* (for example, "bytearray" only
14240 accepts integers that meet the value restriction "0 <= x <= 255").
14241
14242 +--------------------------------+----------------------------------+-----------------------+
14243 | Operation | Result | Notes |
14244 |================================|==================================|=======================|
14245 | "s[i] = x" | item *i* of *s* is replaced by | |
14246 | | *x* | |
14247 +--------------------------------+----------------------------------+-----------------------+
14248 | "del s[i]" | removes item *i* of *s* | |
14249 +--------------------------------+----------------------------------+-----------------------+
14250 | "s[i:j] = t" | slice of *s* from *i* to *j* is | |
14251 | | replaced by the contents of the | |
14252 | | iterable *t* | |
14253 +--------------------------------+----------------------------------+-----------------------+
14254 | "del s[i:j]" | removes the elements of "s[i:j]" | |
14255 | | from the list (same as "s[i:j] = | |
14256 | | []") | |
14257 +--------------------------------+----------------------------------+-----------------------+
14258 | "s[i:j:k] = t" | the elements of "s[i:j:k]" are | (1) |
14259 | | replaced by those of *t* | |
14260 +--------------------------------+----------------------------------+-----------------------+
14261 | "del s[i:j:k]" | removes the elements of | |
14262 | | "s[i:j:k]" from the list | |
14263 +--------------------------------+----------------------------------+-----------------------+
14264 | "s += t" | extends *s* with the contents of | |
14265 | | *t* (for the most part the same | |
14266 | | as "s[len(s):len(s)] = t") | |
14267 +--------------------------------+----------------------------------+-----------------------+
14268 | "s *= n" | updates *s* with its contents | (2) |
14269 | | repeated *n* times | |
14270 +--------------------------------+----------------------------------+-----------------------+
14271
14272 Notes:
14273
14274 1. If *k* is not equal to "1", *t* must have the same length as the
14275 slice it is replacing.
14276
14277 2. The value *n* is an integer, or an object implementing
14278 "__index__()". Zero and negative values of *n* clear the sequence.
14279 Items in the sequence are not copied; they are referenced multiple
14280 times, as explained for "s * n" under Common Sequence Operations.
14281
14282 -[ Mutable Sequence Methods ]-
14283
14284 Mutable sequence types also support the following methods:
14285
14286 sequence.append(value, /)
14287
14288 Append *value* to the end of the sequence. This is equivalent to
14289 writing "seq[len(seq):len(seq)] = [value]".
14290
14291 sequence.clear()
14292
14293 Added in version 3.3.
14294
14295 Remove all items from *sequence*. This is equivalent to writing
14296 "del sequence[:]".
14297
14298 sequence.copy()
14299
14300 Added in version 3.3.
14301
14302 Create a shallow copy of *sequence*. This is equivalent to writing
14303 "sequence[:]".
14304
14305 Hint:
14306
14307 The "copy()" method is not part of the "MutableSequence" "ABC",
14308 but most concrete mutable sequence types provide it.
14309
14310 sequence.extend(iterable, /)
14311
14312 Extend *sequence* with the contents of *iterable*. For the most
14313 part, this is the same as writing "seq[len(seq):len(seq)] =
14314 iterable".
14315
14316 sequence.insert(index, value, /)
14317
14318 Insert *value* into *sequence* at the given *index*. This is
14319 equivalent to writing "sequence[index:index] = [value]".
14320
14321 sequence.pop(index=-1, /)
14322
14323 Retrieve the item at *index* and also removes it from *sequence*.
14324 By default, the last item in *sequence* is removed and returned.
14325
14326 sequence.remove(value, /)
14327
14328 Remove the first item from *sequence* where "sequence[i] == value".
14329
14330 Raises "ValueError" if *value* is not found in *sequence*.
14331
14332 sequence.reverse()
14333
14334 Reverse the items of *sequence* in place. This method maintains
14335 economy of space when reversing a large sequence. To remind users
14336 that it operates by side-effect, it returns "None".
14337 ''',
14338 'unary': r'''Unary arithmetic and bitwise operations
14339 ***************************************
14340
14341 All unary arithmetic and bitwise operations have the same priority:
14342
14343 u_expr: power | "-" u_expr | "+" u_expr | "~" u_expr
14344
14345 The unary "-" (minus) operator yields the negation of its numeric
14346 argument; the operation can be overridden with the "__neg__()" special
14347 method.
14348
14349 The unary "+" (plus) operator yields its numeric argument unchanged;
14350 the operation can be overridden with the "__pos__()" special method.
14351
14352 The unary "~" (invert) operator yields the bitwise inversion of its
14353 integer argument. The bitwise inversion of "x" is defined as
14354 "-(x+1)". It only applies to integral numbers or to custom objects
14355 that override the "__invert__()" special method.
14356
14357 In all three cases, if the argument does not have the proper type, a
14358 "TypeError" exception is raised.
14359 ''',
14360 'while': r'''The "while" statement
14361 *********************
14362
14363 The "while" statement is used for repeated execution as long as an
14364 expression is true:
14365
14366 while_stmt: "while" assignment_expression ":" suite
14367 ["else" ":" suite]
14368
14369 This repeatedly tests the expression and, if it is true, executes the
14370 first suite; if the expression is false (which may be the first time
14371 it is tested) the suite of the "else" clause, if present, is executed
14372 and the loop terminates.
14373
14374 A "break" statement executed in the first suite terminates the loop
14375 without executing the "else" clause’s suite. A "continue" statement
14376 executed in the first suite skips the rest of the suite and goes back
14377 to testing the expression.
14378 ''',
14379 'with': r'''The "with" statement
14380 ********************
14381
14382 The "with" statement is used to wrap the execution of a block with
14383 methods defined by a context manager (see section With Statement
14384 Context Managers). This allows common "try"…"except"…"finally" usage
14385 patterns to be encapsulated for convenient reuse.
14386
14387 with_stmt: "with" ( "(" with_stmt_contents ","? ")" | with_stmt_contents ) ":" suite
14388 with_stmt_contents: with_item ("," with_item)*
14389 with_item: expression ["as" target]
14390
14391 The execution of the "with" statement with one “item” proceeds as
14392 follows:
14393
14394 1. The context expression (the expression given in the "with_item") is
14395 evaluated to obtain a context manager.
14396
14397 2. The context manager’s "__enter__()" is loaded for later use.
14398
14399 3. The context manager’s "__exit__()" is loaded for later use.
14400
14401 4. The context manager’s "__enter__()" method is invoked.
14402
14403 5. If a target was included in the "with" statement, the return value
14404 from "__enter__()" is assigned to it.
14405
14406 Note:
14407
14408 The "with" statement guarantees that if the "__enter__()" method
14409 returns without an error, then "__exit__()" will always be
14410 called. Thus, if an error occurs during the assignment to the
14411 target list, it will be treated the same as an error occurring
14412 within the suite would be. See step 7 below.
14413
14414 6. The suite is executed.
14415
14416 7. The context manager’s "__exit__()" method is invoked. If an
14417 exception caused the suite to be exited, its type, value, and
14418 traceback are passed as arguments to "__exit__()". Otherwise, three
14419 "None" arguments are supplied.
14420
14421 If the suite was exited due to an exception, and the return value
14422 from the "__exit__()" method was false, the exception is reraised.
14423 If the return value was true, the exception is suppressed, and
14424 execution continues with the statement following the "with"
14425 statement.
14426
14427 If the suite was exited for any reason other than an exception, the
14428 return value from "__exit__()" is ignored, and execution proceeds
14429 at the normal location for the kind of exit that was taken.
14430
14431 The following code:
14432
14433 with EXPRESSION as TARGET:
14434 SUITE
14435
14436 is semantically equivalent to:
14437
14438 manager = (EXPRESSION)
14439 enter = manager.__enter__
14440 exit = manager.__exit__
14441 value = enter()
14442 hit_except = False
14443
14444 try:
14445 TARGET = value
14446 SUITE
14447 except:
14448 hit_except = True
14449 if not exit(*sys.exc_info()):
14450 raise
14451 finally:
14452 if not hit_except:
14453 exit(None, None, None)
14454
14455 except that implicit special method lookup is used for "__enter__()"
14456 and "__exit__()".
14457
14458 With more than one item, the context managers are processed as if
14459 multiple "with" statements were nested:
14460
14461 with A() as a, B() as b:
14462 SUITE
14463
14464 is semantically equivalent to:
14465
14466 with A() as a:
14467 with B() as b:
14468 SUITE
14469
14470 You can also write multi-item context managers in multiple lines if
14471 the items are surrounded by parentheses. For example:
14472
14473 with (
14474 A() as a,
14475 B() as b,
14476 ):
14477 SUITE
14478
14479 Changed in version 3.1: Support for multiple context expressions.
14480
14481 Changed in version 3.10: Support for using grouping parentheses to
14482 break the statement in multiple lines.
14483
14484 See also:
14485
14486 **PEP 343** - The “with” statement
14487 The specification, background, and examples for the Python "with"
14488 statement.
14489 ''',
14490 'yield': r'''The "yield" statement
14491 *********************
14492
14493 yield_stmt: yield_expression
14494
14495 A "yield" statement is semantically equivalent to a yield expression.
14496 The "yield" statement can be used to omit the parentheses that would
14497 otherwise be required in the equivalent yield expression statement.
14498 For example, the yield statements
14499
14500 yield <expr>
14501 yield from <expr>
14502
14503 are equivalent to the yield expression statements
14504
14505 (yield <expr>)
14506 (yield from <expr>)
14507
14508 Yield expressions and statements are only used when defining a
14509 *generator* function, and are only used in the body of the generator
14510 function. Using "yield" in a function definition is sufficient to
14511 cause that definition to create a generator function instead of a
14512 normal function.
14513
14514 For full details of "yield" semantics, refer to the Yield expressions
14515 section.
14516 ''',
14517 }