Debian Codegraph @

Lib/pydoc_data/topics.py

raw
1 # Autogenerated by Sphinx on Wed Jun 10 13:03:46 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: flexible_expression "," [flexible_expression_list [',']]
2231 | assignment_expression
2232 case_block: 'case' patterns [guard] ":" suite
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" assignment_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'" float presentation type or
5776 integer presentation type instead.
5777
5778 Changed in version 3.1: Added the "','" option (see also **PEP 378**).
5779
5780 Changed in version 3.6: Added the "'_'" option (see also **PEP 515**).
5781
5782 Changed in version 3.14: Support the *grouping* option for the
5783 fractional part.
5784
5785 Finally, the *type* determines how the data should be presented.
5786
5787 The available string presentation types are:
5788
5789 +-----------+------------------------------------------------------------+
5790 | Type | Meaning |
5791 |===========|============================================================|
5792 | "'s'" | String format. This is the default type for strings and |
5793 | | may be omitted. |
5794 +-----------+------------------------------------------------------------+
5795 | None | The same as "'s'". |
5796 +-----------+------------------------------------------------------------+
5797
5798 The available integer presentation types are:
5799
5800 +-----------+------------------------------------------------------------+
5801 | Type | Meaning |
5802 |===========|============================================================|
5803 | "'b'" | Binary format. Outputs the number in base 2. |
5804 +-----------+------------------------------------------------------------+
5805 | "'c'" | Character. Converts the integer to the corresponding |
5806 | | unicode character before printing. |
5807 +-----------+------------------------------------------------------------+
5808 | "'d'" | Decimal Integer. Outputs the number in base 10. |
5809 +-----------+------------------------------------------------------------+
5810 | "'o'" | Octal format. Outputs the number in base 8. |
5811 +-----------+------------------------------------------------------------+
5812 | "'x'" | Hex format. Outputs the number in base 16, using lower- |
5813 | | case letters for the digits above 9. |
5814 +-----------+------------------------------------------------------------+
5815 | "'X'" | Hex format. Outputs the number in base 16, using upper- |
5816 | | case letters for the digits above 9. In case "'#'" is |
5817 | | specified, the prefix "'0x'" will be upper-cased to "'0X'" |
5818 | | as well. |
5819 +-----------+------------------------------------------------------------+
5820 | "'n'" | Number. This is the same as "'d'", except that it uses the |
5821 | | current locale setting to insert the appropriate digit |
5822 | | group separators. Note that the default locale is not the |
5823 | | system locale. Depending on your use case, you may wish to |
5824 | | set "LC_NUMERIC" with "locale.setlocale()" before using |
5825 | | "'n'". |
5826 +-----------+------------------------------------------------------------+
5827 | None | The same as "'d'". |
5828 +-----------+------------------------------------------------------------+
5829
5830 In addition to the above presentation types, integers can be formatted
5831 with the floating-point presentation types listed below (except "'n'"
5832 and "None"). When doing so, "float()" is used to convert the integer
5833 to a floating-point number before formatting.
5834
5835 The available presentation types for "float" and "Decimal" values are:
5836
5837 +-----------+------------------------------------------------------------+
5838 | Type | Meaning |
5839 |===========|============================================================|
5840 | "'e'" | Scientific notation. For a given precision "p", formats |
5841 | | the number in scientific notation with the letter ‘e’ |
5842 | | separating the coefficient from the exponent. The |
5843 | | coefficient has one digit before and "p" digits after the |
5844 | | decimal point, for a total of "p + 1" significant digits. |
5845 | | With no precision given, uses a precision of "6" digits |
5846 | | after the decimal point for "float", and shows all |
5847 | | coefficient digits for "Decimal". If "p=0", the decimal |
5848 | | point is omitted unless the "#" option is used. For |
5849 | | "float", the exponent always contains at least two digits, |
5850 | | and is zero if the value is zero. |
5851 +-----------+------------------------------------------------------------+
5852 | "'E'" | Scientific notation. Same as "'e'" except it uses an upper |
5853 | | case ‘E’ as the separator character. |
5854 +-----------+------------------------------------------------------------+
5855 | "'f'" | Fixed-point notation. For a given precision "p", formats |
5856 | | the number as a decimal number with exactly "p" digits |
5857 | | following the decimal point. With no precision given, uses |
5858 | | a precision of "6" digits after the decimal point for |
5859 | | "float", and uses a precision large enough to show all |
5860 | | coefficient digits for "Decimal". If "p=0", the decimal |
5861 | | point is omitted unless the "#" option is used. |
5862 +-----------+------------------------------------------------------------+
5863 | "'F'" | Fixed-point notation. Same as "'f'", but converts "nan" to |
5864 | | "NAN" and "inf" to "INF". |
5865 +-----------+------------------------------------------------------------+
5866 | "'g'" | General format. For a given precision "p >= 1", this |
5867 | | rounds the number to "p" significant digits and then |
5868 | | formats the result in either fixed-point format or in |
5869 | | scientific notation, depending on its magnitude. A |
5870 | | precision of "0" is treated as equivalent to a precision |
5871 | | of "1". The precise rules are as follows: suppose that |
5872 | | the result formatted with presentation type "'e'" and |
5873 | | precision "p-1" would have exponent "exp". Then, if "m <= |
5874 | | exp < p", where "m" is -4 for floats and -6 for |
5875 | | "Decimals", the number is formatted with presentation type |
5876 | | "'f'" and precision "p-1-exp". Otherwise, the number is |
5877 | | formatted with presentation type "'e'" and precision |
5878 | | "p-1". In both cases insignificant trailing zeros are |
5879 | | removed from the significand, and the decimal point is |
5880 | | also removed if there are no remaining digits following |
5881 | | it, unless the "'#'" option is used. With no precision |
5882 | | given, uses a precision of "6" significant digits for |
5883 | | "float". For "Decimal", the coefficient of the result is |
5884 | | formed from the coefficient digits of the value; |
5885 | | scientific notation is used for values smaller than "1e-6" |
5886 | | in absolute value and values where the place value of the |
5887 | | least significant digit is larger than 1, and fixed-point |
5888 | | notation is used otherwise. Positive and negative |
5889 | | infinity, positive and negative zero, and nans, are |
5890 | | formatted as "inf", "-inf", "0", "-0" and "nan" |
5891 | | respectively, regardless of the precision. |
5892 +-----------+------------------------------------------------------------+
5893 | "'G'" | General format. Same as "'g'" except switches to "'E'" if |
5894 | | the number gets too large. The representations of infinity |
5895 | | and NaN are uppercased, too. |
5896 +-----------+------------------------------------------------------------+
5897 | "'n'" | Number. This is the same as "'g'", except that it uses the |
5898 | | current locale setting to insert the appropriate digit |
5899 | | group separators for the integral part of a number. Note |
5900 | | that the default locale is not the system locale. |
5901 | | Depending on your use case, you may wish to set |
5902 | | "LC_NUMERIC" with "locale.setlocale()" before using "'n'". |
5903 +-----------+------------------------------------------------------------+
5904 | "'%'" | Percentage. Multiplies the number by 100 and displays in |
5905 | | fixed ("'f'") format, followed by a percent sign. |
5906 +-----------+------------------------------------------------------------+
5907 | None | For "float" this is like the "'g'" type, except that when |
5908 | | fixed- point notation is used to format the result, it |
5909 | | always includes at least one digit past the decimal point, |
5910 | | and switches to the scientific notation when "exp >= p - |
5911 | | 1". When the precision is not specified, the latter will |
5912 | | be as large as needed to represent the given value |
5913 | | faithfully. For "Decimal", this is the same as either |
5914 | | "'g'" or "'G'" depending on the value of |
5915 | | "context.capitals" for the current decimal context. The |
5916 | | overall effect is to match the output of "str()" as |
5917 | | altered by the other format modifiers. |
5918 +-----------+------------------------------------------------------------+
5919
5920 The result should be correctly rounded to a given precision "p" of
5921 digits after the decimal point. The rounding mode for "float" matches
5922 that of the "round()" builtin. For "Decimal", the rounding mode of
5923 the current context will be used.
5924
5925 The available presentation types for "complex" are the same as those
5926 for "float" ("'%'" is not allowed). Both the real and imaginary
5927 components of a complex number are formatted as floating-point
5928 numbers, according to the specified presentation type. They are
5929 separated by the mandatory sign of the imaginary part, the latter
5930 being terminated by a "j" suffix. If the presentation type is
5931 missing, the result will match the output of "str()" (complex numbers
5932 with a non-zero real part are also surrounded by parentheses),
5933 possibly altered by other format modifiers.
5934
5935
5936 Format examples
5937 ===============
5938
5939 This section contains examples of the "str.format()" syntax and
5940 comparison with the old "%"-formatting.
5941
5942 In most of the cases the syntax is similar to the old "%"-formatting,
5943 with the addition of the "{}" and with ":" used instead of "%". For
5944 example, "'%03.2f'" can be translated to "'{:03.2f}'".
5945
5946 The new format syntax also supports new and different options, shown
5947 in the following examples.
5948
5949 Accessing arguments by position:
5950
5951 >>> '{0}, {1}, {2}'.format('a', 'b', 'c')
5952 'a, b, c'
5953 >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only
5954 'a, b, c'
5955 >>> '{2}, {1}, {0}'.format('a', 'b', 'c')
5956 'c, b, a'
5957 >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence
5958 'c, b, a'
5959 >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated
5960 'abracadabra'
5961
5962 Accessing arguments by name:
5963
5964 >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
5965 'Coordinates: 37.24N, -115.81W'
5966 >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
5967 >>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
5968 'Coordinates: 37.24N, -115.81W'
5969
5970 Accessing arguments’ attributes:
5971
5972 >>> c = 3-5j
5973 >>> ('The complex number {0} is formed from the real part {0.real} '
5974 ... 'and the imaginary part {0.imag}.').format(c)
5975 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
5976 >>> class Point:
5977 ... def __init__(self, x, y):
5978 ... self.x, self.y = x, y
5979 ... def __str__(self):
5980 ... return 'Point({self.x}, {self.y})'.format(self=self)
5981 ...
5982 >>> str(Point(4, 2))
5983 'Point(4, 2)'
5984
5985 Accessing arguments’ items:
5986
5987 >>> coord = (3, 5)
5988 >>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
5989 'X: 3; Y: 5'
5990
5991 Replacing "%s" and "%r":
5992
5993 >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
5994 "repr() shows quotes: 'test1'; str() doesn't: test2"
5995
5996 Aligning the text and specifying a width:
5997
5998 >>> '{:<30}'.format('left aligned')
5999 'left aligned '
6000 >>> '{:>30}'.format('right aligned')
6001 ' right aligned'
6002 >>> '{:^30}'.format('centered')
6003 ' centered '
6004 >>> '{:*^30}'.format('centered') # use '*' as a fill char
6005 '***********centered***********'
6006
6007 Replacing "%+f", "%-f", and "% f" and specifying a sign:
6008
6009 >>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it always
6010 '+3.140000; -3.140000'
6011 >>> '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
6012 ' 3.140000; -3.140000'
6013 >>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}'
6014 '3.140000; -3.140000'
6015
6016 Replacing "%x" and "%o" and converting the value to different bases:
6017
6018 >>> # format also supports binary numbers
6019 >>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
6020 'int: 42; hex: 2a; oct: 52; bin: 101010'
6021 >>> # with 0x, 0o, or 0b as prefix:
6022 >>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
6023 'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
6024
6025 Using the comma or the underscore as a digit group separator:
6026
6027 >>> '{:,}'.format(1234567890)
6028 '1,234,567,890'
6029 >>> '{:_}'.format(1234567890)
6030 '1_234_567_890'
6031 >>> '{:_b}'.format(1234567890)
6032 '100_1001_1001_0110_0000_0010_1101_0010'
6033 >>> '{:_x}'.format(1234567890)
6034 '4996_02d2'
6035 >>> '{:_}'.format(123456789.123456789)
6036 '123_456_789.12345679'
6037 >>> '{:.,}'.format(123456789.123456789)
6038 '123456789.123,456,79'
6039 >>> '{:,._}'.format(123456789.123456789)
6040 '123,456,789.123_456_79'
6041
6042 Expressing a percentage:
6043
6044 >>> points = 19
6045 >>> total = 22
6046 >>> 'Correct answers: {:.2%}'.format(points/total)
6047 'Correct answers: 86.36%'
6048
6049 Using type-specific formatting:
6050
6051 >>> import datetime as dt
6052 >>> d = dt.datetime(2010, 7, 4, 12, 15, 58)
6053 >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
6054 '2010-07-04 12:15:58'
6055
6056 Nesting arguments and more complex examples:
6057
6058 >>> for align, text in zip('<^>', ['left', 'center', 'right']):
6059 ... '{0:{fill}{align}16}'.format(text, fill=align, align=align)
6060 ...
6061 'left<<<<<<<<<<<<'
6062 '^^^^^center^^^^^'
6063 '>>>>>>>>>>>right'
6064 >>>
6065 >>> octets = [192, 168, 0, 1]
6066 >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
6067 'C0A80001'
6068 >>> int(_, 16)
6069 3232235521
6070 >>>
6071 >>> width = 5
6072 >>> for num in range(5,12):
6073 ... for base in 'dXob':
6074 ... print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
6075 ... print()
6076 ...
6077 5 5 5 101
6078 6 6 6 110
6079 7 7 7 111
6080 8 8 10 1000
6081 9 9 11 1001
6082 10 A 12 1010
6083 11 B 13 1011
6084 ''',
6085 'function': r'''Function definitions
6086 ********************
6087
6088 A function definition defines a user-defined function object (see
6089 section The standard type hierarchy):
6090
6091 funcdef: [decorators] "def" funcname [type_params] "(" [parameter_list] ")"
6092 ["->" expression] ":" suite
6093 decorators: decorator+
6094 decorator: "@" assignment_expression NEWLINE
6095 parameter_list: defparameter ("," defparameter)* "," "/" ["," [parameter_list_no_posonly]]
6096 | parameter_list_no_posonly
6097 parameter_list_no_posonly: defparameter ("," defparameter)* ["," [parameter_list_starargs]]
6098 | parameter_list_starargs
6099 parameter_list_starargs: "*" [star_parameter] ("," defparameter)* ["," [parameter_star_kwargs]]
6100 | "*" ("," defparameter)+ ["," [parameter_star_kwargs]]
6101 | parameter_star_kwargs
6102 parameter_star_kwargs: "**" parameter [","]
6103 parameter: identifier [":" expression]
6104 star_parameter: identifier [":" ["*"] expression]
6105 defparameter: parameter ["=" expression]
6106 funcname: identifier
6107
6108 A function definition is an executable statement. Its execution binds
6109 the function name in the current local namespace to a function object
6110 (a wrapper around the executable code for the function). This
6111 function object contains a reference to the current global namespace
6112 as the global namespace to be used when the function is called.
6113
6114 The function definition does not execute the function body; this gets
6115 executed only when the function is called. [4]
6116
6117 A function definition may be wrapped by one or more *decorator*
6118 expressions. Decorator expressions are evaluated when the function is
6119 defined, in the scope that contains the function definition. The
6120 result must be a callable, which is invoked with the function object
6121 as the only argument. The returned value is bound to the function name
6122 instead of the function object. Multiple decorators are applied in
6123 nested fashion. For example, the following code
6124
6125 @f1(arg)
6126 @f2
6127 def func(): pass
6128
6129 is roughly equivalent to
6130
6131 def func(): pass
6132 func = f1(arg)(f2(func))
6133
6134 except that the original function is not temporarily bound to the name
6135 "func".
6136
6137 Changed in version 3.9: Functions may be decorated with any valid
6138 "assignment_expression". Previously, the grammar was much more
6139 restrictive; see **PEP 614** for details.
6140
6141 A list of type parameters may be given in square brackets between the
6142 function’s name and the opening parenthesis for its parameter list.
6143 This indicates to static type checkers that the function is generic.
6144 At runtime, the type parameters can be retrieved from the function’s
6145 "__type_params__" attribute. See Generic functions for more.
6146
6147 Changed in version 3.12: Type parameter lists are new in Python 3.12.
6148
6149 When one or more *parameters* have the form *parameter* "="
6150 *expression*, the function is said to have “default parameter values.”
6151 For a parameter with a default value, the corresponding *argument* may
6152 be omitted from a call, in which case the parameter’s default value is
6153 substituted. If a parameter has a default value, all following
6154 parameters up until the “"*"” must also have a default value — this is
6155 a syntactic restriction that is not expressed by the grammar.
6156
6157 **Default parameter values are evaluated from left to right when the
6158 function definition is executed.** This means that the expression is
6159 evaluated once, when the function is defined, and that the same “pre-
6160 computed” value is used for each call. This is especially important
6161 to understand when a default parameter value is a mutable object, such
6162 as a list or a dictionary: if the function modifies the object (e.g.
6163 by appending an item to a list), the default parameter value is in
6164 effect modified. This is generally not what was intended. A way
6165 around this is to use "None" as the default, and explicitly test for
6166 it in the body of the function, e.g.:
6167
6168 def whats_on_the_telly(penguin=None):
6169 if penguin is None:
6170 penguin = []
6171 penguin.append("property of the zoo")
6172 return penguin
6173
6174 Function call semantics are described in more detail in section Calls.
6175 A function call always assigns values to all parameters mentioned in
6176 the parameter list, either from positional arguments, from keyword
6177 arguments, or from default values. If the form “"*identifier"” is
6178 present, it is initialized to a tuple receiving any excess positional
6179 parameters, defaulting to the empty tuple. If the form
6180 “"**identifier"” is present, it is initialized to a new ordered
6181 mapping receiving any excess keyword arguments, defaulting to a new
6182 empty mapping of the same type. Parameters after “"*"” or
6183 “"*identifier"” are keyword-only parameters and may only be passed by
6184 keyword arguments. Parameters before “"/"” are positional-only
6185 parameters and may only be passed by positional arguments.
6186
6187 Changed in version 3.8: The "/" function parameter syntax may be used
6188 to indicate positional-only parameters. See **PEP 570** for details.
6189
6190 Parameters may have an *annotation* of the form “": expression"”
6191 following the parameter name. Any parameter may have an annotation,
6192 even those of the form "*identifier" or "**identifier". (As a special
6193 case, parameters of the form "*identifier" may have an annotation “":
6194 *expression"”.) Functions may have “return” annotation of the form
6195 “"-> expression"” after the parameter list. These annotations can be
6196 any valid Python expression. The presence of annotations does not
6197 change the semantics of a function. See Annotations for more
6198 information on annotations.
6199
6200 Changed in version 3.11: Parameters of the form “"*identifier"” may
6201 have an annotation “": *expression"”. See **PEP 646**.
6202
6203 It is also possible to create anonymous functions (functions not bound
6204 to a name), for immediate use in expressions. This uses lambda
6205 expressions, described in section Lambdas. Note that the lambda
6206 expression is merely a shorthand for a simplified function definition;
6207 a function defined in a “"def"” statement can be passed around or
6208 assigned to another name just like a function defined by a lambda
6209 expression. The “"def"” form is actually more powerful since it
6210 allows the execution of multiple statements and annotations.
6211
6212 **Programmer’s note:** Functions are first-class objects. A “"def"”
6213 statement executed inside a function definition defines a local
6214 function that can be returned or passed around. Free variables used
6215 in the nested function can access the local variables of the function
6216 containing the def. See section Naming and binding for details.
6217
6218 See also:
6219
6220 **PEP 3107** - Function Annotations
6221 The original specification for function annotations.
6222
6223 **PEP 484** - Type Hints
6224 Definition of a standard meaning for annotations: type hints.
6225
6226 **PEP 526** - Syntax for Variable Annotations
6227 Ability to type hint variable declarations, including class
6228 variables and instance variables.
6229
6230 **PEP 563** - Postponed Evaluation of Annotations
6231 Support for forward references within annotations by preserving
6232 annotations in a string form at runtime instead of eager
6233 evaluation.
6234
6235 **PEP 318** - Decorators for Functions and Methods
6236 Function and method decorators were introduced. Class decorators
6237 were introduced in **PEP 3129**.
6238 ''',
6239 'global': r'''The "global" statement
6240 **********************
6241
6242 global_stmt: "global" identifier ("," identifier)*
6243
6244 The "global" statement causes the listed identifiers to be interpreted
6245 as globals. It would be impossible to assign to a global variable
6246 without "global", although free variables may refer to globals without
6247 being declared global.
6248
6249 The "global" statement applies to the entire current scope (module,
6250 function body or class definition). A "SyntaxError" is raised if a
6251 variable is used or assigned to prior to its global declaration in the
6252 scope.
6253
6254 At the module level, all variables are global, so a "global" statement
6255 has no effect. However, variables must still not be used or assigned
6256 to prior to their "global" declaration. This requirement is relaxed in
6257 the interactive prompt (*REPL*).
6258
6259 **Programmer’s note:** "global" is a directive to the parser. It
6260 applies only to code parsed at the same time as the "global"
6261 statement. In particular, a "global" statement contained in a string
6262 or code object supplied to the built-in "exec()" function does not
6263 affect the code block *containing* the function call, and code
6264 contained in such a string is unaffected by "global" statements in the
6265 code containing the function call. The same applies to the "eval()"
6266 and "compile()" functions.
6267 ''',
6268 'id-classes': r'''Reserved classes of identifiers
6269 *******************************
6270
6271 Certain classes of identifiers (besides keywords) have special
6272 meanings. These classes are identified by the patterns of leading and
6273 trailing underscore characters:
6274
6275 "_*"
6276 Not imported by "from module import *".
6277
6278 "_"
6279 In a "case" pattern within a "match" statement, "_" is a soft
6280 keyword that denotes a wildcard.
6281
6282 Separately, the interactive interpreter makes the result of the
6283 last evaluation available in the variable "_". (It is stored in the
6284 "builtins" module, alongside built-in functions like "print".)
6285
6286 Elsewhere, "_" is a regular identifier. It is often used to name
6287 “special” items, but it is not special to Python itself.
6288
6289 Note:
6290
6291 The name "_" is often used in conjunction with
6292 internationalization; refer to the documentation for the
6293 "gettext" module for more information on this convention.It is
6294 also commonly used for unused variables.
6295
6296 "__*__"
6297 System-defined names, informally known as “dunder” names. These
6298 names are defined by the interpreter and its implementation
6299 (including the standard library). Current system names are
6300 discussed in the Special method names section and elsewhere. More
6301 will likely be defined in future versions of Python. *Any* use of
6302 "__*__" names, in any context, that does not follow explicitly
6303 documented use, is subject to breakage without warning.
6304
6305 "__*"
6306 Class-private names. Names in this category, when used within the
6307 context of a class definition, are re-written to use a mangled form
6308 to help avoid name clashes between “private” attributes of base and
6309 derived classes. See section Identifiers (Names).
6310 ''',
6311 'identifiers': r'''Names (identifiers and keywords)
6312 ********************************
6313
6314 "NAME" tokens represent *identifiers*, *keywords*, and *soft
6315 keywords*.
6316
6317 Names are composed of the following characters:
6318
6319 * uppercase and lowercase letters ("A-Z" and "a-z"),
6320
6321 * the underscore ("_"),
6322
6323 * digits ("0" through "9"), which cannot appear as the first
6324 character, and
6325
6326 * non-ASCII characters. Valid names may only contain “letter-like” and
6327 “digit-like” characters; see Non-ASCII characters in names for
6328 details.
6329
6330 Names must contain at least one character, but have no upper length
6331 limit. Case is significant.
6332
6333 Formally, names are described by the following lexical definitions:
6334
6335 NAME: name_start name_continue*
6336 name_start: "a"..."z" | "A"..."Z" | "_" | <non-ASCII character>
6337 name_continue: name_start | "0"..."9"
6338 identifier: <NAME, except keywords>
6339
6340 Note that not all names matched by this grammar are valid; see Non-
6341 ASCII characters in names for details.
6342
6343
6344 Keywords
6345 ========
6346
6347 The following names are used as reserved words, or *keywords* of the
6348 language, and cannot be used as ordinary identifiers. They must be
6349 spelled exactly as written here:
6350
6351 False await else import pass
6352 None break except in raise
6353 True class finally is return
6354 and continue for lambda try
6355 as def from nonlocal while
6356 assert del global not with
6357 async elif if or yield
6358
6359
6360 Soft Keywords
6361 =============
6362
6363 Added in version 3.10.
6364
6365 Some names are only reserved under specific contexts. These are known
6366 as *soft keywords*:
6367
6368 * "match", "case", and "_", when used in the "match" statement.
6369
6370 * "type", when used in the "type" statement.
6371
6372 These syntactically act as keywords in their specific contexts, but
6373 this distinction is done at the parser level, not when tokenizing.
6374
6375 As soft keywords, their use in the grammar is possible while still
6376 preserving compatibility with existing code that uses these names as
6377 identifier names.
6378
6379 Changed in version 3.12: "type" is now a soft keyword.
6380
6381
6382 Reserved classes of identifiers
6383 ===============================
6384
6385 Certain classes of identifiers (besides keywords) have special
6386 meanings. These classes are identified by the patterns of leading and
6387 trailing underscore characters:
6388
6389 "_*"
6390 Not imported by "from module import *".
6391
6392 "_"
6393 In a "case" pattern within a "match" statement, "_" is a soft
6394 keyword that denotes a wildcard.
6395
6396 Separately, the interactive interpreter makes the result of the
6397 last evaluation available in the variable "_". (It is stored in the
6398 "builtins" module, alongside built-in functions like "print".)
6399
6400 Elsewhere, "_" is a regular identifier. It is often used to name
6401 “special” items, but it is not special to Python itself.
6402
6403 Note:
6404
6405 The name "_" is often used in conjunction with
6406 internationalization; refer to the documentation for the
6407 "gettext" module for more information on this convention.It is
6408 also commonly used for unused variables.
6409
6410 "__*__"
6411 System-defined names, informally known as “dunder” names. These
6412 names are defined by the interpreter and its implementation
6413 (including the standard library). Current system names are
6414 discussed in the Special method names section and elsewhere. More
6415 will likely be defined in future versions of Python. *Any* use of
6416 "__*__" names, in any context, that does not follow explicitly
6417 documented use, is subject to breakage without warning.
6418
6419 "__*"
6420 Class-private names. Names in this category, when used within the
6421 context of a class definition, are re-written to use a mangled form
6422 to help avoid name clashes between “private” attributes of base and
6423 derived classes. See section Identifiers (Names).
6424
6425
6426 Non-ASCII characters in names
6427 =============================
6428
6429 Names that contain non-ASCII characters need additional normalization
6430 and validation beyond the rules and grammar explained above. For
6431 example, "ř_1", "蛇", or "साँप" are valid names, but "r〰2", "€", or
6432 "🐍" are not.
6433
6434 This section explains the exact rules.
6435
6436 All names are converted into the normalization form NFKC while
6437 parsing. This means that, for example, some typographic variants of
6438 characters are converted to their “basic” form. For example,
6439 "fiⁿₐˡᵢᶻₐᵗᵢᵒₙ" normalizes to "finalization", so Python treats them as
6440 the same name:
6441
6442 >>> fiⁿₐˡᵢᶻₐᵗᵢᵒₙ = 3
6443 >>> finalization
6444 3
6445
6446 Note:
6447
6448 Normalization is done at the lexical level only. Run-time functions
6449 that take names as *strings* generally do not normalize their
6450 arguments. For example, the variable defined above is accessible at
6451 run time in the "globals()" dictionary as
6452 "globals()["finalization"]" but not "globals()["fiⁿₐˡᵢᶻₐᵗᵢᵒₙ"]".
6453
6454 Similarly to how ASCII-only names must contain only letters, digits
6455 and the underscore, and cannot start with a digit, a valid name must
6456 start with a character in the “letter-like” set "xid_start", and the
6457 remaining characters must be in the “letter- and digit-like” set
6458 "xid_continue".
6459
6460 These sets are based on the *XID_Start* and *XID_Continue* sets as
6461 defined by the Unicode standard annex UAX-31. Python’s "xid_start"
6462 additionally includes the underscore ("_"). Note that Python does not
6463 necessarily conform to UAX-31.
6464
6465 A non-normative listing of characters in the *XID_Start* and
6466 *XID_Continue* sets as defined by Unicode is available in the
6467 DerivedCoreProperties.txt file in the Unicode Character Database. For
6468 reference, the construction rules for the "xid_*" sets are given
6469 below.
6470
6471 The set "id_start" is defined as the union of:
6472
6473 * Unicode category "<Lu>" - uppercase letters (includes "A" to "Z")
6474
6475 * Unicode category "<Ll>" - lowercase letters (includes "a" to "z")
6476
6477 * Unicode category "<Lt>" - titlecase letters
6478
6479 * Unicode category "<Lm>" - modifier letters
6480
6481 * Unicode category "<Lo>" - other letters
6482
6483 * Unicode category "<Nl>" - letter numbers
6484
6485 * {""_""} - the underscore
6486
6487 * "<Other_ID_Start>" - an explicit set of characters in PropList.txt
6488 to support backwards compatibility
6489
6490 The set "xid_start" then closes this set under NFKC normalization, by
6491 removing all characters whose normalization is not of the form
6492 "id_start id_continue*".
6493
6494 The set "id_continue" is defined as the union of:
6495
6496 * "id_start" (see above)
6497
6498 * Unicode category "<Nd>" - decimal numbers (includes "0" to "9")
6499
6500 * Unicode category "<Pc>" - connector punctuations
6501
6502 * Unicode category "<Mn>" - nonspacing marks
6503
6504 * Unicode category "<Mc>" - spacing combining marks
6505
6506 * "<Other_ID_Continue>" - another explicit set of characters in
6507 PropList.txt to support backwards compatibility
6508
6509 Again, "xid_continue" closes this set under NFKC normalization.
6510
6511 Unicode categories use the version of the Unicode Character Database
6512 as included in the "unicodedata" module.
6513
6514 See also:
6515
6516 * **PEP 3131** – Supporting Non-ASCII Identifiers
6517
6518 * **PEP 672** – Unicode-related Security Considerations for Python
6519 ''',
6520 'if': r'''The "if" statement
6521 ******************
6522
6523 The "if" statement is used for conditional execution:
6524
6525 if_stmt: "if" assignment_expression ":" suite
6526 ("elif" assignment_expression ":" suite)*
6527 ["else" ":" suite]
6528
6529 It selects exactly one of the suites by evaluating the expressions one
6530 by one until one is found to be true (see section Boolean operations
6531 for the definition of true and false); then that suite is executed
6532 (and no other part of the "if" statement is executed or evaluated).
6533 If all expressions are false, the suite of the "else" clause, if
6534 present, is executed.
6535 ''',
6536 'imaginary': r'''Imaginary literals
6537 ******************
6538
6539 Python has complex number objects, but no complex literals. Instead,
6540 *imaginary literals* denote complex numbers with a zero real part.
6541
6542 For example, in math, the complex number 3+4.2*i* is written as the
6543 real number 3 added to the imaginary number 4.2*i*. Python uses a
6544 similar syntax, except the imaginary unit is written as "j" rather
6545 than *i*:
6546
6547 3+4.2j
6548
6549 This is an expression composed of the integer literal "3", the
6550 operator ‘"+"’, and the imaginary literal "4.2j". Since these are
6551 three separate tokens, whitespace is allowed between them:
6552
6553 3 + 4.2j
6554
6555 No whitespace is allowed *within* each token. In particular, the "j"
6556 suffix, may not be separated from the number before it.
6557
6558 The number before the "j" has the same syntax as a floating-point
6559 literal. Thus, the following are valid imaginary literals:
6560
6561 4.2j
6562 3.14j
6563 10.j
6564 .001j
6565 1e100j
6566 3.14e-10j
6567 3.14_15_93j
6568
6569 Unlike in a floating-point literal the decimal point can be omitted if
6570 the imaginary number only has an integer part. The number is still
6571 evaluated as a floating-point number, not an integer:
6572
6573 10j
6574 0j
6575 1000000000000000000000000j # equivalent to 1e+24j
6576
6577 The "j" suffix is case-insensitive. That means you can use "J"
6578 instead:
6579
6580 3.14J # equivalent to 3.14j
6581
6582 Formally, imaginary literals are described by the following lexical
6583 definition:
6584
6585 imagnumber: (floatnumber | digitpart) ("j" | "J")
6586 ''',
6587 'import': r'''The "import" statement
6588 **********************
6589
6590 import_stmt: "import" module ["as" identifier] ("," module ["as" identifier])*
6591 | "from" relative_module "import" identifier ["as" identifier]
6592 ("," identifier ["as" identifier])*
6593 | "from" relative_module "import" "(" identifier ["as" identifier]
6594 ("," identifier ["as" identifier])* [","] ")"
6595 | "from" relative_module "import" "*"
6596 module: (identifier ".")* identifier
6597 relative_module: "."* module | "."+
6598
6599 The basic import statement (no "from" clause) is executed in two
6600 steps:
6601
6602 1. find a module, loading and initializing it if necessary
6603
6604 2. define a name or names in the current namespace for the scope where
6605 the "import" statement occurs, just as an assignment statement
6606 would (including "global" and "nonlocal" semantics).
6607
6608 When the statement contains multiple clauses (separated by commas) the
6609 two steps are carried out separately for each clause, just as though
6610 the clauses had been separated out into individual import statements.
6611
6612 The details of the first step, finding and loading modules, are
6613 described in greater detail in the section on the import system, which
6614 also describes the various types of packages and modules that can be
6615 imported, as well as all the hooks that can be used to customize the
6616 import system. Note that failures in this step may indicate either
6617 that the module could not be located, *or* that an error occurred
6618 while initializing the module, which includes execution of the
6619 module’s code.
6620
6621 If the requested module is retrieved successfully, it will be made
6622 available in the local namespace in one of three ways:
6623
6624 * If the module name is followed by "as", then the name following "as"
6625 is bound directly to the imported module.
6626
6627 * If no other name is specified, and the module being imported is a
6628 top level module, the module’s name is bound in the local namespace
6629 as a reference to the imported module
6630
6631 * If the module being imported is *not* a top level module, then the
6632 name of the top level package that contains the module is bound in
6633 the local namespace as a reference to the top level package. The
6634 imported module must be accessed using its full qualified name
6635 rather than directly
6636
6637 The "from" form uses a slightly more complex process:
6638
6639 1. find the module specified in the "from" clause, loading and
6640 initializing it if necessary;
6641
6642 2. for each of the identifiers specified in the "import" clauses:
6643
6644 1. check if the imported module has an attribute by that name
6645
6646 2. if not, attempt to import a submodule with that name and then
6647 check the imported module again for that attribute
6648
6649 3. if the attribute is not found, "ImportError" is raised.
6650
6651 4. otherwise, a reference to that value is stored in the current
6652 namespace, using the name in the "as" clause if it is present,
6653 otherwise using the attribute name
6654
6655 Examples:
6656
6657 import foo # foo imported and bound locally
6658 import foo.bar.baz # foo, foo.bar, and foo.bar.baz imported, foo bound locally
6659 import foo.bar.baz as fbb # foo, foo.bar, and foo.bar.baz imported, foo.bar.baz bound as fbb
6660 from foo.bar import baz # foo, foo.bar, and foo.bar.baz imported, foo.bar.baz bound as baz
6661 from foo import attr # foo imported and foo.attr bound as attr
6662
6663 If the list of identifiers is replaced by a star ("'*'"), all public
6664 names defined in the module are bound in the local namespace for the
6665 scope where the "import" statement occurs.
6666
6667 The *public names* defined by a module are determined by checking the
6668 module’s namespace for a variable named "__all__"; if defined, it must
6669 be a sequence of strings which are names defined or imported by that
6670 module. Names containing non-ASCII characters must be in the
6671 normalization form NFKC; see Non-ASCII characters in names for
6672 details. The names given in "__all__" are all considered public and
6673 are required to exist. If "__all__" is not defined, the set of public
6674 names includes all names found in the module’s namespace which do not
6675 begin with an underscore character ("'_'"). "__all__" should contain
6676 the entire public API. It is intended to avoid accidentally exporting
6677 items that are not part of the API (such as library modules which were
6678 imported and used within the module).
6679
6680 The wild card form of import — "from module import *" — is only
6681 allowed at the module level. Attempting to use it in class or
6682 function definitions will raise a "SyntaxError".
6683
6684 When specifying what module to import you do not have to specify the
6685 absolute name of the module. When a module or package is contained
6686 within another package it is possible to make a relative import within
6687 the same top package without having to mention the package name. By
6688 using leading dots in the specified module or package after "from" you
6689 can specify how high to traverse up the current package hierarchy
6690 without specifying exact names. One leading dot means the current
6691 package where the module making the import exists. Two dots means up
6692 one package level. Three dots is up two levels, etc. So if you execute
6693 "from . import mod" from a module in the "pkg" package then you will
6694 end up importing "pkg.mod". If you execute "from ..subpkg2 import mod"
6695 from within "pkg.subpkg1" you will import "pkg.subpkg2.mod". The
6696 specification for relative imports is contained in the Package
6697 Relative Imports section.
6698
6699 "importlib.import_module()" is provided to support applications that
6700 determine dynamically the modules to be loaded.
6701
6702 Raises an auditing event "import" with arguments "module", "filename",
6703 "sys.path", "sys.meta_path", "sys.path_hooks".
6704
6705
6706 Future statements
6707 =================
6708
6709 A *future statement* is a directive to the compiler that a particular
6710 module should be compiled using syntax or semantics that will be
6711 available in a specified future release of Python where the feature
6712 becomes standard.
6713
6714 The future statement is intended to ease migration to future versions
6715 of Python that introduce incompatible changes to the language. It
6716 allows use of the new features on a per-module basis before the
6717 release in which the feature becomes standard.
6718
6719 future_stmt: "from" "__future__" "import" feature ["as" identifier]
6720 ("," feature ["as" identifier])*
6721 | "from" "__future__" "import" "(" feature ["as" identifier]
6722 ("," feature ["as" identifier])* [","] ")"
6723 feature: identifier
6724
6725 A future statement must appear near the top of the module. The only
6726 lines that can appear before a future statement are:
6727
6728 * the module docstring (if any),
6729
6730 * comments,
6731
6732 * blank lines, and
6733
6734 * other future statements.
6735
6736 The only feature that requires using the future statement is
6737 "annotations" (see **PEP 563**).
6738
6739 All historical features enabled by the future statement are still
6740 recognized by Python 3. The list includes "absolute_import",
6741 "division", "generators", "generator_stop", "unicode_literals",
6742 "print_function", "nested_scopes" and "with_statement". They are all
6743 redundant because they are always enabled, and only kept for backwards
6744 compatibility.
6745
6746 A future statement is recognized and treated specially at compile
6747 time: Changes to the semantics of core constructs are often
6748 implemented by generating different code. It may even be the case
6749 that a new feature introduces new incompatible syntax (such as a new
6750 reserved word), in which case the compiler may need to parse the
6751 module differently. Such decisions cannot be pushed off until
6752 runtime.
6753
6754 For any given release, the compiler knows which feature names have
6755 been defined, and raises a compile-time error if a future statement
6756 contains a feature not known to it.
6757
6758 The direct runtime semantics are the same as for any import statement:
6759 there is a standard module "__future__", described later, and it will
6760 be imported in the usual way at the time the future statement is
6761 executed.
6762
6763 The interesting runtime semantics depend on the specific feature
6764 enabled by the future statement.
6765
6766 Note that there is nothing special about the statement:
6767
6768 import __future__ [as name]
6769
6770 That is not a future statement; it’s an ordinary import statement with
6771 no special semantics or syntax restrictions.
6772
6773 Code compiled by calls to the built-in functions "exec()" and
6774 "compile()" that occur in a module "M" containing a future statement
6775 will, by default, use the new syntax or semantics associated with the
6776 future statement. This can be controlled by optional arguments to
6777 "compile()" — see the documentation of that function for details.
6778
6779 A future statement typed at an interactive interpreter prompt will
6780 take effect for the rest of the interpreter session. If an
6781 interpreter is started with the "-i" option, is passed a script name
6782 to execute, and the script includes a future statement, it will be in
6783 effect in the interactive session started after the script is
6784 executed.
6785
6786 See also:
6787
6788 **PEP 236** - Back to the __future__
6789 The original proposal for the __future__ mechanism.
6790 ''',
6791 'in': r'''Membership test operations
6792 **************************
6793
6794 The operators "in" and "not in" test for membership. "x in s"
6795 evaluates to "True" if *x* is a member of *s*, and "False" otherwise.
6796 "x not in s" returns the negation of "x in s". All built-in sequences
6797 and set types support this as well as dictionary, for which "in" tests
6798 whether the dictionary has a given key. For container types such as
6799 list, tuple, set, frozenset, dict, or collections.deque, the
6800 expression "x in y" is equivalent to "any(x is e or x == e for e in
6801 y)".
6802
6803 For the string and bytes types, "x in y" is "True" if and only if *x*
6804 is a substring of *y*. An equivalent test is "y.find(x) != -1".
6805 Empty strings are always considered to be a substring of any other
6806 string, so """ in "abc"" will return "True".
6807
6808 For user-defined classes which define the "__contains__()" method, "x
6809 in y" returns "True" if "y.__contains__(x)" returns a true value, and
6810 "False" otherwise.
6811
6812 For user-defined classes which do not define "__contains__()" but do
6813 define "__iter__()", "x in y" is "True" if some value "z", for which
6814 the expression "x is z or x == z" is true, is produced while iterating
6815 over "y". If an exception is raised during the iteration, it is as if
6816 "in" raised that exception.
6817
6818 Lastly, the old-style iteration protocol is tried: if a class defines
6819 "__getitem__()", "x in y" is "True" if and only if there is a non-
6820 negative integer index *i* such that "x is y[i] or x == y[i]", and no
6821 lower integer index raises the "IndexError" exception. (If any other
6822 exception is raised, it is as if "in" raised that exception).
6823
6824 The operator "not in" is defined to have the inverse truth value of
6825 "in".
6826 ''',
6827 'integers': r'''Integer literals
6828 ****************
6829
6830 Integer literals denote whole numbers. For example:
6831
6832 7
6833 3
6834 2147483647
6835
6836 There is no limit for the length of integer literals apart from what
6837 can be stored in available memory:
6838
6839 7922816251426433759354395033679228162514264337593543950336
6840
6841 Underscores can be used to group digits for enhanced readability, and
6842 are ignored for determining the numeric value of the literal. For
6843 example, the following literals are equivalent:
6844
6845 100_000_000_000
6846 100000000000
6847 1_00_00_00_00_000
6848
6849 Underscores can only occur between digits. For example, "_123",
6850 "321_", and "123__321" are *not* valid literals.
6851
6852 Integers can be specified in binary (base 2), octal (base 8), or
6853 hexadecimal (base 16) using the prefixes "0b", "0o" and "0x",
6854 respectively. Hexadecimal digits 10 through 15 are represented by
6855 letters "A"-"F", case-insensitive. For example:
6856
6857 0b100110111
6858 0b_1110_0101
6859 0o177
6860 0o377
6861 0xdeadbeef
6862 0xDead_Beef
6863
6864 An underscore can follow the base specifier. For example, "0x_1f" is a
6865 valid literal, but "0_x1f" and "0x__1f" are not.
6866
6867 Leading zeros in a non-zero decimal number are not allowed. For
6868 example, "0123" is not a valid literal. This is for disambiguation
6869 with C-style octal literals, which Python used before version 3.0.
6870
6871 Formally, integer literals are described by the following lexical
6872 definitions:
6873
6874 integer: decinteger | bininteger | octinteger | hexinteger | zerointeger
6875 decinteger: nonzerodigit (["_"] digit)*
6876 bininteger: "0" ("b" | "B") (["_"] bindigit)+
6877 octinteger: "0" ("o" | "O") (["_"] octdigit)+
6878 hexinteger: "0" ("x" | "X") (["_"] hexdigit)+
6879 zerointeger: "0"+ (["_"] "0")*
6880 nonzerodigit: "1"..."9"
6881 digit: "0"..."9"
6882 bindigit: "0" | "1"
6883 octdigit: "0"..."7"
6884 hexdigit: digit | "a"..."f" | "A"..."F"
6885
6886 Changed in version 3.6: Underscores are now allowed for grouping
6887 purposes in literals.
6888 ''',
6889 'lambda': r'''Lambdas
6890 *******
6891
6892 lambda_expr: "lambda" [parameter_list] ":" expression
6893
6894 Lambda expressions (sometimes called lambda forms) are used to create
6895 anonymous functions. The expression "lambda parameters: expression"
6896 yields a function object. The unnamed object behaves like a function
6897 object defined with:
6898
6899 def <lambda>(parameters):
6900 return expression
6901
6902 See section Function definitions for the syntax of parameter lists.
6903 Note that functions created with lambda expressions cannot contain
6904 statements or annotations.
6905 ''',
6906 'lists': r'''List displays
6907 *************
6908
6909 A list display is a possibly empty series of expressions enclosed in
6910 square brackets:
6911
6912 list_display: "[" [flexible_expression_list | comprehension] "]"
6913
6914 A list display yields a new list object, the contents being specified
6915 by either a list of expressions or a comprehension. When a comma-
6916 separated list of expressions is supplied, its elements are evaluated
6917 from left to right and placed into the list object in that order.
6918 When a comprehension is supplied, the list is constructed from the
6919 elements resulting from the comprehension.
6920 ''',
6921 'naming': r'''Naming and binding
6922 ******************
6923
6924
6925 Binding of names
6926 ================
6927
6928 *Names* refer to objects. Names are introduced by name binding
6929 operations.
6930
6931 The following constructs bind names:
6932
6933 * formal parameters to functions,
6934
6935 * class definitions,
6936
6937 * function definitions,
6938
6939 * assignment expressions,
6940
6941 * targets that are identifiers if occurring in an assignment:
6942
6943 * "for" loop header,
6944
6945 * after "as" in a "with" statement, "except" clause, "except*"
6946 clause, or in the as-pattern in structural pattern matching,
6947
6948 * in a capture pattern in structural pattern matching
6949
6950 * "import" statements.
6951
6952 * "type" statements.
6953
6954 * type parameter lists.
6955
6956 The "import" statement of the form "from ... import *" binds all names
6957 defined in the imported module, except those beginning with an
6958 underscore. This form may only be used at the module level.
6959
6960 A target occurring in a "del" statement is also considered bound for
6961 this purpose (though the actual semantics are to unbind the name).
6962
6963 Each assignment or import statement occurs within a block defined by a
6964 class or function definition or at the module level (the top-level
6965 code block).
6966
6967 If a name is bound in a block, it is a local variable of that block,
6968 unless declared as "nonlocal" or "global". If a name is bound at the
6969 module level, it is a global variable. (The variables of the module
6970 code block are local and global.) If a variable is used in a code
6971 block but not defined there, it is a *free variable*.
6972
6973 Each occurrence of a name in the program text refers to the *binding*
6974 of that name established by the following name resolution rules.
6975
6976
6977 Resolution of names
6978 ===================
6979
6980 A *scope* defines the visibility of a name within a block. If a local
6981 variable is defined in a block, its scope includes that block. If the
6982 definition occurs in a function block, the scope extends to any blocks
6983 contained within the defining one, unless a contained block introduces
6984 a different binding for the name.
6985
6986 When a name is used in a code block, it is resolved using the nearest
6987 enclosing scope. The set of all such scopes visible to a code block
6988 is called the block’s *environment*.
6989
6990 When a name is not found at all, a "NameError" exception is raised. If
6991 the current scope is a function scope, and the name refers to a local
6992 variable that has not yet been bound to a value at the point where the
6993 name is used, an "UnboundLocalError" exception is raised.
6994 "UnboundLocalError" is a subclass of "NameError".
6995
6996 If a name binding operation occurs anywhere within a code block, all
6997 uses of the name within the block are treated as references to the
6998 current block. This can lead to errors when a name is used within a
6999 block before it is bound. This rule is subtle. Python lacks
7000 declarations and allows name binding operations to occur anywhere
7001 within a code block. The local variables of a code block can be
7002 determined by scanning the entire text of the block for name binding
7003 operations. See the FAQ entry on UnboundLocalError for examples.
7004
7005 If the "global" statement occurs within a block, all uses of the names
7006 specified in the statement refer to the bindings of those names in the
7007 top-level namespace. Names are resolved in the top-level namespace by
7008 searching the global namespace, i.e. the namespace of the module
7009 containing the code block, and the builtins namespace, the namespace
7010 of the module "builtins". The global namespace is searched first. If
7011 the names are not found there, the builtins namespace is searched
7012 next. If the names are also not found in the builtins namespace, new
7013 variables are created in the global namespace. The global statement
7014 must precede all uses of the listed names.
7015
7016 The "global" statement has the same scope as a name binding operation
7017 in the same block. If the nearest enclosing scope for a free variable
7018 contains a global statement, the free variable is treated as a global.
7019
7020 The "nonlocal" statement causes corresponding names to refer to
7021 previously bound variables in the nearest enclosing function scope.
7022 "SyntaxError" is raised at compile time if the given name does not
7023 exist in any enclosing function scope. Type parameters cannot be
7024 rebound with the "nonlocal" statement.
7025
7026 The namespace for a module is automatically created the first time a
7027 module is imported. The main module for a script is always called
7028 "__main__".
7029
7030 Class definition blocks and arguments to "exec()" and "eval()" are
7031 special in the context of name resolution. A class definition is an
7032 executable statement that may use and define names. These references
7033 follow the normal rules for name resolution with an exception that
7034 unbound local variables are looked up in the global namespace. The
7035 namespace of the class definition becomes the attribute dictionary of
7036 the class. The scope of names defined in a class block is limited to
7037 the class block; it does not extend to the code blocks of methods.
7038 This includes comprehensions and generator expressions, but it does
7039 not include annotation scopes, which have access to their enclosing
7040 class scopes. This means that the following will fail:
7041
7042 class A:
7043 a = 42
7044 b = list(a + i for i in range(10))
7045
7046 However, the following will succeed:
7047
7048 class A:
7049 type Alias = Nested
7050 class Nested: pass
7051
7052 print(A.Alias.__value__) # <type 'A.Nested'>
7053
7054
7055 Annotation scopes
7056 =================
7057
7058 *Annotations*, type parameter lists and "type" statements introduce
7059 *annotation scopes*, which behave mostly like function scopes, but
7060 with some exceptions discussed below.
7061
7062 Annotation scopes are used in the following contexts:
7063
7064 * *Function annotations*.
7065
7066 * *Variable annotations*.
7067
7068 * Type parameter lists for generic type aliases.
7069
7070 * Type parameter lists for generic functions. A generic function’s
7071 annotations are executed within the annotation scope, but its
7072 defaults and decorators are not.
7073
7074 * Type parameter lists for generic classes. A generic class’s base
7075 classes and keyword arguments are executed within the annotation
7076 scope, but its decorators are not.
7077
7078 * The bounds, constraints, and default values for type parameters
7079 (lazily evaluated).
7080
7081 * The value of type aliases (lazily evaluated).
7082
7083 Annotation scopes differ from function scopes in the following ways:
7084
7085 * Annotation scopes have access to their enclosing class namespace. If
7086 an annotation scope is immediately within a class scope, or within
7087 another annotation scope that is immediately within a class scope,
7088 the code in the annotation scope can use names defined in the class
7089 scope as if it were executed directly within the class body. This
7090 contrasts with regular functions defined within classes, which
7091 cannot access names defined in the class scope.
7092
7093 * Expressions in annotation scopes cannot contain "yield", "yield
7094 from", "await", or ":=" expressions. (These expressions are allowed
7095 in other scopes contained within the annotation scope.)
7096
7097 * Names defined in annotation scopes cannot be rebound with "nonlocal"
7098 statements in inner scopes. This includes only type parameters, as
7099 no other syntactic elements that can appear within annotation scopes
7100 can introduce new names.
7101
7102 * While annotation scopes have an internal name, that name is not
7103 reflected in the *qualified name* of objects defined within the
7104 scope. Instead, the "__qualname__" of such objects is as if the
7105 object were defined in the enclosing scope.
7106
7107 Added in version 3.12: Annotation scopes were introduced in Python
7108 3.12 as part of **PEP 695**.
7109
7110 Changed in version 3.13: Annotation scopes are also used for type
7111 parameter defaults, as introduced by **PEP 696**.
7112
7113 Changed in version 3.14: Annotation scopes are now also used for
7114 annotations, as specified in **PEP 649** and **PEP 749**.
7115
7116
7117 Lazy evaluation
7118 ===============
7119
7120 Most annotation scopes are *lazily evaluated*. This includes
7121 annotations, the values of type aliases created through the "type"
7122 statement, and the bounds, constraints, and default values of type
7123 variables created through the type parameter syntax. This means that
7124 they are not evaluated when the type alias or type variable is
7125 created, or when the object carrying annotations is created. Instead,
7126 they are only evaluated when necessary, for example when the
7127 "__value__" attribute on a type alias is accessed.
7128
7129 Example:
7130
7131 >>> type Alias = 1/0
7132 >>> Alias.__value__
7133 Traceback (most recent call last):
7134 ...
7135 ZeroDivisionError: division by zero
7136 >>> def func[T: 1/0](): pass
7137 >>> T = func.__type_params__[0]
7138 >>> T.__bound__
7139 Traceback (most recent call last):
7140 ...
7141 ZeroDivisionError: division by zero
7142
7143 Here the exception is raised only when the "__value__" attribute of
7144 the type alias or the "__bound__" attribute of the type variable is
7145 accessed.
7146
7147 This behavior is primarily useful for references to types that have
7148 not yet been defined when the type alias or type variable is created.
7149 For example, lazy evaluation enables creation of mutually recursive
7150 type aliases:
7151
7152 from typing import Literal
7153
7154 type SimpleExpr = int | Parenthesized
7155 type Parenthesized = tuple[Literal["("], Expr, Literal[")"]]
7156 type Expr = SimpleExpr | tuple[SimpleExpr, Literal["+", "-"], Expr]
7157
7158 Lazily evaluated values are evaluated in annotation scope, which means
7159 that names that appear inside the lazily evaluated value are looked up
7160 as if they were used in the immediately enclosing scope.
7161
7162 Added in version 3.12.
7163
7164
7165 Builtins and restricted execution
7166 =================================
7167
7168 **CPython implementation detail:** Users should not touch
7169 "__builtins__"; it is strictly an implementation detail. Users
7170 wanting to override values in the builtins namespace should "import"
7171 the "builtins" module and modify its attributes appropriately.
7172
7173 The builtins namespace associated with the execution of a code block
7174 is actually found by looking up the name "__builtins__" in its global
7175 namespace; this should be a dictionary or a module (in the latter case
7176 the module’s dictionary is used). By default, when in the "__main__"
7177 module, "__builtins__" is the built-in module "builtins"; when in any
7178 other module, "__builtins__" is an alias for the dictionary of the
7179 "builtins" module itself.
7180
7181
7182 Interaction with dynamic features
7183 =================================
7184
7185 Name resolution of free variables occurs at runtime, not at compile
7186 time. This means that the following code will print 42:
7187
7188 i = 10
7189 def f():
7190 print(i)
7191 i = 42
7192 f()
7193
7194 The "eval()" and "exec()" functions do not have access to the full
7195 environment for resolving names. Names may be resolved in the local
7196 and global namespaces of the caller. Free variables are not resolved
7197 in the nearest enclosing namespace, but in the global namespace. [1]
7198 The "exec()" and "eval()" functions have optional arguments to
7199 override the global and local namespace. If only one namespace is
7200 specified, it is used for both.
7201 ''',
7202 'nonlocal': r'''The "nonlocal" statement
7203 ************************
7204
7205 nonlocal_stmt: "nonlocal" identifier ("," identifier)*
7206
7207 When the definition of a function or class is nested (enclosed) within
7208 the definitions of other functions, its nonlocal scopes are the local
7209 scopes of the enclosing functions. The "nonlocal" statement causes the
7210 listed identifiers to refer to names previously bound in nonlocal
7211 scopes. It allows encapsulated code to rebind such nonlocal
7212 identifiers. If a name is bound in more than one nonlocal scope, the
7213 nearest binding is used. If a name is not bound in any nonlocal scope,
7214 or if there is no nonlocal scope, a "SyntaxError" is raised.
7215
7216 The "nonlocal" statement applies to the entire scope of a function or
7217 class body. A "SyntaxError" is raised if a variable is used or
7218 assigned to prior to its nonlocal declaration in the scope.
7219
7220 See also:
7221
7222 **PEP 3104** - Access to Names in Outer Scopes
7223 The specification for the "nonlocal" statement.
7224
7225 **Programmer’s note:** "nonlocal" is a directive to the parser and
7226 applies only to code parsed along with it. See the note for the
7227 "global" statement.
7228 ''',
7229 'numbers': r'''Numeric literals
7230 ****************
7231
7232 "NUMBER" tokens represent numeric literals, of which there are three
7233 types: integers, floating-point numbers, and imaginary numbers.
7234
7235 NUMBER: integer | floatnumber | imagnumber
7236
7237 The numeric value of a numeric literal is the same as if it were
7238 passed as a string to the "int", "float" or "complex" class
7239 constructor, respectively. Note that not all valid inputs for those
7240 constructors are also valid literals.
7241
7242 Numeric literals do not include a sign; a phrase like "-1" is actually
7243 an expression composed of the unary operator ‘"-"’ and the literal
7244 "1".
7245
7246
7247 Integer literals
7248 ================
7249
7250 Integer literals denote whole numbers. For example:
7251
7252 7
7253 3
7254 2147483647
7255
7256 There is no limit for the length of integer literals apart from what
7257 can be stored in available memory:
7258
7259 7922816251426433759354395033679228162514264337593543950336
7260
7261 Underscores can be used to group digits for enhanced readability, and
7262 are ignored for determining the numeric value of the literal. For
7263 example, the following literals are equivalent:
7264
7265 100_000_000_000
7266 100000000000
7267 1_00_00_00_00_000
7268
7269 Underscores can only occur between digits. For example, "_123",
7270 "321_", and "123__321" are *not* valid literals.
7271
7272 Integers can be specified in binary (base 2), octal (base 8), or
7273 hexadecimal (base 16) using the prefixes "0b", "0o" and "0x",
7274 respectively. Hexadecimal digits 10 through 15 are represented by
7275 letters "A"-"F", case-insensitive. For example:
7276
7277 0b100110111
7278 0b_1110_0101
7279 0o177
7280 0o377
7281 0xdeadbeef
7282 0xDead_Beef
7283
7284 An underscore can follow the base specifier. For example, "0x_1f" is a
7285 valid literal, but "0_x1f" and "0x__1f" are not.
7286
7287 Leading zeros in a non-zero decimal number are not allowed. For
7288 example, "0123" is not a valid literal. This is for disambiguation
7289 with C-style octal literals, which Python used before version 3.0.
7290
7291 Formally, integer literals are described by the following lexical
7292 definitions:
7293
7294 integer: decinteger | bininteger | octinteger | hexinteger | zerointeger
7295 decinteger: nonzerodigit (["_"] digit)*
7296 bininteger: "0" ("b" | "B") (["_"] bindigit)+
7297 octinteger: "0" ("o" | "O") (["_"] octdigit)+
7298 hexinteger: "0" ("x" | "X") (["_"] hexdigit)+
7299 zerointeger: "0"+ (["_"] "0")*
7300 nonzerodigit: "1"..."9"
7301 digit: "0"..."9"
7302 bindigit: "0" | "1"
7303 octdigit: "0"..."7"
7304 hexdigit: digit | "a"..."f" | "A"..."F"
7305
7306 Changed in version 3.6: Underscores are now allowed for grouping
7307 purposes in literals.
7308
7309
7310 Floating-point literals
7311 =======================
7312
7313 Floating-point (float) literals, such as "3.14" or "1.5", denote
7314 approximations of real numbers.
7315
7316 They consist of *integer* and *fraction* parts, each composed of
7317 decimal digits. The parts are separated by a decimal point, ".":
7318
7319 2.71828
7320 4.0
7321
7322 Unlike in integer literals, leading zeros are allowed. For example,
7323 "077.010" is legal, and denotes the same number as "77.01".
7324
7325 As in integer literals, single underscores may occur between digits to
7326 help readability:
7327
7328 96_485.332_123
7329 3.14_15_93
7330
7331 Either of these parts, but not both, can be empty. For example:
7332
7333 10. # (equivalent to 10.0)
7334 .001 # (equivalent to 0.001)
7335
7336 Optionally, the integer and fraction may be followed by an *exponent*:
7337 the letter "e" or "E", followed by an optional sign, "+" or "-", and a
7338 number in the same format as the integer and fraction parts. The "e"
7339 or "E" represents “times ten raised to the power of”:
7340
7341 1.0e3 # (represents 1.0×10³, or 1000.0)
7342 1.166e-5 # (represents 1.166×10⁻⁵, or 0.00001166)
7343 6.02214076e+23 # (represents 6.02214076×10²³, or 602214076000000000000000.)
7344
7345 In floats with only integer and exponent parts, the decimal point may
7346 be omitted:
7347
7348 1e3 # (equivalent to 1.e3 and 1.0e3)
7349 0e0 # (equivalent to 0.)
7350
7351 Formally, floating-point literals are described by the following
7352 lexical definitions:
7353
7354 floatnumber:
7355 | digitpart "." [digitpart] [exponent]
7356 | "." digitpart [exponent]
7357 | digitpart exponent
7358 digitpart: digit (["_"] digit)*
7359 exponent: ("e" | "E") ["+" | "-"] digitpart
7360
7361 Changed in version 3.6: Underscores are now allowed for grouping
7362 purposes in literals.
7363
7364
7365 Imaginary literals
7366 ==================
7367
7368 Python has complex number objects, but no complex literals. Instead,
7369 *imaginary literals* denote complex numbers with a zero real part.
7370
7371 For example, in math, the complex number 3+4.2*i* is written as the
7372 real number 3 added to the imaginary number 4.2*i*. Python uses a
7373 similar syntax, except the imaginary unit is written as "j" rather
7374 than *i*:
7375
7376 3+4.2j
7377
7378 This is an expression composed of the integer literal "3", the
7379 operator ‘"+"’, and the imaginary literal "4.2j". Since these are
7380 three separate tokens, whitespace is allowed between them:
7381
7382 3 + 4.2j
7383
7384 No whitespace is allowed *within* each token. In particular, the "j"
7385 suffix, may not be separated from the number before it.
7386
7387 The number before the "j" has the same syntax as a floating-point
7388 literal. Thus, the following are valid imaginary literals:
7389
7390 4.2j
7391 3.14j
7392 10.j
7393 .001j
7394 1e100j
7395 3.14e-10j
7396 3.14_15_93j
7397
7398 Unlike in a floating-point literal the decimal point can be omitted if
7399 the imaginary number only has an integer part. The number is still
7400 evaluated as a floating-point number, not an integer:
7401
7402 10j
7403 0j
7404 1000000000000000000000000j # equivalent to 1e+24j
7405
7406 The "j" suffix is case-insensitive. That means you can use "J"
7407 instead:
7408
7409 3.14J # equivalent to 3.14j
7410
7411 Formally, imaginary literals are described by the following lexical
7412 definition:
7413
7414 imagnumber: (floatnumber | digitpart) ("j" | "J")
7415 ''',
7416 'numeric-types': r'''Emulating numeric types
7417 ***********************
7418
7419 The following methods can be defined to emulate numeric objects.
7420 Methods corresponding to operations that are not supported by the
7421 particular kind of number implemented (e.g., bitwise operations for
7422 non-integral numbers) should be left undefined.
7423
7424 object.__add__(self, other)
7425 object.__sub__(self, other)
7426 object.__mul__(self, other)
7427 object.__matmul__(self, other)
7428 object.__truediv__(self, other)
7429 object.__floordiv__(self, other)
7430 object.__mod__(self, other)
7431 object.__divmod__(self, other)
7432 object.__pow__(self, other[, modulo])
7433 object.__lshift__(self, other)
7434 object.__rshift__(self, other)
7435 object.__and__(self, other)
7436 object.__xor__(self, other)
7437 object.__or__(self, other)
7438
7439 These methods are called to implement the binary arithmetic
7440 operations ("+", "-", "*", "@", "/", "//", "%", "divmod()",
7441 "pow()", "**", "<<", ">>", "&", "^", "|"). For instance, to
7442 evaluate the expression "x + y", where *x* is an instance of a
7443 class that has an "__add__()" method, "type(x).__add__(x, y)" is
7444 called. The "__divmod__()" method should be the equivalent to
7445 using "__floordiv__()" and "__mod__()"; it should not be related to
7446 "__truediv__()". Note that "__pow__()" should be defined to accept
7447 an optional third argument if the three-argument version of the
7448 built-in "pow()" function is to be supported.
7449
7450 If one of those methods does not support the operation with the
7451 supplied arguments, it should return "NotImplemented".
7452
7453 object.__radd__(self, other)
7454 object.__rsub__(self, other)
7455 object.__rmul__(self, other)
7456 object.__rmatmul__(self, other)
7457 object.__rtruediv__(self, other)
7458 object.__rfloordiv__(self, other)
7459 object.__rmod__(self, other)
7460 object.__rdivmod__(self, other)
7461 object.__rpow__(self, other[, modulo])
7462 object.__rlshift__(self, other)
7463 object.__rrshift__(self, other)
7464 object.__rand__(self, other)
7465 object.__rxor__(self, other)
7466 object.__ror__(self, other)
7467
7468 These methods are called to implement the binary arithmetic
7469 operations ("+", "-", "*", "@", "/", "//", "%", "divmod()",
7470 "pow()", "**", "<<", ">>", "&", "^", "|") with reflected (swapped)
7471 operands. These functions are only called if the operands are of
7472 different types, when the left operand does not support the
7473 corresponding operation [3], or the right operand’s class is
7474 derived from the left operand’s class. [4] For instance, to
7475 evaluate the expression "x - y", where *y* is an instance of a
7476 class that has an "__rsub__()" method, "type(y).__rsub__(y, x)" is
7477 called if "type(x).__sub__(x, y)" returns "NotImplemented" or
7478 "type(y)" is a subclass of "type(x)". [5]
7479
7480 Note that "__rpow__()" should be defined to accept an optional
7481 third argument if the three-argument version of the built-in
7482 "pow()" function is to be supported.
7483
7484 Changed in version 3.14: Three-argument "pow()" now try calling
7485 "__rpow__()" if necessary. Previously it was only called in two-
7486 argument "pow()" and the binary power operator.
7487
7488 Note:
7489
7490 If the right operand’s type is a subclass of the left operand’s
7491 type and that subclass provides a different implementation of the
7492 reflected method for the operation, this method will be called
7493 before the left operand’s non-reflected method. This behavior
7494 allows subclasses to override their ancestors’ operations.
7495
7496 object.__iadd__(self, other)
7497 object.__isub__(self, other)
7498 object.__imul__(self, other)
7499 object.__imatmul__(self, other)
7500 object.__itruediv__(self, other)
7501 object.__ifloordiv__(self, other)
7502 object.__imod__(self, other)
7503 object.__ipow__(self, other[, modulo])
7504 object.__ilshift__(self, other)
7505 object.__irshift__(self, other)
7506 object.__iand__(self, other)
7507 object.__ixor__(self, other)
7508 object.__ior__(self, other)
7509
7510 These methods are called to implement the augmented arithmetic
7511 assignments ("+=", "-=", "*=", "@=", "/=", "//=", "%=", "**=",
7512 "<<=", ">>=", "&=", "^=", "|="). These methods should attempt to
7513 do the operation in-place (modifying *self*) and return the result
7514 (which could be, but does not have to be, *self*). If a specific
7515 method is not defined, or if that method returns "NotImplemented",
7516 the augmented assignment falls back to the normal methods. For
7517 instance, if *x* is an instance of a class with an "__iadd__()"
7518 method, "x += y" is equivalent to "x = x.__iadd__(y)" . If
7519 "__iadd__()" does not exist, or if "x.__iadd__(y)" returns
7520 "NotImplemented", "x.__add__(y)" and "y.__radd__(x)" are
7521 considered, as with the evaluation of "x + y". In certain
7522 situations, augmented assignment can result in unexpected errors
7523 (see Why does a_tuple[i] += [‘item’] raise an exception when the
7524 addition works?), but this behavior is in fact part of the data
7525 model.
7526
7527 object.__neg__(self)
7528 object.__pos__(self)
7529 object.__abs__(self)
7530 object.__invert__(self)
7531
7532 Called to implement the unary arithmetic operations ("-", "+",
7533 "abs()" and "~").
7534
7535 object.__complex__(self)
7536 object.__int__(self)
7537 object.__float__(self)
7538
7539 Called to implement the built-in functions "complex()", "int()" and
7540 "float()". Should return a value of the appropriate type.
7541
7542 object.__index__(self)
7543
7544 Called to implement "operator.index()", and whenever Python needs
7545 to losslessly convert the numeric object to an integer object (such
7546 as in slicing, or in the built-in "bin()", "hex()" and "oct()"
7547 functions). Presence of this method indicates that the numeric
7548 object is an integer type. Must return an integer.
7549
7550 If "__int__()", "__float__()" and "__complex__()" are not defined
7551 then corresponding built-in functions "int()", "float()" and
7552 "complex()" fall back to "__index__()".
7553
7554 object.__round__(self[, ndigits])
7555 object.__trunc__(self)
7556 object.__floor__(self)
7557 object.__ceil__(self)
7558
7559 Called to implement the built-in function "round()" and "math"
7560 functions "trunc()", "floor()" and "ceil()". Unless *ndigits* is
7561 passed to "__round__()" all these methods should return the value
7562 of the object truncated to an "Integral" (typically an "int").
7563
7564 Changed in version 3.14: "int()" no longer delegates to the
7565 "__trunc__()" method.
7566 ''',
7567 'objects': r'''Objects, values and types
7568 *************************
7569
7570 *Objects* are Python’s abstraction for data. All data in a Python
7571 program is represented by objects or by relations between objects.
7572 Even code is represented by objects.
7573
7574 Every object has an identity, a type and a value. An object’s
7575 *identity* never changes once it has been created; you may think of it
7576 as the object’s address in memory. The "is" operator compares the
7577 identity of two objects; the "id()" function returns an integer
7578 representing its identity.
7579
7580 **CPython implementation detail:** For CPython, "id(x)" is the memory
7581 address where "x" is stored.
7582
7583 An object’s type determines the operations that the object supports
7584 (e.g., “does it have a length?”) and also defines the possible values
7585 for objects of that type. The "type()" function returns an object’s
7586 type (which is an object itself). Like its identity, an object’s
7587 *type* is also unchangeable. [1]
7588
7589 The *value* of some objects can change. Objects whose value can
7590 change are said to be *mutable*; objects whose value is unchangeable
7591 once they are created are called *immutable*. (The value of an
7592 immutable container object that contains a reference to a mutable
7593 object can change when the latter’s value is changed; however the
7594 container is still considered immutable, because the collection of
7595 objects it contains cannot be changed. So, immutability is not
7596 strictly the same as having an unchangeable value, it is more subtle.)
7597 An object’s mutability is determined by its type; for instance,
7598 numbers, strings and tuples are immutable, while dictionaries and
7599 lists are mutable.
7600
7601 Objects are never explicitly destroyed; however, when they become
7602 unreachable they may be garbage-collected. An implementation is
7603 allowed to postpone garbage collection or omit it altogether — it is a
7604 matter of implementation quality how garbage collection is
7605 implemented, as long as no objects are collected that are still
7606 reachable.
7607
7608 **CPython implementation detail:** CPython currently uses a reference-
7609 counting scheme with (optional) delayed detection of cyclically linked
7610 garbage, which collects most objects as soon as they become
7611 unreachable, but is not guaranteed to collect garbage containing
7612 circular references. See the documentation of the "gc" module for
7613 information on controlling the collection of cyclic garbage. Other
7614 implementations act differently and CPython may change. Do not depend
7615 on immediate finalization of objects when they become unreachable (so
7616 you should always close files explicitly).
7617
7618 Note that the use of the implementation’s tracing or debugging
7619 facilities may keep objects alive that would normally be collectable.
7620 Also note that catching an exception with a "try"…"except" statement
7621 may keep objects alive.
7622
7623 Some objects contain references to “external” resources such as open
7624 files or windows. It is understood that these resources are freed
7625 when the object is garbage-collected, but since garbage collection is
7626 not guaranteed to happen, such objects also provide an explicit way to
7627 release the external resource, usually a "close()" method. Programs
7628 are strongly recommended to explicitly close such objects. The
7629 "try"…"finally" statement and the "with" statement provide convenient
7630 ways to do this.
7631
7632 Some objects contain references to other objects; these are called
7633 *containers*. Examples of containers are tuples, lists and
7634 dictionaries. The references are part of a container’s value. In
7635 most cases, when we talk about the value of a container, we imply the
7636 values, not the identities of the contained objects; however, when we
7637 talk about the mutability of a container, only the identities of the
7638 immediately contained objects are implied. So, if an immutable
7639 container (like a tuple) contains a reference to a mutable object, its
7640 value changes if that mutable object is changed.
7641
7642 Types affect almost all aspects of object behavior. Even the
7643 importance of object identity is affected in some sense: for immutable
7644 types, operations that compute new values may actually return a
7645 reference to any existing object with the same type and value, while
7646 for mutable objects this is not allowed. For example, after "a = 1; b
7647 = 1", *a* and *b* may or may not refer to the same object with the
7648 value one, depending on the implementation. This is because "int" is
7649 an immutable type, so the reference to "1" can be reused. This
7650 behaviour depends on the implementation used, so should not be relied
7651 upon, but is something to be aware of when making use of object
7652 identity tests. However, after "c = []; d = []", *c* and *d* are
7653 guaranteed to refer to two different, unique, newly created empty
7654 lists. (Note that "e = f = []" assigns the *same* object to both *e*
7655 and *f*.)
7656 ''',
7657 'operator-summary': r'''Operator precedence
7658 *******************
7659
7660 The following table summarizes the operator precedence in Python, from
7661 highest precedence (most binding) to lowest precedence (least
7662 binding). Operators in the same box have the same precedence. Unless
7663 the syntax is explicitly given, operators are binary. Operators in
7664 the same box group left to right (except for exponentiation and
7665 conditional expressions, which group from right to left).
7666
7667 Note that comparisons, membership tests, and identity tests, all have
7668 the same precedence and have a left-to-right chaining feature as
7669 described in the Comparisons section.
7670
7671 +-------------------------------------------------+---------------------------------------+
7672 | Operator | Description |
7673 |=================================================|=======================================|
7674 | "(expressions...)", "[expressions...]", "{key: | Binding or parenthesized expression, |
7675 | value...}", "{expressions...}" | list display, dictionary display, set |
7676 | | display |
7677 +-------------------------------------------------+---------------------------------------+
7678 | "x[index]", "x[index:index]" "x(arguments...)", | Subscription (including slicing), |
7679 | "x.attribute" | call, attribute reference |
7680 +-------------------------------------------------+---------------------------------------+
7681 | "await x" | Await expression |
7682 +-------------------------------------------------+---------------------------------------+
7683 | "**" | Exponentiation [5] |
7684 +-------------------------------------------------+---------------------------------------+
7685 | "+x", "-x", "~x" | Positive, negative, bitwise NOT |
7686 +-------------------------------------------------+---------------------------------------+
7687 | "*", "@", "/", "//", "%" | Multiplication, matrix |
7688 | | multiplication, division, floor |
7689 | | division, remainder [6] |
7690 +-------------------------------------------------+---------------------------------------+
7691 | "+", "-" | Addition and subtraction |
7692 +-------------------------------------------------+---------------------------------------+
7693 | "<<", ">>" | Shifts |
7694 +-------------------------------------------------+---------------------------------------+
7695 | "&" | Bitwise AND |
7696 +-------------------------------------------------+---------------------------------------+
7697 | "^" | Bitwise XOR |
7698 +-------------------------------------------------+---------------------------------------+
7699 | "|" | Bitwise OR |
7700 +-------------------------------------------------+---------------------------------------+
7701 | "in", "not in", "is", "is not", "<", "<=", ">", | Comparisons, including membership |
7702 | ">=", "!=", "==" | tests and identity tests |
7703 +-------------------------------------------------+---------------------------------------+
7704 | "not x" | Boolean NOT |
7705 +-------------------------------------------------+---------------------------------------+
7706 | "and" | Boolean AND |
7707 +-------------------------------------------------+---------------------------------------+
7708 | "or" | Boolean OR |
7709 +-------------------------------------------------+---------------------------------------+
7710 | "if" – "else" | Conditional expression |
7711 +-------------------------------------------------+---------------------------------------+
7712 | "lambda" | Lambda expression |
7713 +-------------------------------------------------+---------------------------------------+
7714 | ":=" | Assignment expression |
7715 +-------------------------------------------------+---------------------------------------+
7716
7717 -[ Footnotes ]-
7718
7719 [1] While "abs(x%y) < abs(y)" is true mathematically, for floats it
7720 may not be true numerically due to roundoff. For example, and
7721 assuming a platform on which a Python float is an IEEE 754 double-
7722 precision number, in order that "-1e-100 % 1e100" have the same
7723 sign as "1e100", the computed result is "-1e-100 + 1e100", which
7724 is numerically exactly equal to "1e100". The function
7725 "math.fmod()" returns a result whose sign matches the sign of the
7726 first argument instead, and so returns "-1e-100" in this case.
7727 Which approach is more appropriate depends on the application.
7728
7729 [2] If x is very close to an exact integer multiple of y, it’s
7730 possible for "x//y" to be one larger than "(x-x%y)//y" due to
7731 rounding. In such cases, Python returns the latter result, in
7732 order to preserve that "divmod(x,y)[0] * y + x % y" be very close
7733 to "x".
7734
7735 [3] The Unicode standard distinguishes between *code points* (e.g.
7736 U+0041) and *abstract characters* (e.g. “LATIN CAPITAL LETTER A”).
7737 While most abstract characters in Unicode are only represented
7738 using one code point, there is a number of abstract characters
7739 that can in addition be represented using a sequence of more than
7740 one code point. For example, the abstract character “LATIN
7741 CAPITAL LETTER C WITH CEDILLA” can be represented as a single
7742 *precomposed character* at code position U+00C7, or as a sequence
7743 of a *base character* at code position U+0043 (LATIN CAPITAL
7744 LETTER C), followed by a *combining character* at code position
7745 U+0327 (COMBINING CEDILLA).
7746
7747 The comparison operators on strings compare at the level of
7748 Unicode code points. This may be counter-intuitive to humans. For
7749 example, ""\u00C7" == "\u0043\u0327"" is "False", even though both
7750 strings represent the same abstract character “LATIN CAPITAL
7751 LETTER C WITH CEDILLA”.
7752
7753 To compare strings at the level of abstract characters (that is,
7754 in a way intuitive to humans), use "unicodedata.normalize()".
7755
7756 [4] Due to automatic garbage-collection, free lists, and the dynamic
7757 nature of descriptors, you may notice seemingly unusual behaviour
7758 in certain uses of the "is" operator, like those involving
7759 comparisons between instance methods, or constants. Check their
7760 documentation for more info.
7761
7762 [5] The power operator "**" binds less tightly than an arithmetic or
7763 bitwise unary operator on its right, that is, "2**-1" is "0.5".
7764
7765 [6] The "%" operator is also used for string formatting; the same
7766 precedence applies.
7767 ''',
7768 'pass': r'''The "pass" statement
7769 ********************
7770
7771 pass_stmt: "pass"
7772
7773 "pass" is a null operation — when it is executed, nothing happens. It
7774 is useful as a placeholder when a statement is required syntactically,
7775 but no code needs to be executed, for example:
7776
7777 def f(arg): pass # a function that does nothing (yet)
7778
7779 class C: pass # a class with no methods (yet)
7780 ''',
7781 'power': r'''The power operator
7782 ******************
7783
7784 The power operator binds more tightly than unary operators on its
7785 left; it binds less tightly than unary operators on its right. The
7786 syntax is:
7787
7788 power: (await_expr | primary) ["**" u_expr]
7789
7790 Thus, in an unparenthesized sequence of power and unary operators, the
7791 operators are evaluated from right to left (this does not constrain
7792 the evaluation order for the operands): "-1**2" results in "-1".
7793
7794 The power operator has the same semantics as the built-in "pow()"
7795 function, when called with two arguments: it yields its left argument
7796 raised to the power of its right argument. Numeric arguments are first
7797 converted to a common type, and the result is of that type.
7798
7799 For int operands, the result has the same type as the operands unless
7800 the second argument is negative; in that case, all arguments are
7801 converted to float and a float result is delivered. For example,
7802 "10**2" returns "100", but "10**-2" returns "0.01".
7803
7804 Raising "0.0" to a negative power results in a "ZeroDivisionError".
7805 Raising a negative number to a fractional power results in a "complex"
7806 number. (In earlier versions it raised a "ValueError".)
7807
7808 This operation can be customized using the special "__pow__()" and
7809 "__rpow__()" methods.
7810 ''',
7811 'raise': r'''The "raise" statement
7812 *********************
7813
7814 raise_stmt: "raise" [expression ["from" expression]]
7815
7816 If no expressions are present, "raise" re-raises the exception that is
7817 currently being handled, which is also known as the *active
7818 exception*. If there isn’t currently an active exception, a
7819 "RuntimeError" exception is raised indicating that this is an error.
7820
7821 Otherwise, "raise" evaluates the first expression as the exception
7822 object. It must be either a subclass or an instance of
7823 "BaseException". If it is a class, the exception instance will be
7824 obtained when needed by instantiating the class with no arguments.
7825
7826 The *type* of the exception is the exception instance’s class, the
7827 *value* is the instance itself.
7828
7829 A traceback object is normally created automatically when an exception
7830 is raised and attached to it as the "__traceback__" attribute. You can
7831 create an exception and set your own traceback in one step using the
7832 "with_traceback()" exception method (which returns the same exception
7833 instance, with its traceback set to its argument), like so:
7834
7835 raise Exception("foo occurred").with_traceback(tracebackobj)
7836
7837 The "from" clause is used for exception chaining: if given, the second
7838 *expression* must be another exception class or instance. If the
7839 second expression is an exception instance, it will be attached to the
7840 raised exception as the "__cause__" attribute (which is writable). If
7841 the expression is an exception class, the class will be instantiated
7842 and the resulting exception instance will be attached to the raised
7843 exception as the "__cause__" attribute. If the raised exception is not
7844 handled, both exceptions will be printed:
7845
7846 >>> try:
7847 ... print(1 / 0)
7848 ... except Exception as exc:
7849 ... raise RuntimeError("Something bad happened") from exc
7850 ...
7851 Traceback (most recent call last):
7852 File "<stdin>", line 2, in <module>
7853 print(1 / 0)
7854 ~~^~~
7855 ZeroDivisionError: division by zero
7856
7857 The above exception was the direct cause of the following exception:
7858
7859 Traceback (most recent call last):
7860 File "<stdin>", line 4, in <module>
7861 raise RuntimeError("Something bad happened") from exc
7862 RuntimeError: Something bad happened
7863
7864 A similar mechanism works implicitly if a new exception is raised when
7865 an exception is already being handled. An exception may be handled
7866 when an "except" or "finally" clause, or a "with" statement, is used.
7867 The previous exception is then attached as the new exception’s
7868 "__context__" attribute:
7869
7870 >>> try:
7871 ... print(1 / 0)
7872 ... except:
7873 ... raise RuntimeError("Something bad happened")
7874 ...
7875 Traceback (most recent call last):
7876 File "<stdin>", line 2, in <module>
7877 print(1 / 0)
7878 ~~^~~
7879 ZeroDivisionError: division by zero
7880
7881 During handling of the above exception, another exception occurred:
7882
7883 Traceback (most recent call last):
7884 File "<stdin>", line 4, in <module>
7885 raise RuntimeError("Something bad happened")
7886 RuntimeError: Something bad happened
7887
7888 Exception chaining can be explicitly suppressed by specifying "None"
7889 in the "from" clause:
7890
7891 >>> try:
7892 ... print(1 / 0)
7893 ... except:
7894 ... raise RuntimeError("Something bad happened") from None
7895 ...
7896 Traceback (most recent call last):
7897 File "<stdin>", line 4, in <module>
7898 RuntimeError: Something bad happened
7899
7900 Additional information on exceptions can be found in section
7901 Exceptions, and information about handling exceptions is in section
7902 The try statement.
7903
7904 Changed in version 3.3: "None" is now permitted as "Y" in "raise X
7905 from Y".Added the "__suppress_context__" attribute to suppress
7906 automatic display of the exception context.
7907
7908 Changed in version 3.11: If the traceback of the active exception is
7909 modified in an "except" clause, a subsequent "raise" statement re-
7910 raises the exception with the modified traceback. Previously, the
7911 exception was re-raised with the traceback it had when it was caught.
7912 ''',
7913 'return': r'''The "return" statement
7914 **********************
7915
7916 return_stmt: "return" [expression_list]
7917
7918 "return" may only occur syntactically nested in a function definition,
7919 not within a nested class definition.
7920
7921 If an expression list is present, it is evaluated, else "None" is
7922 substituted.
7923
7924 "return" leaves the current function call with the expression list (or
7925 "None") as return value.
7926
7927 When "return" passes control out of a "try" statement with a "finally"
7928 clause, that "finally" clause is executed before really leaving the
7929 function.
7930
7931 In a generator function, the "return" statement indicates that the
7932 generator is done and will cause "StopIteration" to be raised. The
7933 returned value (if any) is used as an argument to construct
7934 "StopIteration" and becomes the "StopIteration.value" attribute.
7935
7936 In an asynchronous generator function, an empty "return" statement
7937 indicates that the asynchronous generator is done and will cause
7938 "StopAsyncIteration" to be raised. A non-empty "return" statement is
7939 a syntax error in an asynchronous generator function.
7940 ''',
7941 'sequence-types': r'''Emulating container types
7942 *************************
7943
7944 The following methods can be defined to implement container objects.
7945 None of them are provided by the "object" class itself. Containers
7946 usually are *sequences* (such as "lists" or "tuples") or *mappings*
7947 (like *dictionaries*), but can represent other containers as well.
7948 The first set of methods is used either to emulate a sequence or to
7949 emulate a mapping; the difference is that for a sequence, the
7950 allowable keys should be the integers *k* for which "0 <= k < N" where
7951 *N* is the length of the sequence, or "slice" objects, which define a
7952 range of items. It is also recommended that mappings provide the
7953 methods "keys()", "values()", "items()", "get()", "clear()",
7954 "setdefault()", "pop()", "popitem()", "copy()", and "update()"
7955 behaving similar to those for Python’s standard "dictionary" objects.
7956 The "collections.abc" module provides a "MutableMapping" *abstract
7957 base class* to help create those methods from a base set of
7958 "__getitem__()", "__setitem__()", "__delitem__()", and "keys()".
7959
7960 Mutable sequences should provide methods "append()", "clear()",
7961 "count()", "extend()", "index()", "insert()", "pop()", "remove()", and
7962 "reverse()", like Python standard "list" objects. Finally, sequence
7963 types should implement addition (meaning concatenation) and
7964 multiplication (meaning repetition) by defining the methods
7965 "__add__()", "__radd__()", "__iadd__()", "__mul__()", "__rmul__()" and
7966 "__imul__()" described below; they should not define other numerical
7967 operators.
7968
7969 It is recommended that both mappings and sequences implement the
7970 "__contains__()" method to allow efficient use of the "in" operator;
7971 for mappings, "in" should search the mapping’s keys; for sequences, it
7972 should search through the values. It is further recommended that both
7973 mappings and sequences implement the "__iter__()" method to allow
7974 efficient iteration through the container; for mappings, "__iter__()"
7975 should iterate through the object’s keys; for sequences, it should
7976 iterate through the values.
7977
7978 object.__len__(self)
7979
7980 Called to implement the built-in function "len()". Should return
7981 the length of the object, an integer ">=" 0. Also, an object that
7982 doesn’t define a "__bool__()" method and whose "__len__()" method
7983 returns zero is considered to be false in a Boolean context.
7984
7985 **CPython implementation detail:** In CPython, the length is
7986 required to be at most "sys.maxsize". If the length is larger than
7987 "sys.maxsize" some features (such as "len()") may raise
7988 "OverflowError". To prevent raising "OverflowError" by truth value
7989 testing, an object must define a "__bool__()" method.
7990
7991 object.__length_hint__(self)
7992
7993 Called to implement "operator.length_hint()". Should return an
7994 estimated length for the object (which may be greater or less than
7995 the actual length). The length must be an integer ">=" 0. The
7996 return value may also be "NotImplemented", which is treated the
7997 same as if the "__length_hint__" method didn’t exist at all. This
7998 method is purely an optimization and is never required for
7999 correctness.
8000
8001 Added in version 3.4.
8002
8003 object.__getitem__(self, subscript)
8004
8005 Called to implement *subscription*, that is, "self[subscript]". See
8006 Subscriptions and slicings for details on the syntax.
8007
8008 There are two types of built-in objects that support subscription
8009 via "__getitem__()":
8010
8011 * **sequences**, where *subscript* (also called *index*) should be
8012 an integer or a "slice" object. See the sequence documentation
8013 for the expected behavior, including handling "slice" objects and
8014 negative indices.
8015
8016 * **mappings**, where *subscript* is also called the *key*. See
8017 mapping documentation for the expected behavior.
8018
8019 If *subscript* is of an inappropriate type, "__getitem__()" should
8020 raise "TypeError". If *subscript* has an inappropriate value,
8021 "__getitem__()" should raise an "LookupError" or one of its
8022 subclasses ("IndexError" for sequences; "KeyError" for mappings).
8023
8024 Note:
8025
8026 Slicing is handled by "__getitem__()", "__setitem__()", and
8027 "__delitem__()". A call like
8028
8029 a[1:2] = b
8030
8031 is translated to
8032
8033 a[slice(1, 2, None)] = b
8034
8035 and so forth. Missing slice items are always filled in with
8036 "None".
8037
8038 Note:
8039
8040 The sequence iteration protocol (used, for example, in "for"
8041 loops), expects that an "IndexError" will be raised for illegal
8042 indexes to allow proper detection of the end of a sequence.
8043
8044 Note:
8045
8046 When subscripting a *class*, the special class method
8047 "__class_getitem__()" may be called instead of "__getitem__()".
8048 See __class_getitem__ versus __getitem__ for more details.
8049
8050 object.__setitem__(self, key, value)
8051
8052 Called to implement assignment to "self[key]". Same note as for
8053 "__getitem__()". This should only be implemented for mappings if
8054 the objects support changes to the values for keys, or if new keys
8055 can be added, or for sequences if elements can be replaced. The
8056 same exceptions should be raised for improper *key* values as for
8057 the "__getitem__()" method.
8058
8059 object.__delitem__(self, key)
8060
8061 Called to implement deletion of "self[key]". Same note as for
8062 "__getitem__()". This should only be implemented for mappings if
8063 the objects support removal of keys, or for sequences if elements
8064 can be removed from the sequence. The same exceptions should be
8065 raised for improper *key* values as for the "__getitem__()" method.
8066
8067 object.__missing__(self, key)
8068
8069 Called by "dict"."__getitem__()" to implement "self[key]" for dict
8070 subclasses when key is not in the dictionary.
8071
8072 object.__iter__(self)
8073
8074 This method is called when an *iterator* is required for a
8075 container. This method should return a new iterator object that can
8076 iterate over all the objects in the container. For mappings, it
8077 should iterate over the keys of the container.
8078
8079 object.__reversed__(self)
8080
8081 Called (if present) by the "reversed()" built-in to implement
8082 reverse iteration. It should return a new iterator object that
8083 iterates over all the objects in the container in reverse order.
8084
8085 If the "__reversed__()" method is not provided, the "reversed()"
8086 built-in will fall back to using the sequence protocol ("__len__()"
8087 and "__getitem__()"). Objects that support the sequence protocol
8088 should only provide "__reversed__()" if they can provide an
8089 implementation that is more efficient than the one provided by
8090 "reversed()".
8091
8092 The membership test operators ("in" and "not in") are normally
8093 implemented as an iteration through a container. However, container
8094 objects can supply the following special method with a more efficient
8095 implementation, which also does not require the object be iterable.
8096
8097 object.__contains__(self, item)
8098
8099 Called to implement membership test operators. Should return true
8100 if *item* is in *self*, false otherwise. For mapping objects, this
8101 should consider the keys of the mapping rather than the values or
8102 the key-item pairs.
8103
8104 For objects that don’t define "__contains__()", the membership test
8105 first tries iteration via "__iter__()", then the old sequence
8106 iteration protocol via "__getitem__()", see this section in the
8107 language reference.
8108 ''',
8109 'shifting': r'''Shifting operations
8110 *******************
8111
8112 The shifting operations have lower priority than the arithmetic
8113 operations:
8114
8115 shift_expr: a_expr | shift_expr ("<<" | ">>") a_expr
8116
8117 These operators accept integers as arguments. They shift the first
8118 argument to the left or right by the number of bits given by the
8119 second argument.
8120
8121 The left shift operation can be customized using the special
8122 "__lshift__()" and "__rlshift__()" methods. The right shift operation
8123 can be customized using the special "__rshift__()" and "__rrshift__()"
8124 methods.
8125
8126 A right shift by *n* bits is defined as floor division by "pow(2,n)".
8127 A left shift by *n* bits is defined as multiplication with "pow(2,n)".
8128 ''',
8129 'slicings': r'''Slicings
8130 ********
8131
8132 A more advanced form of subscription, *slicing*, is commonly used to
8133 extract a portion of a sequence. In this form, the subscript is a
8134 *slice*: up to three expressions separated by colons. Any of the
8135 expressions may be omitted, but a slice must contain at least one
8136 colon:
8137
8138 >>> number_names = ['zero', 'one', 'two', 'three', 'four', 'five']
8139 >>> number_names[1:3]
8140 ['one', 'two']
8141 >>> number_names[1:]
8142 ['one', 'two', 'three', 'four', 'five']
8143 >>> number_names[:3]
8144 ['zero', 'one', 'two']
8145 >>> number_names[:]
8146 ['zero', 'one', 'two', 'three', 'four', 'five']
8147 >>> number_names[::2]
8148 ['zero', 'two', 'four']
8149 >>> number_names[:-3]
8150 ['zero', 'one', 'two']
8151 >>> del number_names[4:]
8152 >>> number_names
8153 ['zero', 'one', 'two', 'three']
8154
8155 When a slice is evaluated, the interpreter constructs a "slice" object
8156 whose "start", "stop" and "step" attributes, respectively, are the
8157 results of the expressions between the colons. Any missing expression
8158 evaluates to "None". This "slice" object is then passed to the
8159 "__getitem__()" or "__class_getitem__()" *special method*, as above.
8160
8161 # continuing with the SubscriptionDemo instance defined above:
8162 >>> demo[2:3]
8163 subscripted with: slice(2, 3, None)
8164 >>> demo[::'spam']
8165 subscripted with: slice(None, None, 'spam')
8166 ''',
8167 'specialattrs': r'''Special Attributes
8168 ******************
8169
8170 The implementation adds a few special read-only attributes to several
8171 object types, where they are relevant. Some of these are not reported
8172 by the "dir()" built-in function.
8173
8174 definition.__name__
8175
8176 The name of the class, function, method, descriptor, or generator
8177 instance.
8178
8179 definition.__qualname__
8180
8181 The *qualified name* of the class, function, method, descriptor, or
8182 generator instance.
8183
8184 Added in version 3.3.
8185
8186 definition.__module__
8187
8188 The name of the module in which a class or function was defined.
8189
8190 definition.__doc__
8191
8192 The documentation string of a class or function, or "None" if
8193 undefined.
8194
8195 definition.__type_params__
8196
8197 The type parameters of generic classes, functions, and type
8198 aliases. For classes and functions that are not generic, this will
8199 be an empty tuple.
8200
8201 Added in version 3.12.
8202 ''',
8203 'specialnames': r'''Special method names
8204 ********************
8205
8206 A class can implement certain operations that are invoked by special
8207 syntax (such as arithmetic operations or subscripting and slicing) by
8208 defining methods with special names. This is Python’s approach to
8209 *operator overloading*, allowing classes to define their own behavior
8210 with respect to language operators. For instance, if a class defines
8211 a method named "__getitem__()", and "x" is an instance of this class,
8212 then "x[i]" is roughly equivalent to "type(x).__getitem__(x, i)".
8213 Except where mentioned, attempts to execute an operation raise an
8214 exception when no appropriate method is defined (typically
8215 "AttributeError" or "TypeError").
8216
8217 Setting a special method to "None" indicates that the corresponding
8218 operation is not available. For example, if a class sets "__iter__()"
8219 to "None", the class is not iterable, so calling "iter()" on its
8220 instances will raise a "TypeError" (without falling back to
8221 "__getitem__()"). [2]
8222
8223 When implementing a class that emulates any built-in type, it is
8224 important that the emulation only be implemented to the degree that it
8225 makes sense for the object being modelled. For example, some
8226 sequences may work well with retrieval of individual elements, but
8227 extracting a slice may not make sense. (One example of this is the
8228 NodeList interface in the W3C’s Document Object Model.)
8229
8230
8231 Basic customization
8232 ===================
8233
8234 object.__new__(cls[, ...])
8235
8236 Called to create a new instance of class *cls*. "__new__()" is a
8237 static method (special-cased so you need not declare it as such)
8238 that takes the class of which an instance was requested as its
8239 first argument. The remaining arguments are those passed to the
8240 object constructor expression (the call to the class). The return
8241 value of "__new__()" should be the new object instance (usually an
8242 instance of *cls*).
8243
8244 Typical implementations create a new instance of the class by
8245 invoking the superclass’s "__new__()" method using
8246 "super().__new__(cls[, ...])" with appropriate arguments and then
8247 modifying the newly created instance as necessary before returning
8248 it.
8249
8250 If "__new__()" is invoked during object construction and it returns
8251 an instance of *cls*, then the new instance’s "__init__()" method
8252 will be invoked like "__init__(self[, ...])", where *self* is the
8253 new instance and the remaining arguments are the same as were
8254 passed to the object constructor.
8255
8256 If "__new__()" does not return an instance of *cls*, then the new
8257 instance’s "__init__()" method will not be invoked.
8258
8259 "__new__()" is intended mainly to allow subclasses of immutable
8260 types (like int, str, or tuple) to customize instance creation. It
8261 is also commonly overridden in custom metaclasses in order to
8262 customize class creation.
8263
8264 object.__init__(self[, ...])
8265
8266 Called after the instance has been created (by "__new__()"), but
8267 before it is returned to the caller. The arguments are those
8268 passed to the class constructor expression. If a base class has an
8269 "__init__()" method, the derived class’s "__init__()" method, if
8270 any, must explicitly call it to ensure proper initialization of the
8271 base class part of the instance; for example:
8272 "super().__init__([args...])".
8273
8274 Because "__new__()" and "__init__()" work together in constructing
8275 objects ("__new__()" to create it, and "__init__()" to customize
8276 it), no non-"None" value may be returned by "__init__()"; doing so
8277 will cause a "TypeError" to be raised at runtime.
8278
8279 object.__del__(self)
8280
8281 Called when the instance is about to be destroyed. This is also
8282 called a finalizer or (improperly) a destructor. If a base class
8283 has a "__del__()" method, the derived class’s "__del__()" method,
8284 if any, must explicitly call it to ensure proper deletion of the
8285 base class part of the instance.
8286
8287 It is possible (though not recommended!) for the "__del__()" method
8288 to postpone destruction of the instance by creating a new reference
8289 to it. This is called object *resurrection*. It is
8290 implementation-dependent whether "__del__()" is called a second
8291 time when a resurrected object is about to be destroyed; the
8292 current *CPython* implementation only calls it once.
8293
8294 It is not guaranteed that "__del__()" methods are called for
8295 objects that still exist when the interpreter exits.
8296 "weakref.finalize" provides a straightforward way to register a
8297 cleanup function to be called when an object is garbage collected.
8298
8299 Note:
8300
8301 "del x" doesn’t directly call "x.__del__()" — the former
8302 decrements the reference count for "x" by one, and the latter is
8303 only called when "x"’s reference count reaches zero.
8304
8305 **CPython implementation detail:** It is possible for a reference
8306 cycle to prevent the reference count of an object from going to
8307 zero. In this case, the cycle will be later detected and deleted
8308 by the *cyclic garbage collector*. A common cause of reference
8309 cycles is when an exception has been caught in a local variable.
8310 The frame’s locals then reference the exception, which references
8311 its own traceback, which references the locals of all frames caught
8312 in the traceback.
8313
8314 See also: Documentation for the "gc" module.
8315
8316 Warning:
8317
8318 Due to the precarious circumstances under which "__del__()"
8319 methods are invoked, exceptions that occur during their execution
8320 are ignored, and a warning is printed to "sys.stderr" instead.
8321 In particular:
8322
8323 * "__del__()" can be invoked when arbitrary code is being
8324 executed, including from any arbitrary thread. If "__del__()"
8325 needs to take a lock or invoke any other blocking resource, it
8326 may deadlock as the resource may already be taken by the code
8327 that gets interrupted to execute "__del__()".
8328
8329 * "__del__()" can be executed during interpreter shutdown. As a
8330 consequence, the global variables it needs to access (including
8331 other modules) may already have been deleted or set to "None".
8332 Python guarantees that globals whose name begins with a single
8333 underscore are deleted from their module before other globals
8334 are deleted; if no other references to such globals exist, this
8335 may help in assuring that imported modules are still available
8336 at the time when the "__del__()" method is called.
8337
8338 object.__repr__(self)
8339
8340 Called by the "repr()" built-in function to compute the “official”
8341 string representation of an object. If at all possible, this
8342 should look like a valid Python expression that could be used to
8343 recreate an object with the same value (given an appropriate
8344 environment). If this is not possible, a string of the form
8345 "<...some useful description...>" should be returned. The return
8346 value must be a string object. If a class defines "__repr__()" but
8347 not "__str__()", then "__repr__()" is also used when an “informal”
8348 string representation of instances of that class is required.
8349
8350 This is typically used for debugging, so it is important that the
8351 representation is information-rich and unambiguous. A default
8352 implementation is provided by the "object" class itself.
8353
8354 object.__str__(self)
8355
8356 Called by "str(object)", the default "__format__()" implementation,
8357 and the built-in function "print()", to compute the “informal” or
8358 nicely printable string representation of an object. The return
8359 value must be a str object.
8360
8361 This method differs from "object.__repr__()" in that there is no
8362 expectation that "__str__()" return a valid Python expression: a
8363 more convenient or concise representation can be used.
8364
8365 The default implementation defined by the built-in type "object"
8366 calls "object.__repr__()".
8367
8368 object.__bytes__(self)
8369
8370 Called by bytes to compute a byte-string representation of an
8371 object. This should return a "bytes" object. The "object" class
8372 itself does not provide this method.
8373
8374 object.__format__(self, format_spec)
8375
8376 Called by the "format()" built-in function, and by extension,
8377 evaluation of formatted string literals and the "str.format()"
8378 method, to produce a “formatted” string representation of an
8379 object. The *format_spec* argument is a string that contains a
8380 description of the formatting options desired. The interpretation
8381 of the *format_spec* argument is up to the type implementing
8382 "__format__()", however most classes will either delegate
8383 formatting to one of the built-in types, or use a similar
8384 formatting option syntax.
8385
8386 See Format specification mini-language for a description of the
8387 standard formatting syntax.
8388
8389 The return value must be a string object.
8390
8391 The default implementation by the "object" class should be given an
8392 empty *format_spec* string. It delegates to "__str__()".
8393
8394 Changed in version 3.4: The __format__ method of "object" itself
8395 raises a "TypeError" if passed any non-empty string.
8396
8397 Changed in version 3.7: "object.__format__(x, '')" is now
8398 equivalent to "str(x)" rather than "format(str(x), '')".
8399
8400 object.__lt__(self, other)
8401 object.__le__(self, other)
8402 object.__eq__(self, other)
8403 object.__ne__(self, other)
8404 object.__gt__(self, other)
8405 object.__ge__(self, other)
8406
8407 These are the so-called “rich comparison” methods. The
8408 correspondence between operator symbols and method names is as
8409 follows: "x<y" calls "x.__lt__(y)", "x<=y" calls "x.__le__(y)",
8410 "x==y" calls "x.__eq__(y)", "x!=y" calls "x.__ne__(y)", "x>y" calls
8411 "x.__gt__(y)", and "x>=y" calls "x.__ge__(y)".
8412
8413 A rich comparison method may return the singleton "NotImplemented"
8414 if it does not implement the operation for a given pair of
8415 arguments. By convention, "False" and "True" are returned for a
8416 successful comparison. However, these methods can return any value,
8417 so if the comparison operator is used in a Boolean context (e.g.,
8418 in the condition of an "if" statement), Python will call "bool()"
8419 on the value to determine if the result is true or false.
8420
8421 By default, "object" implements "__eq__()" by using "is", returning
8422 "NotImplemented" in the case of a false comparison: "True if x is y
8423 else NotImplemented". For "__ne__()", by default it delegates to
8424 "__eq__()" and inverts the result unless it is "NotImplemented".
8425 There are no other implied relationships among the comparison
8426 operators or default implementations; for example, the truth of
8427 "(x<y or x==y)" does not imply "x<=y". To automatically generate
8428 ordering operations from a single root operation, see
8429 "functools.total_ordering()".
8430
8431 By default, the "object" class provides implementations consistent
8432 with Value comparisons: equality compares according to object
8433 identity, and order comparisons raise "TypeError". Each default
8434 method may generate these results directly, but may also return
8435 "NotImplemented".
8436
8437 See the paragraph on "__hash__()" for some important notes on
8438 creating *hashable* objects which support custom comparison
8439 operations and are usable as dictionary keys.
8440
8441 There are no swapped-argument versions of these methods (to be used
8442 when the left argument does not support the operation but the right
8443 argument does); rather, "__lt__()" and "__gt__()" are each other’s
8444 reflection, "__le__()" and "__ge__()" are each other’s reflection,
8445 and "__eq__()" and "__ne__()" are their own reflection. If the
8446 operands are of different types, and the right operand’s type is a
8447 direct or indirect subclass of the left operand’s type, the
8448 reflected method of the right operand has priority, otherwise the
8449 left operand’s method has priority. Virtual subclassing is not
8450 considered.
8451
8452 When no appropriate method returns any value other than
8453 "NotImplemented", the "==" and "!=" operators will fall back to
8454 "is" and "is not", respectively.
8455
8456 object.__hash__(self)
8457
8458 Called by built-in function "hash()" and for operations on members
8459 of hashed collections including "set", "frozenset", and "dict".
8460 The "__hash__()" method should return an integer. The only required
8461 property is that objects which compare equal have the same hash
8462 value; it is advised to mix together the hash values of the
8463 components of the object that also play a part in comparison of
8464 objects by packing them into a tuple and hashing the tuple.
8465 Example:
8466
8467 def __hash__(self):
8468 return hash((self.name, self.nick, self.color))
8469
8470 Note:
8471
8472 "hash()" truncates the value returned from an object’s custom
8473 "__hash__()" method to the size of a "Py_ssize_t". This is
8474 typically 8 bytes on 64-bit builds and 4 bytes on 32-bit builds.
8475 If an object’s "__hash__()" must interoperate on builds of
8476 different bit sizes, be sure to check the width on all supported
8477 builds. An easy way to do this is with "python -c "import sys;
8478 print(sys.hash_info.width)"".
8479
8480 If a class does not define an "__eq__()" method it should not
8481 define a "__hash__()" operation either; if it defines "__eq__()"
8482 but not "__hash__()", its instances will not be usable as items in
8483 hashable collections. If a class defines mutable objects and
8484 implements an "__eq__()" method, it should not implement
8485 "__hash__()", since the implementation of *hashable* collections
8486 requires that a key’s hash value is immutable (if the object’s hash
8487 value changes, it will be in the wrong hash bucket).
8488
8489 User-defined classes have "__eq__()" and "__hash__()" methods by
8490 default (inherited from the "object" class); with them, all objects
8491 compare unequal (except with themselves) and "x.__hash__()" returns
8492 an appropriate value such that "x == y" implies both that "x is y"
8493 and "hash(x) == hash(y)".
8494
8495 A class that overrides "__eq__()" and does not define "__hash__()"
8496 will have its "__hash__()" implicitly set to "None". When the
8497 "__hash__()" method of a class is "None", instances of the class
8498 will raise an appropriate "TypeError" when a program attempts to
8499 retrieve their hash value, and will also be correctly identified as
8500 unhashable when checking "isinstance(obj,
8501 collections.abc.Hashable)".
8502
8503 If a class that overrides "__eq__()" needs to retain the
8504 implementation of "__hash__()" from a parent class, the interpreter
8505 must be told this explicitly by setting "__hash__ =
8506 <ParentClass>.__hash__".
8507
8508 If a class that does not override "__eq__()" wishes to suppress
8509 hash support, it should include "__hash__ = None" in the class
8510 definition. A class which defines its own "__hash__()" that
8511 explicitly raises a "TypeError" would be incorrectly identified as
8512 hashable by an "isinstance(obj, collections.abc.Hashable)" call.
8513
8514 Note:
8515
8516 By default, the "__hash__()" values of str and bytes objects are
8517 “salted” with an unpredictable random value. Although they
8518 remain constant within an individual Python process, they are not
8519 predictable between repeated invocations of Python.This is
8520 intended to provide protection against a denial-of-service caused
8521 by carefully chosen inputs that exploit the worst case
8522 performance of a dict insertion, *O*(*n*^2) complexity. See
8523 https://ocert.org/advisories/ocert-2011-003.html for
8524 details.Changing hash values affects the iteration order of sets.
8525 Python has never made guarantees about this ordering (and it
8526 typically varies between 32-bit and 64-bit builds).See also
8527 "PYTHONHASHSEED".
8528
8529 Changed in version 3.3: Hash randomization is enabled by default.
8530
8531 object.__bool__(self)
8532
8533 Called to implement truth value testing and the built-in operation
8534 "bool()"; should return "False" or "True". When this method is not
8535 defined, "__len__()" is called, if it is defined, and the object is
8536 considered true if its result is nonzero. If a class defines
8537 neither "__len__()" nor "__bool__()" (which is true of the "object"
8538 class itself), all its instances are considered true.
8539
8540
8541 Customizing attribute access
8542 ============================
8543
8544 The following methods can be defined to customize the meaning of
8545 attribute access (use of, assignment to, or deletion of "x.name") for
8546 class instances.
8547
8548 object.__getattr__(self, name)
8549
8550 Called when the default attribute access fails with an
8551 "AttributeError" (either "__getattribute__()" raises an
8552 "AttributeError" because *name* is not an instance attribute or an
8553 attribute in the class tree for "self"; or "__get__()" of a *name*
8554 property raises "AttributeError"). This method should either
8555 return the (computed) attribute value or raise an "AttributeError"
8556 exception. The "object" class itself does not provide this method.
8557
8558 Note that if the attribute is found through the normal mechanism,
8559 "__getattr__()" is not called. (This is an intentional asymmetry
8560 between "__getattr__()" and "__setattr__()".) This is done both for
8561 efficiency reasons and because otherwise "__getattr__()" would have
8562 no way to access other attributes of the instance. Note that at
8563 least for instance variables, you can take total control by not
8564 inserting any values in the instance attribute dictionary (but
8565 instead inserting them in another object). See the
8566 "__getattribute__()" method below for a way to actually get total
8567 control over attribute access.
8568
8569 object.__getattribute__(self, name)
8570
8571 Called unconditionally to implement attribute accesses for
8572 instances of the class. If the class also defines "__getattr__()",
8573 the latter will not be called unless "__getattribute__()" either
8574 calls it explicitly or raises an "AttributeError". This method
8575 should return the (computed) attribute value or raise an
8576 "AttributeError" exception. In order to avoid infinite recursion in
8577 this method, its implementation should always call the base class
8578 method with the same name to access any attributes it needs, for
8579 example, "object.__getattribute__(self, name)".
8580
8581 Note:
8582
8583 This method may still be bypassed when looking up special methods
8584 as the result of implicit invocation via language syntax or
8585 built-in functions. See Special method lookup.
8586
8587 For certain sensitive attribute accesses, raises an auditing event
8588 "object.__getattr__" with arguments "obj" and "name".
8589
8590 object.__setattr__(self, name, value)
8591
8592 Called when an attribute assignment is attempted. This is called
8593 instead of the normal mechanism (i.e. store the value in the
8594 instance dictionary). *name* is the attribute name, *value* is the
8595 value to be assigned to it.
8596
8597 If "__setattr__()" wants to assign to an instance attribute, it
8598 should call the base class method with the same name, for example,
8599 "object.__setattr__(self, name, value)".
8600
8601 For certain sensitive attribute assignments, raises an auditing
8602 event "object.__setattr__" with arguments "obj", "name", "value".
8603
8604 object.__delattr__(self, name)
8605
8606 Like "__setattr__()" but for attribute deletion instead of
8607 assignment. This should only be implemented if "del obj.name" is
8608 meaningful for the object.
8609
8610 For certain sensitive attribute deletions, raises an auditing event
8611 "object.__delattr__" with arguments "obj" and "name".
8612
8613 object.__dir__(self)
8614
8615 Called when "dir()" is called on the object. An iterable must be
8616 returned. "dir()" converts the returned iterable to a list and
8617 sorts it.
8618
8619
8620 Customizing module attribute access
8621 -----------------------------------
8622
8623 module.__getattr__()
8624 module.__dir__()
8625
8626 Special names "__getattr__" and "__dir__" can be also used to
8627 customize access to module attributes. The "__getattr__" function at
8628 the module level should accept one argument which is the name of an
8629 attribute and return the computed value or raise an "AttributeError".
8630 If an attribute is not found on a module object through the normal
8631 lookup, i.e. "object.__getattribute__()", then "__getattr__" is
8632 searched in the module "__dict__" before raising an "AttributeError".
8633 If found, it is called with the attribute name and the result is
8634 returned.
8635
8636 The "__dir__" function should accept no arguments, and return an
8637 iterable of strings that represents the names accessible on module. If
8638 present, this function overrides the standard "dir()" search on a
8639 module.
8640
8641 module.__class__
8642
8643 For a more fine grained customization of the module behavior (setting
8644 attributes, properties, etc.), one can set the "__class__" attribute
8645 of a module object to a subclass of "types.ModuleType". For example:
8646
8647 import sys
8648 from types import ModuleType
8649
8650 class VerboseModule(ModuleType):
8651 def __repr__(self):
8652 return f'Verbose {self.__name__}'
8653
8654 def __setattr__(self, attr, value):
8655 print(f'Setting {attr}...')
8656 super().__setattr__(attr, value)
8657
8658 sys.modules[__name__].__class__ = VerboseModule
8659
8660 Note:
8661
8662 Defining module "__getattr__" and setting module "__class__" only
8663 affect lookups made using the attribute access syntax – directly
8664 accessing the module globals (whether by code within the module, or
8665 via a reference to the module’s globals dictionary) is unaffected.
8666
8667 Changed in version 3.5: "__class__" module attribute is now writable.
8668
8669 Added in version 3.7: "__getattr__" and "__dir__" module attributes.
8670
8671 See also:
8672
8673 **PEP 562** - Module __getattr__ and __dir__
8674 Describes the "__getattr__" and "__dir__" functions on modules.
8675
8676
8677 Implementing Descriptors
8678 ------------------------
8679
8680 The following methods only apply when an instance of the class
8681 containing the method (a so-called *descriptor* class) appears in an
8682 *owner* class (the descriptor must be in either the owner’s class
8683 dictionary or in the class dictionary for one of its parents). In the
8684 examples below, “the attribute” refers to the attribute whose name is
8685 the key of the property in the owner class’ "__dict__". The "object"
8686 class itself does not implement any of these protocols.
8687
8688 object.__get__(self, instance, owner=None)
8689
8690 Called to get the attribute of the owner class (class attribute
8691 access) or of an instance of that class (instance attribute
8692 access). The optional *owner* argument is the owner class, while
8693 *instance* is the instance that the attribute was accessed through,
8694 or "None" when the attribute is accessed through the *owner*.
8695
8696 This method should return the computed attribute value or raise an
8697 "AttributeError" exception.
8698
8699 **PEP 252** specifies that "__get__()" is callable with one or two
8700 arguments. Python’s own built-in descriptors support this
8701 specification; however, it is likely that some third-party tools
8702 have descriptors that require both arguments. Python’s own
8703 "__getattribute__()" implementation always passes in both arguments
8704 whether they are required or not.
8705
8706 object.__set__(self, instance, value)
8707
8708 Called to set the attribute on an instance *instance* of the owner
8709 class to a new value, *value*.
8710
8711 Note, adding "__set__()" or "__delete__()" changes the kind of
8712 descriptor to a “data descriptor”. See Invoking Descriptors for
8713 more details.
8714
8715 object.__delete__(self, instance)
8716
8717 Called to delete the attribute on an instance *instance* of the
8718 owner class.
8719
8720 Instances of descriptors may also have the "__objclass__" attribute
8721 present:
8722
8723 object.__objclass__
8724
8725 The attribute "__objclass__" is interpreted by the "inspect" module
8726 as specifying the class where this object was defined (setting this
8727 appropriately can assist in runtime introspection of dynamic class
8728 attributes). For callables, it may indicate that an instance of the
8729 given type (or a subclass) is expected or required as the first
8730 positional argument (for example, CPython sets this attribute for
8731 unbound methods that are implemented in C).
8732
8733
8734 Invoking Descriptors
8735 --------------------
8736
8737 In general, a descriptor is an object attribute with “binding
8738 behavior”, one whose attribute access has been overridden by methods
8739 in the descriptor protocol: "__get__()", "__set__()", and
8740 "__delete__()". If any of those methods are defined for an object, it
8741 is said to be a descriptor.
8742
8743 The default behavior for attribute access is to get, set, or delete
8744 the attribute from an object’s dictionary. For instance, "a.x" has a
8745 lookup chain starting with "a.__dict__['x']", then
8746 "type(a).__dict__['x']", and continuing through the base classes of
8747 "type(a)" excluding metaclasses.
8748
8749 However, if the looked-up value is an object defining one of the
8750 descriptor methods, then Python may override the default behavior and
8751 invoke the descriptor method instead. Where this occurs in the
8752 precedence chain depends on which descriptor methods were defined and
8753 how they were called.
8754
8755 The starting point for descriptor invocation is a binding, "a.x". How
8756 the arguments are assembled depends on "a":
8757
8758 Direct Call
8759 The simplest and least common call is when user code directly
8760 invokes a descriptor method: "x.__get__(a)".
8761
8762 Instance Binding
8763 If binding to an object instance, "a.x" is transformed into the
8764 call: "type(a).__dict__['x'].__get__(a, type(a))".
8765
8766 Class Binding
8767 If binding to a class, "A.x" is transformed into the call:
8768 "A.__dict__['x'].__get__(None, A)".
8769
8770 Super Binding
8771 A dotted lookup such as "super(A, a).x" searches
8772 "a.__class__.__mro__" for a base class "B" following "A" and then
8773 returns "B.__dict__['x'].__get__(a, A)". If not a descriptor, "x"
8774 is returned unchanged.
8775
8776 For instance bindings, the precedence of descriptor invocation depends
8777 on which descriptor methods are defined. A descriptor can define any
8778 combination of "__get__()", "__set__()" and "__delete__()". If it
8779 does not define "__get__()", then accessing the attribute will return
8780 the descriptor object itself unless there is a value in the object’s
8781 instance dictionary. If the descriptor defines "__set__()" and/or
8782 "__delete__()", it is a data descriptor; if it defines neither, it is
8783 a non-data descriptor. Normally, data descriptors define both
8784 "__get__()" and "__set__()", while non-data descriptors have just the
8785 "__get__()" method. Data descriptors with "__get__()" and "__set__()"
8786 (and/or "__delete__()") defined always override a redefinition in an
8787 instance dictionary. In contrast, non-data descriptors can be
8788 overridden by instances.
8789
8790 Python methods (including those decorated with "@staticmethod" and
8791 "@classmethod") are implemented as non-data descriptors. Accordingly,
8792 instances can redefine and override methods. This allows individual
8793 instances to acquire behaviors that differ from other instances of the
8794 same class.
8795
8796 The "property()" function is implemented as a data descriptor.
8797 Accordingly, instances cannot override the behavior of a property.
8798
8799
8800 __slots__
8801 ---------
8802
8803 *__slots__* allow us to explicitly declare data members (like
8804 properties) and deny the creation of "__dict__" and *__weakref__*
8805 (unless explicitly declared in *__slots__* or available in a parent.)
8806
8807 The space saved over using "__dict__" can be significant. Attribute
8808 lookup speed can be significantly improved as well.
8809
8810 object.__slots__
8811
8812 This class variable can be assigned a string, iterable, or sequence
8813 of strings with variable names used by instances. *__slots__*
8814 reserves space for the declared variables and prevents the
8815 automatic creation of "__dict__" and *__weakref__* for each
8816 instance.
8817
8818 Notes on using *__slots__*:
8819
8820 * When inheriting from a class without *__slots__*, the "__dict__" and
8821 *__weakref__* attribute of the instances will always be accessible.
8822
8823 * Without a "__dict__" variable, instances cannot be assigned new
8824 variables not listed in the *__slots__* definition. Attempts to
8825 assign to an unlisted variable name raises "AttributeError". If
8826 dynamic assignment of new variables is desired, then add
8827 "'__dict__'" to the sequence of strings in the *__slots__*
8828 declaration.
8829
8830 * Without a *__weakref__* variable for each instance, classes defining
8831 *__slots__* do not support "weak references" to its instances. If
8832 weak reference support is needed, then add "'__weakref__'" to the
8833 sequence of strings in the *__slots__* declaration.
8834
8835 * *__slots__* are implemented at the class level by creating
8836 descriptors for each variable name. As a result, class attributes
8837 cannot be used to set default values for instance variables defined
8838 by *__slots__*; otherwise, the class attribute would overwrite the
8839 descriptor assignment.
8840
8841 * The action of a *__slots__* declaration is not limited to the class
8842 where it is defined. *__slots__* declared in parents are available
8843 in child classes. However, instances of a child subclass will get a
8844 "__dict__" and *__weakref__* unless the subclass also defines
8845 *__slots__* (which should only contain names of any *additional*
8846 slots).
8847
8848 * If a class defines a slot also defined in a base class, the instance
8849 variable defined by the base class slot is inaccessible (except by
8850 retrieving its descriptor directly from the base class). This
8851 renders the meaning of the program undefined. In the future, a
8852 check may be added to prevent this.
8853
8854 * "TypeError" will be raised if nonempty *__slots__* are defined for a
8855 class derived from a ""variable-length" built-in type" such as
8856 "int", "bytes", and "tuple".
8857
8858 * Any non-string *iterable* may be assigned to *__slots__*.
8859
8860 * If a "dictionary" is used to assign *__slots__*, the dictionary keys
8861 will be used as the slot names. The values of the dictionary can be
8862 used to provide per-attribute docstrings that will be recognised by
8863 "inspect.getdoc()" and displayed in the output of "help()".
8864
8865 * "__class__" assignment works only if both classes have the same
8866 *__slots__*.
8867
8868 * Multiple inheritance with multiple slotted parent classes can be
8869 used, but only one parent is allowed to have attributes created by
8870 slots (the other bases must have empty slot layouts) - violations
8871 raise "TypeError".
8872
8873 * If an *iterator* is used for *__slots__* then a *descriptor* is
8874 created for each of the iterator’s values. However, the *__slots__*
8875 attribute will be an empty iterator.
8876
8877
8878 Customizing class creation
8879 ==========================
8880
8881 Whenever a class inherits from another class, "__init_subclass__()" is
8882 called on the parent class. This way, it is possible to write classes
8883 which change the behavior of subclasses. This is closely related to
8884 class decorators, but where class decorators only affect the specific
8885 class they’re applied to, "__init_subclass__" solely applies to future
8886 subclasses of the class defining the method.
8887
8888 classmethod object.__init_subclass__(cls)
8889
8890 This method is called whenever the containing class is subclassed.
8891 *cls* is then the new subclass. If defined as a normal instance
8892 method, this method is implicitly converted to a class method.
8893
8894 Keyword arguments which are given to a new class are passed to the
8895 parent class’s "__init_subclass__". For compatibility with other
8896 classes using "__init_subclass__", one should take out the needed
8897 keyword arguments and pass the others over to the base class, as
8898 in:
8899
8900 class Philosopher:
8901 def __init_subclass__(cls, /, default_name, **kwargs):
8902 super().__init_subclass__(**kwargs)
8903 cls.default_name = default_name
8904
8905 class AustralianPhilosopher(Philosopher, default_name="Bruce"):
8906 pass
8907
8908 The default implementation "object.__init_subclass__" does nothing,
8909 but raises an error if it is called with any arguments.
8910
8911 Note:
8912
8913 The metaclass hint "metaclass" is consumed by the rest of the
8914 type machinery, and is never passed to "__init_subclass__"
8915 implementations. The actual metaclass (rather than the explicit
8916 hint) can be accessed as "type(cls)".
8917
8918 Added in version 3.6.
8919
8920 When a class is created, "type.__new__()" scans the class variables
8921 and makes callbacks to those with a "__set_name__()" hook.
8922
8923 object.__set_name__(self, owner, name)
8924
8925 Automatically called at the time the owning class *owner* is
8926 created. The object has been assigned to *name* in that class:
8927
8928 class A:
8929 x = C() # Automatically calls: x.__set_name__(A, 'x')
8930
8931 If the class variable is assigned after the class is created,
8932 "__set_name__()" will not be called automatically. If needed,
8933 "__set_name__()" can be called directly:
8934
8935 class A:
8936 pass
8937
8938 c = C()
8939 A.x = c # The hook is not called
8940 c.__set_name__(A, 'x') # Manually invoke the hook
8941
8942 See Creating the class object for more details.
8943
8944 Added in version 3.6.
8945
8946
8947 Metaclasses
8948 -----------
8949
8950 By default, classes are constructed using "type()". The class body is
8951 executed in a new namespace and the class name is bound locally to the
8952 result of "type(name, bases, namespace)".
8953
8954 The class creation process can be customized by passing the
8955 "metaclass" keyword argument in the class definition line, or by
8956 inheriting from an existing class that included such an argument. In
8957 the following example, both "MyClass" and "MySubclass" are instances
8958 of "Meta":
8959
8960 class Meta(type):
8961 pass
8962
8963 class MyClass(metaclass=Meta):
8964 pass
8965
8966 class MySubclass(MyClass):
8967 pass
8968
8969 Any other keyword arguments that are specified in the class definition
8970 are passed through to all metaclass operations described below.
8971
8972 When a class definition is executed, the following steps occur:
8973
8974 * MRO entries are resolved;
8975
8976 * the appropriate metaclass is determined;
8977
8978 * the class namespace is prepared;
8979
8980 * the class body is executed;
8981
8982 * the class object is created.
8983
8984
8985 Resolving MRO entries
8986 ---------------------
8987
8988 object.__mro_entries__(self, bases)
8989
8990 If a base that appears in a class definition is not an instance of
8991 "type", then an "__mro_entries__()" method is searched on the base.
8992 If an "__mro_entries__()" method is found, the base is substituted
8993 with the result of a call to "__mro_entries__()" when creating the
8994 class. The method is called with the original bases tuple passed to
8995 the *bases* parameter, and must return a tuple of classes that will
8996 be used instead of the base. The returned tuple may be empty: in
8997 these cases, the original base is ignored.
8998
8999 See also:
9000
9001 "types.resolve_bases()"
9002 Dynamically resolve bases that are not instances of "type".
9003
9004 "types.get_original_bases()"
9005 Retrieve a class’s “original bases” prior to modifications by
9006 "__mro_entries__()".
9007
9008 **PEP 560**
9009 Core support for typing module and generic types.
9010
9011
9012 Determining the appropriate metaclass
9013 -------------------------------------
9014
9015 The appropriate metaclass for a class definition is determined as
9016 follows:
9017
9018 * if no bases and no explicit metaclass are given, then "type()" is
9019 used;
9020
9021 * if an explicit metaclass is given and it is *not* an instance of
9022 "type()", then it is used directly as the metaclass;
9023
9024 * if an instance of "type()" is given as the explicit metaclass, or
9025 bases are defined, then the most derived metaclass is used.
9026
9027 The most derived metaclass is selected from the explicitly specified
9028 metaclass (if any) and the metaclasses (i.e. "type(cls)") of all
9029 specified base classes. The most derived metaclass is one which is a
9030 subtype of *all* of these candidate metaclasses. If none of the
9031 candidate metaclasses meets that criterion, then the class definition
9032 will fail with "TypeError".
9033
9034
9035 Preparing the class namespace
9036 -----------------------------
9037
9038 Once the appropriate metaclass has been identified, then the class
9039 namespace is prepared. If the metaclass has a "__prepare__" attribute,
9040 it is called as "namespace = metaclass.__prepare__(name, bases,
9041 **kwds)" (where the additional keyword arguments, if any, come from
9042 the class definition). The "__prepare__" method should be implemented
9043 as a "classmethod". The namespace returned by "__prepare__" is passed
9044 in to "__new__", but when the final class object is created the
9045 namespace is copied into a new "dict".
9046
9047 If the metaclass has no "__prepare__" attribute, then the class
9048 namespace is initialised as an empty ordered mapping.
9049
9050 See also:
9051
9052 **PEP 3115** - Metaclasses in Python 3000
9053 Introduced the "__prepare__" namespace hook
9054
9055
9056 Executing the class body
9057 ------------------------
9058
9059 The class body is executed (approximately) as "exec(body, globals(),
9060 namespace)". The key difference from a normal call to "exec()" is that
9061 lexical scoping allows the class body (including any methods) to
9062 reference names from the current and outer scopes when the class
9063 definition occurs inside a function.
9064
9065 However, even when the class definition occurs inside the function,
9066 methods defined inside the class still cannot see names defined at the
9067 class scope. Class variables must be accessed through the first
9068 parameter of instance or class methods, or through the implicit
9069 lexically scoped "__class__" reference described in the next section.
9070
9071
9072 Creating the class object
9073 -------------------------
9074
9075 Once the class namespace has been populated by executing the class
9076 body, the class object is created by calling "metaclass(name, bases,
9077 namespace, **kwds)" (the additional keywords passed here are the same
9078 as those passed to "__prepare__").
9079
9080 This class object is the one that will be referenced by the zero-
9081 argument form of "super()". "__class__" is an implicit closure
9082 reference created by the compiler if any methods in a class body refer
9083 to either "__class__" or "super". This allows the zero argument form
9084 of "super()" to correctly identify the class being defined based on
9085 lexical scoping, while the class or instance that was used to make the
9086 current call is identified based on the first argument passed to the
9087 method.
9088
9089 **CPython implementation detail:** In CPython 3.6 and later, the
9090 "__class__" cell is passed to the metaclass as a "__classcell__" entry
9091 in the class namespace. If present, this must be propagated up to the
9092 "type.__new__" call in order for the class to be initialised
9093 correctly. Failing to do so will result in a "RuntimeError" in Python
9094 3.8.
9095
9096 When using the default metaclass "type", or any metaclass that
9097 ultimately calls "type.__new__", the following additional
9098 customization steps are invoked after creating the class object:
9099
9100 1. The "type.__new__" method collects all of the attributes in the
9101 class namespace that define a "__set_name__()" method;
9102
9103 2. Those "__set_name__" methods are called with the class being
9104 defined and the assigned name of that particular attribute;
9105
9106 3. The "__init_subclass__()" hook is called on the immediate parent of
9107 the new class in its method resolution order.
9108
9109 After the class object is created, it is passed to the class
9110 decorators included in the class definition (if any) and the resulting
9111 object is bound in the local namespace as the defined class.
9112
9113 When a new class is created by "type.__new__", the object provided as
9114 the namespace parameter is copied to a new ordered mapping and the
9115 original object is discarded. The new copy is wrapped in a read-only
9116 proxy, which becomes the "__dict__" attribute of the class object.
9117
9118 See also:
9119
9120 **PEP 3135** - New super
9121 Describes the implicit "__class__" closure reference
9122
9123
9124 Uses for metaclasses
9125 --------------------
9126
9127 The potential uses for metaclasses are boundless. Some ideas that have
9128 been explored include enum, logging, interface checking, automatic
9129 delegation, automatic property creation, proxies, frameworks, and
9130 automatic resource locking/synchronization.
9131
9132
9133 Customizing instance and subclass checks
9134 ========================================
9135
9136 The following methods are used to override the default behavior of the
9137 "isinstance()" and "issubclass()" built-in functions.
9138
9139 In particular, the metaclass "abc.ABCMeta" implements these methods in
9140 order to allow the addition of Abstract Base Classes (ABCs) as
9141 “virtual base classes” to any class or type (including built-in
9142 types), including other ABCs.
9143
9144 type.__instancecheck__(self, instance)
9145
9146 Return true if *instance* should be considered a (direct or
9147 indirect) instance of *class*. If defined, called to implement
9148 "isinstance(instance, class)".
9149
9150 type.__subclasscheck__(self, subclass)
9151
9152 Return true if *subclass* should be considered a (direct or
9153 indirect) subclass of *class*. If defined, called to implement
9154 "issubclass(subclass, class)".
9155
9156 Note that these methods are looked up on the type (metaclass) of a
9157 class. They cannot be defined as class methods in the actual class.
9158 This is consistent with the lookup of special methods that are called
9159 on instances, only in this case the instance is itself a class.
9160
9161 See also:
9162
9163 **PEP 3119** - Introducing Abstract Base Classes
9164 Includes the specification for customizing "isinstance()" and
9165 "issubclass()" behavior through "__instancecheck__()" and
9166 "__subclasscheck__()", with motivation for this functionality in
9167 the context of adding Abstract Base Classes (see the "abc"
9168 module) to the language.
9169
9170
9171 Emulating generic types
9172 =======================
9173
9174 When using *type annotations*, it is often useful to *parameterize* a
9175 *generic type* using Python’s square-brackets notation. For example,
9176 the annotation "list[int]" might be used to signify a "list" in which
9177 all the elements are of type "int".
9178
9179 See also:
9180
9181 **PEP 484** - Type Hints
9182 Introducing Python’s framework for type annotations
9183
9184 Generic Alias Types
9185 Documentation for objects representing parameterized generic
9186 classes
9187
9188 Generics, user-defined generics and "typing.Generic"
9189 Documentation on how to implement generic classes that can be
9190 parameterized at runtime and understood by static type-checkers.
9191
9192 A class can *generally* only be parameterized if it defines the
9193 special class method "__class_getitem__()".
9194
9195 classmethod object.__class_getitem__(cls, key)
9196
9197 Return an object representing the specialization of a generic class
9198 by type arguments found in *key*.
9199
9200 When defined on a class, "__class_getitem__()" is automatically a
9201 class method. As such, there is no need for it to be decorated with
9202 "@classmethod" when it is defined.
9203
9204
9205 The purpose of *__class_getitem__*
9206 ----------------------------------
9207
9208 The purpose of "__class_getitem__()" is to allow runtime
9209 parameterization of standard-library generic classes in order to more
9210 easily apply *type hints* to these classes.
9211
9212 To implement custom generic classes that can be parameterized at
9213 runtime and understood by static type-checkers, users should either
9214 inherit from a standard library class that already implements
9215 "__class_getitem__()", or inherit from "typing.Generic", which has its
9216 own implementation of "__class_getitem__()".
9217
9218 Custom implementations of "__class_getitem__()" on classes defined
9219 outside of the standard library may not be understood by third-party
9220 type-checkers such as mypy. Using "__class_getitem__()" on any class
9221 for purposes other than type hinting is discouraged.
9222
9223
9224 *__class_getitem__* versus *__getitem__*
9225 ----------------------------------------
9226
9227 Usually, the subscription of an object using square brackets will call
9228 the "__getitem__()" instance method defined on the object’s class.
9229 However, if the object being subscribed is itself a class, the class
9230 method "__class_getitem__()" may be called instead.
9231 "__class_getitem__()" should return a GenericAlias object if it is
9232 properly defined.
9233
9234 Presented with the *expression* "obj[x]", the Python interpreter
9235 follows something like the following process to decide whether
9236 "__getitem__()" or "__class_getitem__()" should be called:
9237
9238 from inspect import isclass
9239
9240 def subscribe(obj, x):
9241 """Return the result of the expression 'obj[x]'"""
9242
9243 class_of_obj = type(obj)
9244
9245 # If the class of obj defines __getitem__,
9246 # call class_of_obj.__getitem__(obj, x)
9247 if hasattr(class_of_obj, '__getitem__'):
9248 return class_of_obj.__getitem__(obj, x)
9249
9250 # Else, if obj is a class and defines __class_getitem__,
9251 # call obj.__class_getitem__(x)
9252 elif isclass(obj) and hasattr(obj, '__class_getitem__'):
9253 return obj.__class_getitem__(x)
9254
9255 # Else, raise an exception
9256 else:
9257 raise TypeError(
9258 f"'{class_of_obj.__name__}' object is not subscriptable"
9259 )
9260
9261 In Python, all classes are themselves instances of other classes. The
9262 class of a class is known as that class’s *metaclass*, and most
9263 classes have the "type" class as their metaclass. "type" does not
9264 define "__getitem__()", meaning that expressions such as "list[int]",
9265 "dict[str, float]" and "tuple[str, bytes]" all result in
9266 "__class_getitem__()" being called:
9267
9268 >>> # list has class "type" as its metaclass, like most classes:
9269 >>> type(list)
9270 <class 'type'>
9271 >>> type(dict) == type(list) == type(tuple) == type(str) == type(bytes)
9272 True
9273 >>> # "list[int]" calls "list.__class_getitem__(int)"
9274 >>> list[int]
9275 list[int]
9276 >>> # list.__class_getitem__ returns a GenericAlias object:
9277 >>> type(list[int])
9278 <class 'types.GenericAlias'>
9279
9280 However, if a class has a custom metaclass that defines
9281 "__getitem__()", subscribing the class may result in different
9282 behaviour. An example of this can be found in the "enum" module:
9283
9284 >>> from enum import Enum
9285 >>> class Menu(Enum):
9286 ... """A breakfast menu"""
9287 ... SPAM = 'spam'
9288 ... BACON = 'bacon'
9289 ...
9290 >>> # Enum classes have a custom metaclass:
9291 >>> type(Menu)
9292 <class 'enum.EnumMeta'>
9293 >>> # EnumMeta defines __getitem__,
9294 >>> # so __class_getitem__ is not called,
9295 >>> # and the result is not a GenericAlias object:
9296 >>> Menu['SPAM']
9297 <Menu.SPAM: 'spam'>
9298 >>> type(Menu['SPAM'])
9299 <enum 'Menu'>
9300
9301 See also:
9302
9303 **PEP 560** - Core Support for typing module and generic types
9304 Introducing "__class_getitem__()", and outlining when a
9305 subscription results in "__class_getitem__()" being called
9306 instead of "__getitem__()"
9307
9308
9309 Emulating callable objects
9310 ==========================
9311
9312 object.__call__(self[, args...])
9313
9314 Called when the instance is “called” as a function; if this method
9315 is defined, "x(arg1, arg2, ...)" roughly translates to
9316 "type(x).__call__(x, arg1, ...)". The "object" class itself does
9317 not provide this method.
9318
9319
9320 Emulating container types
9321 =========================
9322
9323 The following methods can be defined to implement container objects.
9324 None of them are provided by the "object" class itself. Containers
9325 usually are *sequences* (such as "lists" or "tuples") or *mappings*
9326 (like *dictionaries*), but can represent other containers as well.
9327 The first set of methods is used either to emulate a sequence or to
9328 emulate a mapping; the difference is that for a sequence, the
9329 allowable keys should be the integers *k* for which "0 <= k < N" where
9330 *N* is the length of the sequence, or "slice" objects, which define a
9331 range of items. It is also recommended that mappings provide the
9332 methods "keys()", "values()", "items()", "get()", "clear()",
9333 "setdefault()", "pop()", "popitem()", "copy()", and "update()"
9334 behaving similar to those for Python’s standard "dictionary" objects.
9335 The "collections.abc" module provides a "MutableMapping" *abstract
9336 base class* to help create those methods from a base set of
9337 "__getitem__()", "__setitem__()", "__delitem__()", and "keys()".
9338
9339 Mutable sequences should provide methods "append()", "clear()",
9340 "count()", "extend()", "index()", "insert()", "pop()", "remove()", and
9341 "reverse()", like Python standard "list" objects. Finally, sequence
9342 types should implement addition (meaning concatenation) and
9343 multiplication (meaning repetition) by defining the methods
9344 "__add__()", "__radd__()", "__iadd__()", "__mul__()", "__rmul__()" and
9345 "__imul__()" described below; they should not define other numerical
9346 operators.
9347
9348 It is recommended that both mappings and sequences implement the
9349 "__contains__()" method to allow efficient use of the "in" operator;
9350 for mappings, "in" should search the mapping’s keys; for sequences, it
9351 should search through the values. It is further recommended that both
9352 mappings and sequences implement the "__iter__()" method to allow
9353 efficient iteration through the container; for mappings, "__iter__()"
9354 should iterate through the object’s keys; for sequences, it should
9355 iterate through the values.
9356
9357 object.__len__(self)
9358
9359 Called to implement the built-in function "len()". Should return
9360 the length of the object, an integer ">=" 0. Also, an object that
9361 doesn’t define a "__bool__()" method and whose "__len__()" method
9362 returns zero is considered to be false in a Boolean context.
9363
9364 **CPython implementation detail:** In CPython, the length is
9365 required to be at most "sys.maxsize". If the length is larger than
9366 "sys.maxsize" some features (such as "len()") may raise
9367 "OverflowError". To prevent raising "OverflowError" by truth value
9368 testing, an object must define a "__bool__()" method.
9369
9370 object.__length_hint__(self)
9371
9372 Called to implement "operator.length_hint()". Should return an
9373 estimated length for the object (which may be greater or less than
9374 the actual length). The length must be an integer ">=" 0. The
9375 return value may also be "NotImplemented", which is treated the
9376 same as if the "__length_hint__" method didn’t exist at all. This
9377 method is purely an optimization and is never required for
9378 correctness.
9379
9380 Added in version 3.4.
9381
9382 object.__getitem__(self, subscript)
9383
9384 Called to implement *subscription*, that is, "self[subscript]". See
9385 Subscriptions and slicings for details on the syntax.
9386
9387 There are two types of built-in objects that support subscription
9388 via "__getitem__()":
9389
9390 * **sequences**, where *subscript* (also called *index*) should be
9391 an integer or a "slice" object. See the sequence documentation
9392 for the expected behavior, including handling "slice" objects and
9393 negative indices.
9394
9395 * **mappings**, where *subscript* is also called the *key*. See
9396 mapping documentation for the expected behavior.
9397
9398 If *subscript* is of an inappropriate type, "__getitem__()" should
9399 raise "TypeError". If *subscript* has an inappropriate value,
9400 "__getitem__()" should raise an "LookupError" or one of its
9401 subclasses ("IndexError" for sequences; "KeyError" for mappings).
9402
9403 Note:
9404
9405 Slicing is handled by "__getitem__()", "__setitem__()", and
9406 "__delitem__()". A call like
9407
9408 a[1:2] = b
9409
9410 is translated to
9411
9412 a[slice(1, 2, None)] = b
9413
9414 and so forth. Missing slice items are always filled in with
9415 "None".
9416
9417 Note:
9418
9419 The sequence iteration protocol (used, for example, in "for"
9420 loops), expects that an "IndexError" will be raised for illegal
9421 indexes to allow proper detection of the end of a sequence.
9422
9423 Note:
9424
9425 When subscripting a *class*, the special class method
9426 "__class_getitem__()" may be called instead of "__getitem__()".
9427 See __class_getitem__ versus __getitem__ for more details.
9428
9429 object.__setitem__(self, key, value)
9430
9431 Called to implement assignment to "self[key]". Same note as for
9432 "__getitem__()". This should only be implemented for mappings if
9433 the objects support changes to the values for keys, or if new keys
9434 can be added, or for sequences if elements can be replaced. The
9435 same exceptions should be raised for improper *key* values as for
9436 the "__getitem__()" method.
9437
9438 object.__delitem__(self, key)
9439
9440 Called to implement deletion of "self[key]". Same note as for
9441 "__getitem__()". This should only be implemented for mappings if
9442 the objects support removal of keys, or for sequences if elements
9443 can be removed from the sequence. The same exceptions should be
9444 raised for improper *key* values as for the "__getitem__()" method.
9445
9446 object.__missing__(self, key)
9447
9448 Called by "dict"."__getitem__()" to implement "self[key]" for dict
9449 subclasses when key is not in the dictionary.
9450
9451 object.__iter__(self)
9452
9453 This method is called when an *iterator* is required for a
9454 container. This method should return a new iterator object that can
9455 iterate over all the objects in the container. For mappings, it
9456 should iterate over the keys of the container.
9457
9458 object.__reversed__(self)
9459
9460 Called (if present) by the "reversed()" built-in to implement
9461 reverse iteration. It should return a new iterator object that
9462 iterates over all the objects in the container in reverse order.
9463
9464 If the "__reversed__()" method is not provided, the "reversed()"
9465 built-in will fall back to using the sequence protocol ("__len__()"
9466 and "__getitem__()"). Objects that support the sequence protocol
9467 should only provide "__reversed__()" if they can provide an
9468 implementation that is more efficient than the one provided by
9469 "reversed()".
9470
9471 The membership test operators ("in" and "not in") are normally
9472 implemented as an iteration through a container. However, container
9473 objects can supply the following special method with a more efficient
9474 implementation, which also does not require the object be iterable.
9475
9476 object.__contains__(self, item)
9477
9478 Called to implement membership test operators. Should return true
9479 if *item* is in *self*, false otherwise. For mapping objects, this
9480 should consider the keys of the mapping rather than the values or
9481 the key-item pairs.
9482
9483 For objects that don’t define "__contains__()", the membership test
9484 first tries iteration via "__iter__()", then the old sequence
9485 iteration protocol via "__getitem__()", see this section in the
9486 language reference.
9487
9488
9489 Emulating numeric types
9490 =======================
9491
9492 The following methods can be defined to emulate numeric objects.
9493 Methods corresponding to operations that are not supported by the
9494 particular kind of number implemented (e.g., bitwise operations for
9495 non-integral numbers) should be left undefined.
9496
9497 object.__add__(self, other)
9498 object.__sub__(self, other)
9499 object.__mul__(self, other)
9500 object.__matmul__(self, other)
9501 object.__truediv__(self, other)
9502 object.__floordiv__(self, other)
9503 object.__mod__(self, other)
9504 object.__divmod__(self, other)
9505 object.__pow__(self, other[, modulo])
9506 object.__lshift__(self, other)
9507 object.__rshift__(self, other)
9508 object.__and__(self, other)
9509 object.__xor__(self, other)
9510 object.__or__(self, other)
9511
9512 These methods are called to implement the binary arithmetic
9513 operations ("+", "-", "*", "@", "/", "//", "%", "divmod()",
9514 "pow()", "**", "<<", ">>", "&", "^", "|"). For instance, to
9515 evaluate the expression "x + y", where *x* is an instance of a
9516 class that has an "__add__()" method, "type(x).__add__(x, y)" is
9517 called. The "__divmod__()" method should be the equivalent to
9518 using "__floordiv__()" and "__mod__()"; it should not be related to
9519 "__truediv__()". Note that "__pow__()" should be defined to accept
9520 an optional third argument if the three-argument version of the
9521 built-in "pow()" function is to be supported.
9522
9523 If one of those methods does not support the operation with the
9524 supplied arguments, it should return "NotImplemented".
9525
9526 object.__radd__(self, other)
9527 object.__rsub__(self, other)
9528 object.__rmul__(self, other)
9529 object.__rmatmul__(self, other)
9530 object.__rtruediv__(self, other)
9531 object.__rfloordiv__(self, other)
9532 object.__rmod__(self, other)
9533 object.__rdivmod__(self, other)
9534 object.__rpow__(self, other[, modulo])
9535 object.__rlshift__(self, other)
9536 object.__rrshift__(self, other)
9537 object.__rand__(self, other)
9538 object.__rxor__(self, other)
9539 object.__ror__(self, other)
9540
9541 These methods are called to implement the binary arithmetic
9542 operations ("+", "-", "*", "@", "/", "//", "%", "divmod()",
9543 "pow()", "**", "<<", ">>", "&", "^", "|") with reflected (swapped)
9544 operands. These functions are only called if the operands are of
9545 different types, when the left operand does not support the
9546 corresponding operation [3], or the right operand’s class is
9547 derived from the left operand’s class. [4] For instance, to
9548 evaluate the expression "x - y", where *y* is an instance of a
9549 class that has an "__rsub__()" method, "type(y).__rsub__(y, x)" is
9550 called if "type(x).__sub__(x, y)" returns "NotImplemented" or
9551 "type(y)" is a subclass of "type(x)". [5]
9552
9553 Note that "__rpow__()" should be defined to accept an optional
9554 third argument if the three-argument version of the built-in
9555 "pow()" function is to be supported.
9556
9557 Changed in version 3.14: Three-argument "pow()" now try calling
9558 "__rpow__()" if necessary. Previously it was only called in two-
9559 argument "pow()" and the binary power operator.
9560
9561 Note:
9562
9563 If the right operand’s type is a subclass of the left operand’s
9564 type and that subclass provides a different implementation of the
9565 reflected method for the operation, this method will be called
9566 before the left operand’s non-reflected method. This behavior
9567 allows subclasses to override their ancestors’ operations.
9568
9569 object.__iadd__(self, other)
9570 object.__isub__(self, other)
9571 object.__imul__(self, other)
9572 object.__imatmul__(self, other)
9573 object.__itruediv__(self, other)
9574 object.__ifloordiv__(self, other)
9575 object.__imod__(self, other)
9576 object.__ipow__(self, other[, modulo])
9577 object.__ilshift__(self, other)
9578 object.__irshift__(self, other)
9579 object.__iand__(self, other)
9580 object.__ixor__(self, other)
9581 object.__ior__(self, other)
9582
9583 These methods are called to implement the augmented arithmetic
9584 assignments ("+=", "-=", "*=", "@=", "/=", "//=", "%=", "**=",
9585 "<<=", ">>=", "&=", "^=", "|="). These methods should attempt to
9586 do the operation in-place (modifying *self*) and return the result
9587 (which could be, but does not have to be, *self*). If a specific
9588 method is not defined, or if that method returns "NotImplemented",
9589 the augmented assignment falls back to the normal methods. For
9590 instance, if *x* is an instance of a class with an "__iadd__()"
9591 method, "x += y" is equivalent to "x = x.__iadd__(y)" . If
9592 "__iadd__()" does not exist, or if "x.__iadd__(y)" returns
9593 "NotImplemented", "x.__add__(y)" and "y.__radd__(x)" are
9594 considered, as with the evaluation of "x + y". In certain
9595 situations, augmented assignment can result in unexpected errors
9596 (see Why does a_tuple[i] += [‘item’] raise an exception when the
9597 addition works?), but this behavior is in fact part of the data
9598 model.
9599
9600 object.__neg__(self)
9601 object.__pos__(self)
9602 object.__abs__(self)
9603 object.__invert__(self)
9604
9605 Called to implement the unary arithmetic operations ("-", "+",
9606 "abs()" and "~").
9607
9608 object.__complex__(self)
9609 object.__int__(self)
9610 object.__float__(self)
9611
9612 Called to implement the built-in functions "complex()", "int()" and
9613 "float()". Should return a value of the appropriate type.
9614
9615 object.__index__(self)
9616
9617 Called to implement "operator.index()", and whenever Python needs
9618 to losslessly convert the numeric object to an integer object (such
9619 as in slicing, or in the built-in "bin()", "hex()" and "oct()"
9620 functions). Presence of this method indicates that the numeric
9621 object is an integer type. Must return an integer.
9622
9623 If "__int__()", "__float__()" and "__complex__()" are not defined
9624 then corresponding built-in functions "int()", "float()" and
9625 "complex()" fall back to "__index__()".
9626
9627 object.__round__(self[, ndigits])
9628 object.__trunc__(self)
9629 object.__floor__(self)
9630 object.__ceil__(self)
9631
9632 Called to implement the built-in function "round()" and "math"
9633 functions "trunc()", "floor()" and "ceil()". Unless *ndigits* is
9634 passed to "__round__()" all these methods should return the value
9635 of the object truncated to an "Integral" (typically an "int").
9636
9637 Changed in version 3.14: "int()" no longer delegates to the
9638 "__trunc__()" method.
9639
9640
9641 With Statement Context Managers
9642 ===============================
9643
9644 A *context manager* is an object that defines the runtime context to
9645 be established when executing a "with" statement. The context manager
9646 handles the entry into, and the exit from, the desired runtime context
9647 for the execution of the block of code. Context managers are normally
9648 invoked using the "with" statement (described in section The with
9649 statement), but can also be used by directly invoking their methods.
9650
9651 Typical uses of context managers include saving and restoring various
9652 kinds of global state, locking and unlocking resources, closing opened
9653 files, etc.
9654
9655 For more information on context managers, see Context Manager Types.
9656 The "object" class itself does not provide the context manager
9657 methods.
9658
9659 object.__enter__(self)
9660
9661 Enter the runtime context related to this object. The "with"
9662 statement will bind this method’s return value to the target(s)
9663 specified in the "as" clause of the statement, if any.
9664
9665 object.__exit__(self, exc_type, exc_value, traceback)
9666
9667 Exit the runtime context related to this object. The parameters
9668 describe the exception that caused the context to be exited. If the
9669 context was exited without an exception, all three arguments will
9670 be "None".
9671
9672 If an exception is supplied, and the method wishes to suppress the
9673 exception (i.e., prevent it from being propagated), it should
9674 return a true value. Otherwise, the exception will be processed
9675 normally upon exit from this method.
9676
9677 Note that "__exit__()" methods should not reraise the passed-in
9678 exception; this is the caller’s responsibility.
9679
9680 See also:
9681
9682 **PEP 343** - The “with” statement
9683 The specification, background, and examples for the Python "with"
9684 statement.
9685
9686
9687 Customizing positional arguments in class pattern matching
9688 ==========================================================
9689
9690 When using a class name in a pattern, positional arguments in the
9691 pattern are not allowed by default, i.e. "case MyClass(x, y)" is
9692 typically invalid without special support in "MyClass". To be able to
9693 use that kind of pattern, the class needs to define a *__match_args__*
9694 attribute.
9695
9696 object.__match_args__
9697
9698 This class variable can be assigned a tuple of strings. When this
9699 class is used in a class pattern with positional arguments, each
9700 positional argument will be converted into a keyword argument,
9701 using the corresponding value in *__match_args__* as the keyword.
9702 The absence of this attribute is equivalent to setting it to "()".
9703
9704 For example, if "MyClass.__match_args__" is "("left", "center",
9705 "right")" that means that "case MyClass(x, y)" is equivalent to "case
9706 MyClass(left=x, center=y)". Note that the number of arguments in the
9707 pattern must be smaller than or equal to the number of elements in
9708 *__match_args__*; if it is larger, the pattern match attempt will
9709 raise a "TypeError".
9710
9711 Added in version 3.10.
9712
9713 See also:
9714
9715 **PEP 634** - Structural Pattern Matching
9716 The specification for the Python "match" statement.
9717
9718
9719 Emulating buffer types
9720 ======================
9721
9722 The buffer protocol provides a way for Python objects to expose
9723 efficient access to a low-level memory array. This protocol is
9724 implemented by builtin types such as "bytes" and "memoryview", and
9725 third-party libraries may define additional buffer types.
9726
9727 While buffer types are usually implemented in C, it is also possible
9728 to implement the protocol in Python.
9729
9730 object.__buffer__(self, flags)
9731
9732 Called when a buffer is requested from *self* (for example, by the
9733 "memoryview" constructor). The *flags* argument is an integer
9734 representing the kind of buffer requested, affecting for example
9735 whether the returned buffer is read-only or writable.
9736 "inspect.BufferFlags" provides a convenient way to interpret the
9737 flags. The method must return a "memoryview" object.
9738
9739 **Thread safety:** In *free-threaded* Python, implementations must
9740 manage any internal export counter using atomic operations. The
9741 method must be safe to call concurrently from multiple threads, and
9742 the returned buffer’s underlying data must remain valid until the
9743 corresponding "__release_buffer__()" call completes. See Thread
9744 safety for memoryview objects for details.
9745
9746 object.__release_buffer__(self, buffer)
9747
9748 Called when a buffer is no longer needed. The *buffer* argument is
9749 a "memoryview" object that was previously returned by
9750 "__buffer__()". The method must release any resources associated
9751 with the buffer. This method should return "None".
9752
9753 **Thread safety:** In *free-threaded* Python, any export counter
9754 decrement must use atomic operations. Resource cleanup must be
9755 thread-safe, as the final release may race with concurrent releases
9756 from other threads.
9757
9758 Buffer objects that do not need to perform any cleanup are not
9759 required to implement this method.
9760
9761 Added in version 3.12.
9762
9763 See also:
9764
9765 **PEP 688** - Making the buffer protocol accessible in Python
9766 Introduces the Python "__buffer__" and "__release_buffer__"
9767 methods.
9768
9769 "collections.abc.Buffer"
9770 ABC for buffer types.
9771
9772
9773 Annotations
9774 ===========
9775
9776 Functions, classes, and modules may contain *annotations*, which are a
9777 way to associate information (usually *type hints*) with a symbol.
9778
9779 object.__annotations__
9780
9781 This attribute contains the annotations for an object. It is lazily
9782 evaluated, so accessing the attribute may execute arbitrary code
9783 and raise exceptions. If evaluation is successful, the attribute is
9784 set to a dictionary mapping from variable names to annotations.
9785
9786 Changed in version 3.14: Annotations are now lazily evaluated.
9787
9788 object.__annotate__(format)
9789
9790 An *annotate function*. Returns a new dictionary object mapping
9791 attribute/parameter names to their annotation values.
9792
9793 Takes a format parameter specifying the format in which annotations
9794 values should be provided. It must be a member of the
9795 "annotationlib.Format" enum, or an integer with a value
9796 corresponding to a member of the enum.
9797
9798 If an annotate function doesn’t support the requested format, it
9799 must raise "NotImplementedError". Annotate functions must always
9800 support "VALUE" format; they must not raise "NotImplementedError()"
9801 when called with this format.
9802
9803 When called with "VALUE" format, an annotate function may raise
9804 "NameError"; it must not raise "NameError" when called requesting
9805 any other format.
9806
9807 If an object does not have any annotations, "__annotate__" should
9808 preferably be set to "None" (it can’t be deleted), rather than set
9809 to a function that returns an empty dict.
9810
9811 Added in version 3.14.
9812
9813 See also:
9814
9815 **PEP 649** — Deferred evaluation of annotation using descriptors
9816 Introduces lazy evaluation of annotations and the "__annotate__"
9817 function.
9818
9819
9820 Special method lookup
9821 =====================
9822
9823 For custom classes, implicit invocations of special methods are only
9824 guaranteed to work correctly if defined on an object’s type, not in
9825 the object’s instance dictionary. That behaviour is the reason why
9826 the following code raises an exception:
9827
9828 >>> class C:
9829 ... pass
9830 ...
9831 >>> c = C()
9832 >>> c.__len__ = lambda: 5
9833 >>> len(c)
9834 Traceback (most recent call last):
9835 File "<stdin>", line 1, in <module>
9836 TypeError: object of type 'C' has no len()
9837
9838 The rationale behind this behaviour lies with a number of special
9839 methods such as "__hash__()" and "__repr__()" that are implemented by
9840 all objects, including type objects. If the implicit lookup of these
9841 methods used the conventional lookup process, they would fail when
9842 invoked on the type object itself:
9843
9844 >>> 1 .__hash__() == hash(1)
9845 True
9846 >>> int.__hash__() == hash(int)
9847 Traceback (most recent call last):
9848 File "<stdin>", line 1, in <module>
9849 TypeError: descriptor '__hash__' of 'int' object needs an argument
9850
9851 Incorrectly attempting to invoke an unbound method of a class in this
9852 way is sometimes referred to as ‘metaclass confusion’, and is avoided
9853 by bypassing the instance when looking up special methods:
9854
9855 >>> type(1).__hash__(1) == hash(1)
9856 True
9857 >>> type(int).__hash__(int) == hash(int)
9858 True
9859
9860 In addition to bypassing any instance attributes in the interest of
9861 correctness, implicit special method lookup generally also bypasses
9862 the "__getattribute__()" method even of the object’s metaclass:
9863
9864 >>> class Meta(type):
9865 ... def __getattribute__(*args):
9866 ... print("Metaclass getattribute invoked")
9867 ... return type.__getattribute__(*args)
9868 ...
9869 >>> class C(object, metaclass=Meta):
9870 ... def __len__(self):
9871 ... return 10
9872 ... def __getattribute__(*args):
9873 ... print("Class getattribute invoked")
9874 ... return object.__getattribute__(*args)
9875 ...
9876 >>> c = C()
9877 >>> c.__len__() # Explicit lookup via instance
9878 Class getattribute invoked
9879 10
9880 >>> type(c).__len__(c) # Explicit lookup via type
9881 Metaclass getattribute invoked
9882 10
9883 >>> len(c) # Implicit lookup
9884 10
9885
9886 Bypassing the "__getattribute__()" machinery in this fashion provides
9887 significant scope for speed optimisations within the interpreter, at
9888 the cost of some flexibility in the handling of special methods (the
9889 special method *must* be set on the class object itself in order to be
9890 consistently invoked by the interpreter).
9891 ''',
9892 'string-methods': r'''String Methods
9893 **************
9894
9895 Strings implement all of the common sequence operations, along with
9896 the additional methods described below.
9897
9898 Strings also support two styles of string formatting, one providing a
9899 large degree of flexibility and customization (see "str.format()",
9900 Format string syntax and Custom string formatting) and the other based
9901 on C "printf" style formatting that handles a narrower range of types
9902 and is slightly harder to use correctly, but is often faster for the
9903 cases it can handle (printf-style String Formatting).
9904
9905 The Text Processing Services section of the standard library covers a
9906 number of other modules that provide various text related utilities
9907 (including regular expression support in the "re" module).
9908
9909 str.capitalize()
9910
9911 Return a copy of the string with its first character capitalized
9912 and the rest lowercased.
9913
9914 Changed in version 3.8: The first character is now put into
9915 titlecase rather than uppercase. This means that characters like
9916 digraphs will only have their first letter capitalized, instead of
9917 the full character.
9918
9919 str.casefold()
9920
9921 Return a casefolded copy of the string. Casefolded strings may be
9922 used for caseless matching.
9923
9924 Casefolding is similar to lowercasing but more aggressive because
9925 it is intended to remove all case distinctions in a string. For
9926 example, the German lowercase letter "'ß'" is equivalent to ""ss"".
9927 Since it is already lowercase, "lower()" would do nothing to "'ß'";
9928 "casefold()" converts it to ""ss"". For example:
9929
9930 >>> 'straße'.lower()
9931 'straße'
9932 >>> 'straße'.casefold()
9933 'strasse'
9934
9935 The casefolding algorithm is described in section 3.13 ‘Default
9936 Case Folding’ of the Unicode Standard.
9937
9938 Added in version 3.3.
9939
9940 str.center(width, fillchar=' ', /)
9941
9942 Return centered in a string of length *width*. Padding is done
9943 using the specified *fillchar* (default is an ASCII space). The
9944 original string is returned if *width* is less than or equal to
9945 "len(s)". For example:
9946
9947 >>> 'Python'.center(10)
9948 ' Python '
9949 >>> 'Python'.center(10, '-')
9950 '--Python--'
9951 >>> 'Python'.center(4)
9952 'Python'
9953
9954 str.count(sub[, start[, end]])
9955
9956 Return the number of non-overlapping occurrences of substring *sub*
9957 in the range [*start*, *end*]. Optional arguments *start* and
9958 *end* are interpreted as in slice notation.
9959
9960 If *sub* is empty, returns the number of empty strings between
9961 characters which is the length of the string plus one. For example:
9962
9963 >>> 'spam, spam, spam'.count('spam')
9964 3
9965 >>> 'spam, spam, spam'.count('spam', 5)
9966 2
9967 >>> 'spam, spam, spam'.count('spam', 5, 10)
9968 1
9969 >>> 'spam, spam, spam'.count('eggs')
9970 0
9971 >>> 'spam, spam, spam'.count('')
9972 17
9973
9974 str.encode(encoding='utf-8', errors='strict')
9975
9976 Return the string encoded to "bytes".
9977
9978 *encoding* defaults to "'utf-8'"; see Standard Encodings for
9979 possible values.
9980
9981 *errors* controls how encoding errors are handled. If "'strict'"
9982 (the default), a "UnicodeError" exception is raised. Other possible
9983 values are "'ignore'", "'replace'", "'xmlcharrefreplace'",
9984 "'backslashreplace'" and any other name registered via
9985 "codecs.register_error()". See Error Handlers for details.
9986
9987 For performance reasons, the value of *errors* is not checked for
9988 validity unless an encoding error actually occurs, Python
9989 Development Mode is enabled or a debug build is used. For example:
9990
9991 >>> encoded_str_to_bytes = 'Python'.encode()
9992 >>> type(encoded_str_to_bytes)
9993 <class 'bytes'>
9994 >>> encoded_str_to_bytes
9995 b'Python'
9996
9997 Changed in version 3.1: Added support for keyword arguments.
9998
9999 Changed in version 3.9: The value of the *errors* argument is now
10000 checked in Python Development Mode and in debug mode.
10001
10002 str.endswith(suffix[, start[, end]])
10003
10004 Return "True" if the string ends with the specified *suffix*,
10005 otherwise return "False". *suffix* can also be a tuple of suffixes
10006 to look for. With optional *start*, test beginning at that
10007 position. With optional *end*, stop comparing at that position.
10008 Using *start* and *end* is equivalent to
10009 "str[start:end].endswith(suffix)". For example:
10010
10011 >>> 'Python'.endswith('on')
10012 True
10013 >>> 'a tuple of suffixes'.endswith(('at', 'in'))
10014 False
10015 >>> 'a tuple of suffixes'.endswith(('at', 'es'))
10016 True
10017 >>> 'Python is amazing'.endswith('is', 0, 9)
10018 True
10019
10020 See also "startswith()" and "removesuffix()".
10021
10022 str.expandtabs(tabsize=8)
10023
10024 Return a copy of the string where all tab characters are replaced
10025 by one or more spaces, depending on the current column and the
10026 given tab size. Tab positions occur every *tabsize* characters
10027 (default is 8, giving tab positions at columns 0, 8, 16 and so on).
10028 To expand the string, the current column is set to zero and the
10029 string is examined character by character. If the character is a
10030 tab ("\t"), one or more space characters are inserted in the result
10031 until the current column is equal to the next tab position. (The
10032 tab character itself is not copied.) If the character is a newline
10033 ("\n") or return ("\r"), it is copied and the current column is
10034 reset to zero. Any other character is copied unchanged and the
10035 current column is incremented by one regardless of how the
10036 character is represented when printed. For example:
10037
10038 >>> '01\t012\t0123\t01234'.expandtabs()
10039 '01 012 0123 01234'
10040 >>> '01\t012\t0123\t01234'.expandtabs(4)
10041 '01 012 0123 01234'
10042 >>> print('01\t012\n0123\t01234'.expandtabs(4))
10043 01 012
10044 0123 01234
10045
10046 str.find(sub[, start[, end]])
10047
10048 Return the lowest index in the string where substring *sub* is
10049 found within the slice "s[start:end]". Optional arguments *start*
10050 and *end* are interpreted as in slice notation. Return "-1" if
10051 *sub* is not found. For example:
10052
10053 >>> 'spam, spam, spam'.find('sp')
10054 0
10055 >>> 'spam, spam, spam'.find('sp', 5)
10056 6
10057
10058 See also "rfind()" and "index()".
10059
10060 Note:
10061
10062 The "find()" method should be used only if you need to know the
10063 position of *sub*. To check if *sub* is a substring or not, use
10064 the "in" operator:
10065
10066 >>> 'Py' in 'Python'
10067 True
10068
10069 str.format(*args, **kwargs)
10070
10071 Perform a string formatting operation. The string on which this
10072 method is called can contain literal text or replacement fields
10073 delimited by braces "{}". Each replacement field contains either
10074 the numeric index of a positional argument, or the name of a
10075 keyword argument. Returns a copy of the string where each
10076 replacement field is replaced with the string value of the
10077 corresponding argument. For example:
10078
10079 >>> "The sum of 1 + 2 is {0}".format(1+2)
10080 'The sum of 1 + 2 is 3'
10081 >>> "The sum of {a} + {b} is {answer}".format(answer=1+2, a=1, b=2)
10082 'The sum of 1 + 2 is 3'
10083 >>> "{1} expects the {0} Inquisition!".format("Spanish", "Nobody")
10084 'Nobody expects the Spanish Inquisition!'
10085
10086 See Format string syntax for a description of the various
10087 formatting options that can be specified in format strings.
10088
10089 Note:
10090
10091 When formatting a number ("int", "float", "complex",
10092 "decimal.Decimal" and subclasses) with the "n" type (ex:
10093 "'{:n}'.format(1234)"), the function temporarily sets the
10094 "LC_CTYPE" locale to the "LC_NUMERIC" locale to decode
10095 "decimal_point" and "thousands_sep" fields of "localeconv()" if
10096 they are non-ASCII or longer than 1 byte, and the "LC_NUMERIC"
10097 locale is different than the "LC_CTYPE" locale. This temporary
10098 change affects other threads.
10099
10100 Changed in version 3.7: When formatting a number with the "n" type,
10101 the function sets temporarily the "LC_CTYPE" locale to the
10102 "LC_NUMERIC" locale in some cases.
10103
10104 str.format_map(mapping, /)
10105
10106 Similar to "str.format(**mapping)", except that "mapping" is used
10107 directly and not copied to a "dict". This is useful if for example
10108 "mapping" is a dict subclass:
10109
10110 >>> class Default(dict):
10111 ... def __missing__(self, key):
10112 ... return key
10113 ...
10114 >>> '{name} was born in {country}'.format_map(Default(name='Guido'))
10115 'Guido was born in country'
10116
10117 Added in version 3.2.
10118
10119 str.index(sub[, start[, end]])
10120
10121 Like "find()", but raise "ValueError" when the substring is not
10122 found. For example:
10123
10124 >>> 'spam, spam, spam'.index('spam')
10125 0
10126 >>> 'spam, spam, spam'.index('eggs')
10127 Traceback (most recent call last):
10128 File "<python-input-0>", line 1, in <module>
10129 'spam, spam, spam'.index('eggs')
10130 ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
10131 ValueError: substring not found
10132
10133 See also "rindex()".
10134
10135 str.isalnum()
10136
10137 Return "True" if all characters in the string are alphanumeric and
10138 there is at least one character, "False" otherwise. A character
10139 "c" is alphanumeric if one of the following returns "True":
10140 "c.isalpha()", "c.isdecimal()", "c.isdigit()", or "c.isnumeric()".
10141 For example:
10142
10143 >>> 'abc123'.isalnum()
10144 True
10145 >>> 'abc123!@#'.isalnum()
10146 False
10147 >>> ''.isalnum()
10148 False
10149 >>> ' '.isalnum()
10150 False
10151
10152 str.isalpha()
10153
10154 Return "True" if all characters in the string are alphabetic and
10155 there is at least one character, "False" otherwise. Alphabetic
10156 characters are those characters defined in the Unicode character
10157 database as “Letter”, i.e., those with general category property
10158 being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is
10159 different from the Alphabetic property defined in the section 4.10
10160 ‘Letters, Alphabetic, and Ideographic’ of the Unicode Standard. For
10161 example:
10162
10163 >>> 'Letters and spaces'.isalpha()
10164 False
10165 >>> 'LettersOnly'.isalpha()
10166 True
10167 >>> 'µ'.isalpha() # non-ASCII characters can be considered alphabetical too
10168 True
10169
10170 See Unicode Properties.
10171
10172 str.isascii()
10173
10174 Return "True" if the string is empty or all characters in the
10175 string are ASCII, "False" otherwise. ASCII characters have code
10176 points in the range U+0000-U+007F. For example:
10177
10178 >>> 'ASCII characters'.isascii()
10179 True
10180 >>> 'µ'.isascii()
10181 False
10182
10183 Added in version 3.7.
10184
10185 str.isdecimal()
10186
10187 Return "True" if all characters in the string are decimal
10188 characters and there is at least one character, "False" otherwise.
10189 Decimal characters are those that can be used to form numbers in
10190 base 10, such as U+0660, ARABIC-INDIC DIGIT ZERO. Formally a
10191 decimal character is a character in the Unicode General Category
10192 “Nd”. For example:
10193
10194 >>> '0123456789'.isdecimal()
10195 True
10196 >>> '٠١٢٣٤٥٦٧٨٩'.isdecimal() # Arabic-Indic digits zero to nine
10197 True
10198 >>> 'alphabetic'.isdecimal()
10199 False
10200
10201 str.isdigit()
10202
10203 Return "True" if all characters in the string are digits and there
10204 is at least one character, "False" otherwise. Digits include
10205 decimal characters and digits that need special handling, such as
10206 the compatibility superscript digits. This covers digits which
10207 cannot be used to form numbers in base 10, like the Kharosthi
10208 numbers. Formally, a digit is a character that has the property
10209 value Numeric_Type=Digit or Numeric_Type=Decimal.
10210
10211 For example:
10212
10213 >>> '0123456789'.isdigit()
10214 True
10215 >>> '٠١٢٣٤٥٦٧٨٩'.isdigit() # Arabic-Indic digits zero to nine
10216 True
10217 >>> '⅕'.isdigit() # Vulgar fraction one fifth
10218 False
10219 >>> '²'.isdecimal(), '²'.isdigit(), '²'.isnumeric()
10220 (False, True, True)
10221
10222 See also "isdecimal()" and "isnumeric()".
10223
10224 str.isidentifier()
10225
10226 Return "True" if the string is a valid identifier according to the
10227 language definition, section Names (identifiers and keywords).
10228
10229 "keyword.iskeyword()" can be used to test whether string "s" is a
10230 reserved identifier, such as "def" and "class".
10231
10232 Example:
10233
10234 >>> from keyword import iskeyword
10235
10236 >>> 'hello'.isidentifier(), iskeyword('hello')
10237 (True, False)
10238 >>> 'def'.isidentifier(), iskeyword('def')
10239 (True, True)
10240
10241 str.islower()
10242
10243 Return "True" if all cased characters [4] in the string are
10244 lowercase and there is at least one cased character, "False"
10245 otherwise.
10246
10247 str.isnumeric()
10248
10249 Return "True" if all characters in the string are numeric
10250 characters, and there is at least one character, "False" otherwise.
10251 Numeric characters include digit characters, and all characters
10252 that have the Unicode numeric value property, e.g. U+2155, VULGAR
10253 FRACTION ONE FIFTH. Formally, numeric characters are those with
10254 the property value Numeric_Type=Digit, Numeric_Type=Decimal or
10255 Numeric_Type=Numeric. For example:
10256
10257 >>> '0123456789'.isnumeric()
10258 True
10259 >>> '٠١٢٣٤٥٦٧٨٩'.isnumeric() # Arabic-Indic digits zero to nine
10260 True
10261 >>> '⅕'.isnumeric() # Vulgar fraction one fifth
10262 True
10263 >>> '²'.isdecimal(), '²'.isdigit(), '²'.isnumeric()
10264 (False, True, True)
10265
10266 See also "isdecimal()" and "isdigit()".
10267
10268 str.isprintable()
10269
10270 Return "True" if all characters in the string are printable,
10271 "False" if it contains at least one non-printable character.
10272
10273 Here “printable” means the character is suitable for "repr()" to
10274 use in its output; “non-printable” means that "repr()" on built-in
10275 types will hex-escape the character. It has no bearing on the
10276 handling of strings written to "sys.stdout" or "sys.stderr".
10277
10278 The printable characters are those which in the Unicode character
10279 database (see "unicodedata") have a general category in group
10280 Letter, Mark, Number, Punctuation, or Symbol (L, M, N, P, or S);
10281 plus the ASCII space 0x20. Nonprintable characters are those in
10282 group Separator or Other (Z or C), except the ASCII space.
10283
10284 For example:
10285
10286 >>> ''.isprintable(), ' '.isprintable()
10287 (True, True)
10288 >>> '\t'.isprintable(), '\n'.isprintable()
10289 (False, False)
10290
10291 See also "isspace()".
10292
10293 str.isspace()
10294
10295 Return "True" if there are only whitespace characters in the string
10296 and there is at least one character, "False" otherwise.
10297
10298 For example:
10299
10300 >>> ''.isspace()
10301 False
10302 >>> ' '.isspace()
10303 True
10304 >>> '\t\n'.isspace() # TAB and BREAK LINE
10305 True
10306 >>> '\u3000'.isspace() # IDEOGRAPHIC SPACE
10307 True
10308
10309 A character is *whitespace* if in the Unicode character database
10310 (see "unicodedata"), either its general category is "Zs"
10311 (“Separator, space”), or its bidirectional class is one of "WS",
10312 "B", or "S".
10313
10314 See also "isprintable()".
10315
10316 str.istitle()
10317
10318 Return "True" if the string is a titlecased string and there is at
10319 least one character, for example uppercase characters may only
10320 follow uncased characters and lowercase characters only cased ones.
10321 Return "False" otherwise.
10322
10323 For example:
10324
10325 >>> 'Spam, Spam, Spam'.istitle()
10326 True
10327 >>> 'spam, spam, spam'.istitle()
10328 False
10329 >>> 'SPAM, SPAM, SPAM'.istitle()
10330 False
10331
10332 See also "title()".
10333
10334 str.isupper()
10335
10336 Return "True" if all cased characters [4] in the string are
10337 uppercase and there is at least one cased character, "False"
10338 otherwise.
10339
10340 >>> 'BANANA'.isupper()
10341 True
10342 >>> 'banana'.isupper()
10343 False
10344 >>> 'baNana'.isupper()
10345 False
10346 >>> ' '.isupper()
10347 False
10348
10349 str.join(iterable, /)
10350
10351 Return a string which is the concatenation of the strings in
10352 *iterable*. A "TypeError" will be raised if there are any non-
10353 string values in *iterable*, including "bytes" objects. The
10354 separator between elements is the string providing this method. For
10355 example:
10356
10357 >>> ', '.join(['spam', 'spam', 'spam'])
10358 'spam, spam, spam'
10359 >>> '-'.join('Python')
10360 'P-y-t-h-o-n'
10361
10362 See also "split()".
10363
10364 str.ljust(width, fillchar=' ', /)
10365
10366 Return the string left justified in a string of length *width*.
10367 Padding is done using the specified *fillchar* (default is an ASCII
10368 space). The original string is returned if *width* is less than or
10369 equal to "len(s)".
10370
10371 For example:
10372
10373 >>> 'Python'.ljust(10)
10374 'Python '
10375 >>> 'Python'.ljust(10, '.')
10376 'Python....'
10377 >>> 'Monty Python'.ljust(10, '.')
10378 'Monty Python'
10379
10380 See also "rjust()".
10381
10382 str.lower()
10383
10384 Return a copy of the string with all the cased characters [4]
10385 converted to lowercase. For example:
10386
10387 >>> 'Lower Method Example'.lower()
10388 'lower method example'
10389
10390 The lowercasing algorithm used is described in section 3.13
10391 ‘Default Case Folding’ of the Unicode Standard.
10392
10393 str.lstrip(chars=None, /)
10394
10395 Return a copy of the string with leading characters removed. The
10396 *chars* argument is a string specifying the set of characters to be
10397 removed. If omitted or "None", the *chars* argument defaults to
10398 removing whitespace. The *chars* argument is not a prefix; rather,
10399 all combinations of its values are stripped:
10400
10401 >>> ' spacious '.lstrip()
10402 'spacious '
10403 >>> 'www.example.com'.lstrip('cmowz.')
10404 'example.com'
10405
10406 See "str.removeprefix()" for a method that will remove a single
10407 prefix string rather than all of a set of characters. For example:
10408
10409 >>> 'Arthur: three!'.lstrip('Arthur: ')
10410 'ee!'
10411 >>> 'Arthur: three!'.removeprefix('Arthur: ')
10412 'three!'
10413
10414 static str.maketrans(dict, /)
10415 static str.maketrans(from, to, remove='', /)
10416
10417 This static method returns a translation table usable for
10418 "str.translate()".
10419
10420 If there is only one argument, it must be a dictionary mapping
10421 Unicode ordinals (integers) or characters (strings of length 1) to
10422 Unicode ordinals, strings (of arbitrary lengths) or "None".
10423 Character keys will then be converted to ordinals.
10424
10425 If there are two arguments, they must be strings of equal length,
10426 and in the resulting dictionary, each character in *from* will be
10427 mapped to the character at the same position in *to*. If there is
10428 a third argument, it must be a string, whose characters will be
10429 mapped to "None" in the result.
10430
10431 str.partition(sep, /)
10432
10433 Split the string at the first occurrence of *sep*, and return a
10434 3-tuple containing the part before the separator, the separator
10435 itself, and the part after the separator. If the separator is not
10436 found, return a 3-tuple containing the string itself, followed by
10437 two empty strings.
10438
10439 For example:
10440
10441 >>> 'Monty Python'.partition(' ')
10442 ('Monty', ' ', 'Python')
10443 >>> "Monty Python's Flying Circus".partition(' ')
10444 ('Monty', ' ', "Python's Flying Circus")
10445 >>> 'Monty Python'.partition('-')
10446 ('Monty Python', '', '')
10447
10448 See also "rpartition()".
10449
10450 str.removeprefix(prefix, /)
10451
10452 If the string starts with the *prefix* string, return
10453 "string[len(prefix):]". Otherwise, return a copy of the original
10454 string:
10455
10456 >>> 'TestHook'.removeprefix('Test')
10457 'Hook'
10458 >>> 'BaseTestCase'.removeprefix('Test')
10459 'BaseTestCase'
10460
10461 Added in version 3.9.
10462
10463 See also "removesuffix()" and "startswith()".
10464
10465 str.removesuffix(suffix, /)
10466
10467 If the string ends with the *suffix* string and that *suffix* is
10468 not empty, return "string[:-len(suffix)]". Otherwise, return a copy
10469 of the original string:
10470
10471 >>> 'MiscTests'.removesuffix('Tests')
10472 'Misc'
10473 >>> 'TmpDirMixin'.removesuffix('Tests')
10474 'TmpDirMixin'
10475
10476 Added in version 3.9.
10477
10478 See also "removeprefix()" and "endswith()".
10479
10480 str.replace(old, new, /, count=-1)
10481
10482 Return a copy of the string with all occurrences of substring *old*
10483 replaced by *new*. If *count* is given, only the first *count*
10484 occurrences are replaced. If *count* is not specified or "-1", then
10485 all occurrences are replaced. For example:
10486
10487 >>> 'spam, spam, spam'.replace('spam', 'eggs')
10488 'eggs, eggs, eggs'
10489 >>> 'spam, spam, spam'.replace('spam', 'eggs', 1)
10490 'eggs, spam, spam'
10491
10492 Changed in version 3.13: *count* is now supported as a keyword
10493 argument.
10494
10495 str.rfind(sub[, start[, end]])
10496
10497 Return the highest index in the string where substring *sub* is
10498 found, such that *sub* is contained within "s[start:end]".
10499 Optional arguments *start* and *end* are interpreted as in slice
10500 notation. Return "-1" on failure. For example:
10501
10502 >>> 'spam, spam, spam'.rfind('sp')
10503 12
10504 >>> 'spam, spam, spam'.rfind('sp', 0, 10)
10505 6
10506
10507 See also "find()" and "rindex()".
10508
10509 str.rindex(sub[, start[, end]])
10510
10511 Like "rfind()" but raises "ValueError" when the substring *sub* is
10512 not found. For example:
10513
10514 >>> 'spam, spam, spam'.rindex('spam')
10515 12
10516 >>> 'spam, spam, spam'.rindex('eggs')
10517 Traceback (most recent call last):
10518 File "<stdin-0>", line 1, in <module>
10519 'spam, spam, spam'.rindex('eggs')
10520 ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
10521 ValueError: substring not found
10522
10523 See also "index()" and "find()".
10524
10525 str.rjust(width, fillchar=' ', /)
10526
10527 Return the string right justified in a string of length *width*.
10528 Padding is done using the specified *fillchar* (default is an ASCII
10529 space). The original string is returned if *width* is less than or
10530 equal to "len(s)".
10531
10532 For example:
10533
10534 >>> 'Python'.rjust(10)
10535 ' Python'
10536 >>> 'Python'.rjust(10, '.')
10537 '....Python'
10538 >>> 'Monty Python'.rjust(10, '.')
10539 'Monty Python'
10540
10541 See also "ljust()" and "zfill()".
10542
10543 str.rpartition(sep, /)
10544
10545 Split the string at the last occurrence of *sep*, and return a
10546 3-tuple containing the part before the separator, the separator
10547 itself, and the part after the separator. If the separator is not
10548 found, return a 3-tuple containing two empty strings, followed by
10549 the string itself.
10550
10551 For example:
10552
10553 >>> 'Monty Python'.rpartition(' ')
10554 ('Monty', ' ', 'Python')
10555 >>> "Monty Python's Flying Circus".rpartition(' ')
10556 ("Monty Python's Flying", ' ', 'Circus')
10557 >>> 'Monty Python'.rpartition('-')
10558 ('', '', 'Monty Python')
10559
10560 See also "partition()".
10561
10562 str.rsplit(sep=None, maxsplit=-1)
10563
10564 Return a list of the words in the string, using *sep* as the
10565 delimiter string. If *maxsplit* is given, at most *maxsplit* splits
10566 are done, the *rightmost* ones. If *sep* is not specified or
10567 "None", any whitespace string is a separator. Except for splitting
10568 from the right, "rsplit()" behaves like "split()" which is
10569 described in detail below.
10570
10571 str.rstrip(chars=None, /)
10572
10573 Return a copy of the string with trailing characters removed. The
10574 *chars* argument is a string specifying the set of characters to be
10575 removed. If omitted or "None", the *chars* argument defaults to
10576 removing whitespace. The *chars* argument is not a suffix; rather,
10577 all combinations of its values are stripped. For example:
10578
10579 >>> ' spacious '.rstrip()
10580 ' spacious'
10581 >>> 'mississippi'.rstrip('ipz')
10582 'mississ'
10583
10584 See "removesuffix()" for a method that will remove a single suffix
10585 string rather than all of a set of characters. For example:
10586
10587 >>> 'Monty Python'.rstrip(' Python')
10588 'M'
10589 >>> 'Monty Python'.removesuffix(' Python')
10590 'Monty'
10591
10592 See also "strip()".
10593
10594 str.split(sep=None, maxsplit=-1)
10595
10596 Return a list of the words in the string, using *sep* as the
10597 delimiter string. If *maxsplit* is given, at most *maxsplit*
10598 splits are done (thus, the list will have at most "maxsplit+1"
10599 elements). If *maxsplit* is not specified or "-1", then there is
10600 no limit on the number of splits (all possible splits are made).
10601
10602 If *sep* is given, consecutive delimiters are not grouped together
10603 and are deemed to delimit empty strings (for example,
10604 "'1,,2'.split(',')" returns "['1', '', '2']"). The *sep* argument
10605 may consist of multiple characters as a single delimiter (to split
10606 with multiple delimiters, use "re.split()"). Splitting an empty
10607 string with a specified separator returns "['']".
10608
10609 For example:
10610
10611 >>> '1,2,3'.split(',')
10612 ['1', '2', '3']
10613 >>> '1,2,3'.split(',', maxsplit=1)
10614 ['1', '2,3']
10615 >>> '1,2,,3,'.split(',')
10616 ['1', '2', '', '3', '']
10617 >>> '1<>2<>3<4'.split('<>')
10618 ['1', '2', '3<4']
10619
10620 If *sep* is not specified or is "None", a different splitting
10621 algorithm is applied: runs of consecutive whitespace are regarded
10622 as a single separator, and the result will contain no empty strings
10623 at the start or end if the string has leading or trailing
10624 whitespace. Consequently, splitting an empty string or a string
10625 consisting of just whitespace with a "None" separator returns "[]".
10626
10627 For example:
10628
10629 >>> '1 2 3'.split()
10630 ['1', '2', '3']
10631 >>> '1 2 3'.split(maxsplit=1)
10632 ['1', '2 3']
10633 >>> ' 1 2 3 '.split()
10634 ['1', '2', '3']
10635
10636 If *sep* is not specified or is "None" and *maxsplit* is "0", only
10637 leading runs of consecutive whitespace are considered.
10638
10639 For example:
10640
10641 >>> "".split(None, 0)
10642 []
10643 >>> " ".split(None, 0)
10644 []
10645 >>> " foo ".split(maxsplit=0)
10646 ['foo ']
10647
10648 See also "join()" and "rsplit()".
10649
10650 str.splitlines(keepends=False)
10651
10652 Return a list of the lines in the string, breaking at line
10653 boundaries. Line breaks are not included in the resulting list
10654 unless *keepends* is given and true.
10655
10656 This method splits on the following line boundaries. In
10657 particular, the boundaries are a superset of *universal newlines*.
10658
10659 +-------------------------+-------------------------------+
10660 | Representation | Description |
10661 |=========================|===============================|
10662 | "\n" | Line Feed |
10663 +-------------------------+-------------------------------+
10664 | "\r" | Carriage Return |
10665 +-------------------------+-------------------------------+
10666 | "\r\n" | Carriage Return + Line Feed |
10667 +-------------------------+-------------------------------+
10668 | "\v" or "\x0b" | Line Tabulation |
10669 +-------------------------+-------------------------------+
10670 | "\f" or "\x0c" | Form Feed |
10671 +-------------------------+-------------------------------+
10672 | "\x1c" | File Separator |
10673 +-------------------------+-------------------------------+
10674 | "\x1d" | Group Separator |
10675 +-------------------------+-------------------------------+
10676 | "\x1e" | Record Separator |
10677 +-------------------------+-------------------------------+
10678 | "\x85" | Next Line (C1 Control Code) |
10679 +-------------------------+-------------------------------+
10680 | "\u2028" | Line Separator |
10681 +-------------------------+-------------------------------+
10682 | "\u2029" | Paragraph Separator |
10683 +-------------------------+-------------------------------+
10684
10685 Changed in version 3.2: "\v" and "\f" added to list of line
10686 boundaries.
10687
10688 For example:
10689
10690 >>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
10691 ['ab c', '', 'de fg', 'kl']
10692 >>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
10693 ['ab c\n', '\n', 'de fg\r', 'kl\r\n']
10694
10695 Unlike "split()" when a delimiter string *sep* is given, this
10696 method returns an empty list for the empty string, and a terminal
10697 line break does not result in an extra line:
10698
10699 >>> "".splitlines()
10700 []
10701 >>> "One line\n".splitlines()
10702 ['One line']
10703
10704 For comparison, "split('\n')" gives:
10705
10706 >>> ''.split('\n')
10707 ['']
10708 >>> 'Two lines\n'.split('\n')
10709 ['Two lines', '']
10710
10711 str.startswith(prefix[, start[, end]])
10712
10713 Return "True" if string starts with the *prefix*, otherwise return
10714 "False". *prefix* can also be a tuple of prefixes to look for.
10715 With optional *start*, test string beginning at that position.
10716 With optional *end*, stop comparing string at that position.
10717
10718 For example:
10719
10720 >>> 'Python'.startswith('Py')
10721 True
10722 >>> 'a tuple of prefixes'.startswith(('at', 'a'))
10723 True
10724 >>> 'Python is amazing'.startswith('is', 7)
10725 True
10726
10727 See also "endswith()" and "removeprefix()".
10728
10729 str.strip(chars=None, /)
10730
10731 Return a copy of the string with the leading and trailing
10732 characters removed. The *chars* argument is a string specifying the
10733 set of characters to be removed. If omitted or "None", the *chars*
10734 argument defaults to removing whitespace. The *chars* argument is
10735 not a prefix or suffix; rather, all combinations of its values are
10736 stripped.
10737
10738 Whitespace characters are defined by "str.isspace()".
10739
10740 For example:
10741
10742 >>> ' spacious '.strip()
10743 'spacious'
10744 >>> 'www.example.com'.strip('cmowz.')
10745 'example'
10746
10747 The outermost leading and trailing *chars* argument values are
10748 stripped from the string. Characters are removed from the leading
10749 end until reaching a string character that is not contained in the
10750 set of characters in *chars*. A similar action takes place on the
10751 trailing end.
10752
10753 For example:
10754
10755 >>> comment_string = '#....... Section 3.2.1 Issue #32 .......'
10756 >>> comment_string.strip('.#! ')
10757 'Section 3.2.1 Issue #32'
10758
10759 See also "rstrip()".
10760
10761 str.swapcase()
10762
10763 Return a copy of the string with uppercase characters converted to
10764 lowercase and vice versa. For example:
10765
10766 >>> 'Hello World'.swapcase()
10767 'hELLO wORLD'
10768
10769 Note that it is not necessarily true that "s.swapcase().swapcase()
10770 == s". For example:
10771
10772 >>> 'straße'.swapcase().swapcase()
10773 'strasse'
10774
10775 See also "str.lower()" and "str.upper()".
10776
10777 str.title()
10778
10779 Return a titlecased version of the string where words start with an
10780 uppercase character and the remaining characters are lowercase.
10781
10782 For example:
10783
10784 >>> 'Hello world'.title()
10785 'Hello World'
10786
10787 The algorithm uses a simple language-independent definition of a
10788 word as groups of consecutive letters. The definition works in
10789 many contexts but it means that apostrophes in contractions and
10790 possessives form word boundaries, which may not be the desired
10791 result:
10792
10793 >>> "they're bill's friends from the UK".title()
10794 "They'Re Bill'S Friends From The Uk"
10795
10796 The "string.capwords()" function does not have this problem, as it
10797 splits words on spaces only.
10798
10799 Alternatively, a workaround for apostrophes can be constructed
10800 using regular expressions:
10801
10802 >>> import re
10803 >>> def titlecase(s):
10804 ... return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
10805 ... lambda mo: mo.group(0).capitalize(),
10806 ... s)
10807 ...
10808 >>> titlecase("they're bill's friends.")
10809 "They're Bill's Friends."
10810
10811 See also "istitle()".
10812
10813 str.translate(table, /)
10814
10815 Return a copy of the string in which each character has been mapped
10816 through the given translation table. The table must be an object
10817 that implements indexing via "__getitem__()", typically a *mapping*
10818 or *sequence*. When indexed by a Unicode ordinal (an integer), the
10819 table object can do any of the following: return a Unicode ordinal
10820 or a string, to map the character to one or more other characters;
10821 return "None", to delete the character from the return string; or
10822 raise a "LookupError" exception, to map the character to itself.
10823
10824 You can use "str.maketrans()" to create a translation map from
10825 character-to-character mappings in different formats.
10826
10827 See also the "codecs" module for a more flexible approach to custom
10828 character mappings.
10829
10830 str.upper()
10831
10832 Return a copy of the string with all the cased characters [4]
10833 converted to uppercase. Note that "s.upper().isupper()" might be
10834 "False" if "s" contains uncased characters or if the Unicode
10835 category of the resulting character(s) is not “Lu” (Letter,
10836 uppercase), but e.g. “Lt” (Letter, titlecase).
10837
10838 The uppercasing algorithm used is described in section 3.13
10839 ‘Default Case Folding’ of the Unicode Standard.
10840
10841 str.zfill(width, /)
10842
10843 Return a copy of the string left filled with ASCII "'0'" digits to
10844 make a string of length *width*. A leading sign prefix
10845 ("'+'"/"'-'") is handled by inserting the padding *after* the sign
10846 character rather than before. The original string is returned if
10847 *width* is less than or equal to "len(s)".
10848
10849 For example:
10850
10851 >>> "42".zfill(5)
10852 '00042'
10853 >>> "-42".zfill(5)
10854 '-0042'
10855
10856 See also "rjust()".
10857 ''',
10858 'strings': '''String and Bytes literals
10859 *************************
10860
10861 String literals are text enclosed in single quotes ("'") or double
10862 quotes ("""). For example:
10863
10864 "spam"
10865 'eggs'
10866
10867 The quote used to start the literal also terminates it, so a string
10868 literal can only contain the other quote (except with escape
10869 sequences, see below). For example:
10870
10871 'Say "Hello", please.'
10872 "Don't do that!"
10873
10874 Except for this limitation, the choice of quote character ("'" or """)
10875 does not affect how the literal is parsed.
10876
10877 Inside a string literal, the backslash ("\\") character introduces an
10878 *escape sequence*, which has special meaning depending on the
10879 character after the backslash. For example, "\\"" denotes the double
10880 quote character, and does *not* end the string:
10881
10882 >>> print("Say \\"Hello\\" to everyone!")
10883 Say "Hello" to everyone!
10884
10885 See escape sequences below for a full list of such sequences, and more
10886 details.
10887
10888
10889 Triple-quoted strings
10890 =====================
10891
10892 Strings can also be enclosed in matching groups of three single or
10893 double quotes. These are generally referred to as *triple-quoted
10894 strings*:
10895
10896 """This is a triple-quoted string."""
10897
10898 In triple-quoted literals, unescaped quotes are allowed (and are
10899 retained), except that three unescaped quotes in a row terminate the
10900 literal, if they are of the same kind ("'" or """) used at the start:
10901
10902 """This string has "quotes" inside."""
10903
10904 Unescaped newlines are also allowed and retained:
10905
10906 \'\'\'This triple-quoted string
10907 continues on the next line.\'\'\'
10908
10909
10910 String prefixes
10911 ===============
10912
10913 String literals can have an optional *prefix* that influences how the
10914 content of the literal is parsed, for example:
10915
10916 b"data"
10917 f'{result=}'
10918
10919 The allowed prefixes are:
10920
10921 * "b": Bytes literal
10922
10923 * "r": Raw string
10924
10925 * "f": Formatted string literal (“f-string”)
10926
10927 * "t": Template string literal (“t-string”)
10928
10929 * "u": No effect (allowed for backwards compatibility)
10930
10931 See the linked sections for details on each type.
10932
10933 Prefixes are case-insensitive (for example, ‘"B"’ works the same as
10934 ‘"b"’). The ‘"r"’ prefix can be combined with ‘"f"’, ‘"t"’ or ‘"b"’,
10935 so ‘"fr"’, ‘"rf"’, ‘"tr"’, ‘"rt"’, ‘"br"’, and ‘"rb"’ are also valid
10936 prefixes.
10937
10938 Added in version 3.3: The "'rb'" prefix of raw bytes literals has been
10939 added as a synonym of "'br'".Support for the unicode legacy literal
10940 ("u'value'") was reintroduced to simplify the maintenance of dual
10941 Python 2.x and 3.x codebases. See **PEP 414** for more information.
10942
10943
10944 Formal grammar
10945 ==============
10946
10947 String literals, except “f-strings” and “t-strings”, are described by
10948 the following lexical definitions.
10949
10950 These definitions use negative lookaheads ("!") to indicate that an
10951 ending quote ends the literal.
10952
10953 STRING: [stringprefix] (stringcontent)
10954 stringprefix: <("r" | "u" | "b" | "br" | "rb"), case-insensitive>
10955 stringcontent:
10956 | "\'\'\'" ( !"\'\'\'" longstringitem)* "\'\'\'"
10957 | '"""' ( !'"""' longstringitem)* '"""'
10958 | "'" ( !"'" stringitem)* "'"
10959 | '"' ( !'"' stringitem)* '"'
10960 stringitem: stringchar | stringescapeseq
10961 stringchar: <any source_character, except backslash and newline>
10962 longstringitem: stringitem | newline
10963 stringescapeseq: "\\" <any source_character>
10964
10965 Note that as in all lexical definitions, whitespace is significant. In
10966 particular, the prefix (if any) must be immediately followed by the
10967 starting quote.
10968
10969
10970 Escape sequences
10971 ================
10972
10973 Unless an ‘"r"’ or ‘"R"’ prefix is present, escape sequences in string
10974 and bytes literals are interpreted according to rules similar to those
10975 used by Standard C. The recognized escape sequences are:
10976
10977 +----------------------------------------------------+----------------------------------------------------+
10978 | Escape Sequence | Meaning |
10979 |====================================================|====================================================|
10980 | "\\"<newline> | Ignored end of line |
10981 +----------------------------------------------------+----------------------------------------------------+
10982 | "\\\\" | Backslash |
10983 +----------------------------------------------------+----------------------------------------------------+
10984 | "\\'" | Single quote |
10985 +----------------------------------------------------+----------------------------------------------------+
10986 | "\\"" | Double quote |
10987 +----------------------------------------------------+----------------------------------------------------+
10988 | "\\a" | ASCII Bell (BEL) |
10989 +----------------------------------------------------+----------------------------------------------------+
10990 | "\\b" | ASCII Backspace (BS) |
10991 +----------------------------------------------------+----------------------------------------------------+
10992 | "\\f" | ASCII Formfeed (FF) |
10993 +----------------------------------------------------+----------------------------------------------------+
10994 | "\\n" | ASCII Linefeed (LF) |
10995 +----------------------------------------------------+----------------------------------------------------+
10996 | "\\r" | ASCII Carriage Return (CR) |
10997 +----------------------------------------------------+----------------------------------------------------+
10998 | "\\t" | ASCII Horizontal Tab (TAB) |
10999 +----------------------------------------------------+----------------------------------------------------+
11000 | "\\v" | ASCII Vertical Tab (VT) |
11001 +----------------------------------------------------+----------------------------------------------------+
11002 | "\\*ooo*" | Octal character |
11003 +----------------------------------------------------+----------------------------------------------------+
11004 | "\\x*hh*" | Hexadecimal character |
11005 +----------------------------------------------------+----------------------------------------------------+
11006 | "\\N{*name*}" | Named Unicode character |
11007 +----------------------------------------------------+----------------------------------------------------+
11008 | "\\u*xxxx*" | Hexadecimal Unicode character |
11009 +----------------------------------------------------+----------------------------------------------------+
11010 | "\\U*xxxxxxxx*" | Hexadecimal Unicode character |
11011 +----------------------------------------------------+----------------------------------------------------+
11012
11013
11014 Ignored end of line
11015 -------------------
11016
11017 A backslash can be added at the end of a line to ignore the newline:
11018
11019 >>> 'This string will not include \\
11020 ... backslashes or newline characters.'
11021 'This string will not include backslashes or newline characters.'
11022
11023 The same result can be achieved using triple-quoted strings, or
11024 parentheses and string literal concatenation.
11025
11026
11027 Escaped characters
11028 ------------------
11029
11030 To include a backslash in a non-raw Python string literal, it must be
11031 doubled. The "\\\\" escape sequence denotes a single backslash
11032 character:
11033
11034 >>> print('C:\\\\Program Files')
11035 C:\\Program Files
11036
11037 Similarly, the "\\'" and "\\"" sequences denote the single and double
11038 quote character, respectively:
11039
11040 >>> print('\\' and \\"')
11041 ' and "
11042
11043
11044 Octal character
11045 ---------------
11046
11047 The sequence "\\*ooo*" denotes a *character* with the octal (base 8)
11048 value *ooo*:
11049
11050 >>> '\\120'
11051 'P'
11052
11053 Up to three octal digits (0 through 7) are accepted.
11054
11055 In a bytes literal, *character* means a *byte* with the given value.
11056 In a string literal, it means a Unicode character with the given
11057 value.
11058
11059 Changed in version 3.11: Octal escapes with value larger than "0o377"
11060 (255) produce a "DeprecationWarning".
11061
11062 Changed in version 3.12: Octal escapes with value larger than "0o377"
11063 (255) produce a "SyntaxWarning". In a future Python version they will
11064 raise a "SyntaxError".
11065
11066
11067 Hexadecimal character
11068 ---------------------
11069
11070 The sequence "\\x*hh*" denotes a *character* with the hex (base 16)
11071 value *hh*:
11072
11073 >>> '\\x50'
11074 'P'
11075
11076 Unlike in Standard C, exactly two hex digits are required.
11077
11078 In a bytes literal, *character* means a *byte* with the given value.
11079 In a string literal, it means a Unicode character with the given
11080 value.
11081
11082
11083 Named Unicode character
11084 -----------------------
11085
11086 The sequence "\\N{*name*}" denotes a Unicode character with the given
11087 *name*:
11088
11089 >>> '\\N{LATIN CAPITAL LETTER P}'
11090 'P'
11091 >>> '\\N{SNAKE}'
11092 '🐍'
11093
11094 This sequence cannot appear in bytes literals.
11095
11096 Changed in version 3.3: Support for name aliases has been added.
11097
11098
11099 Hexadecimal Unicode characters
11100 ------------------------------
11101
11102 These sequences "\\u*xxxx*" and "\\U*xxxxxxxx*" denote the Unicode
11103 character with the given hex (base 16) value. Exactly four digits are
11104 required for "\\u"; exactly eight digits are required for "\\U". The
11105 latter can encode any Unicode character.
11106
11107 >>> '\\u1234'
11108 'ሴ'
11109 >>> '\\U0001f40d'
11110 '🐍'
11111
11112 These sequences cannot appear in bytes literals.
11113
11114
11115 Unrecognized escape sequences
11116 -----------------------------
11117
11118 Unlike in Standard C, all unrecognized escape sequences are left in
11119 the string unchanged, that is, *the backslash is left in the result*:
11120
11121 >>> print('\\q')
11122 \\q
11123 >>> list('\\q')
11124 ['\\\\', 'q']
11125
11126 Note that for bytes literals, the escape sequences only recognized in
11127 string literals ("\\N...", "\\u...", "\\U...") fall into the category of
11128 unrecognized escapes.
11129
11130 Changed in version 3.6: Unrecognized escape sequences produce a
11131 "DeprecationWarning".
11132
11133 Changed in version 3.12: Unrecognized escape sequences produce a
11134 "SyntaxWarning". In a future Python version they will raise a
11135 "SyntaxError".
11136
11137
11138 Bytes literals
11139 ==============
11140
11141 *Bytes literals* are always prefixed with ‘"b"’ or ‘"B"’; they produce
11142 an instance of the "bytes" type instead of the "str" type. They may
11143 only contain ASCII characters; bytes with a numeric value of 128 or
11144 greater must be expressed with escape sequences (typically Hexadecimal
11145 character or Octal character):
11146
11147 >>> b'\\x89PNG\\r\\n\\x1a\\n'
11148 b'\\x89PNG\\r\\n\\x1a\\n'
11149 >>> list(b'\\x89PNG\\r\\n\\x1a\\n')
11150 [137, 80, 78, 71, 13, 10, 26, 10]
11151
11152 Similarly, a zero byte must be expressed using an escape sequence
11153 (typically "\\0" or "\\x00").
11154
11155
11156 Raw string literals
11157 ===================
11158
11159 Both string and bytes literals may optionally be prefixed with a
11160 letter ‘"r"’ or ‘"R"’; such constructs are called *raw string
11161 literals* and *raw bytes literals* respectively and treat backslashes
11162 as literal characters. As a result, in raw string literals, escape
11163 sequences are not treated specially:
11164
11165 >>> r'\\d{4}-\\d{2}-\\d{2}'
11166 '\\\\d{4}-\\\\d{2}-\\\\d{2}'
11167
11168 Even in a raw literal, quotes can be escaped with a backslash, but the
11169 backslash remains in the result; for example, "r"\\""" is a valid
11170 string literal consisting of two characters: a backslash and a double
11171 quote; "r"\\"" is not a valid string literal (even a raw string cannot
11172 end in an odd number of backslashes). Specifically, *a raw literal
11173 cannot end in a single backslash* (since the backslash would escape
11174 the following quote character). Note also that a single backslash
11175 followed by a newline is interpreted as those two characters as part
11176 of the literal, *not* as a line continuation.
11177
11178
11179 f-strings
11180 =========
11181
11182 Added in version 3.6.
11183
11184 Changed in version 3.7: The "await" and "async for" can be used in
11185 expressions within f-strings.
11186
11187 Changed in version 3.8: Added the debug specifier ("=")
11188
11189 Changed in version 3.12: Many restrictions on expressions within
11190 f-strings have been removed. Notably, nested strings, comments, and
11191 backslashes are now permitted.
11192
11193 A *formatted string literal* or *f-string* is a string literal that is
11194 prefixed with ‘"f"’ or ‘"F"’. Unlike other string literals, f-strings
11195 do not have a constant value. They may contain *replacement fields*
11196 delimited by curly braces "{}". Replacement fields contain expressions
11197 which are evaluated at run time. For example:
11198
11199 >>> who = 'nobody'
11200 >>> nationality = 'Spanish'
11201 >>> f'{who.title()} expects the {nationality} Inquisition!'
11202 'Nobody expects the Spanish Inquisition!'
11203
11204 Any doubled curly braces ("{{" or "}}") outside replacement fields are
11205 replaced with the corresponding single curly brace:
11206
11207 >>> print(f'{{...}}')
11208 {...}
11209
11210 Other characters outside replacement fields are treated like in
11211 ordinary string literals. This means that escape sequences are decoded
11212 (except when a literal is also marked as a raw string), and newlines
11213 are possible in triple-quoted f-strings:
11214
11215 >>> name = 'Galahad'
11216 >>> favorite_color = 'blue'
11217 >>> print(f'{name}:\\t{favorite_color}')
11218 Galahad: blue
11219 >>> print(rf"C:\\Users\\{name}")
11220 C:\\Users\\Galahad
11221 >>> print(f\'\'\'Three shall be the number of the counting
11222 ... and the number of the counting shall be three.\'\'\')
11223 Three shall be the number of the counting
11224 and the number of the counting shall be three.
11225
11226 Expressions in formatted string literals are treated like regular
11227 Python expressions. Each expression is evaluated in the context where
11228 the formatted string literal appears, in order from left to right. An
11229 empty expression is not allowed, and both "lambda" and assignment
11230 expressions ":=" must be surrounded by explicit parentheses:
11231
11232 >>> f'{(half := 1/2)}, {half * 42}'
11233 '0.5, 21.0'
11234
11235 Reusing the outer f-string quoting type inside a replacement field is
11236 permitted:
11237
11238 >>> a = dict(x=2)
11239 >>> f"abc {a["x"]} def"
11240 'abc 2 def'
11241
11242 Backslashes are also allowed in replacement fields and are evaluated
11243 the same way as in any other context:
11244
11245 >>> a = ["a", "b", "c"]
11246 >>> print(f"List a contains:\\n{"\\n".join(a)}")
11247 List a contains:
11248 a
11249 b
11250 c
11251
11252 It is possible to nest f-strings:
11253
11254 >>> name = 'world'
11255 >>> f'Repeated:{f' hello {name}' * 3}'
11256 'Repeated: hello world hello world hello world'
11257
11258 Portable Python programs should not use more than 5 levels of nesting.
11259
11260 **CPython implementation detail:** CPython does not limit nesting of
11261 f-strings.
11262
11263 Replacement expressions can contain newlines in both single-quoted and
11264 triple-quoted f-strings and they can contain comments. Everything that
11265 comes after a "#" inside a replacement field is a comment (even
11266 closing braces and quotes). This means that replacement fields with
11267 comments must be closed in a different line:
11268
11269 >>> a = 2
11270 >>> f"abc{a # This comment }" continues until the end of the line
11271 ... + 3}"
11272 'abc5'
11273
11274 After the expression, replacement fields may optionally contain:
11275
11276 * a *debug specifier* – an equal sign ("="), optionally surrounded by
11277 whitespace on one or both sides;
11278
11279 * a *conversion specifier* – "!s", "!r" or "!a"; and/or
11280
11281 * a *format specifier* prefixed with a colon (":").
11282
11283 See the Standard Library section on f-strings for details on how these
11284 fields are evaluated.
11285
11286 As that section explains, *format specifiers* are passed as the second
11287 argument to the "format()" function to format a replacement field
11288 value. For example, they can be used to specify a field width and
11289 padding characters using the Format Specification Mini-Language:
11290
11291 >>> number = 14.3
11292 >>> f'{number:20.7f}'
11293 ' 14.3000000'
11294
11295 Top-level format specifiers may include nested replacement fields:
11296
11297 >>> field_size = 20
11298 >>> precision = 7
11299 >>> f'{number:{field_size}.{precision}f}'
11300 ' 14.3000000'
11301
11302 These nested fields may include their own conversion fields and format
11303 specifiers:
11304
11305 >>> number = 3
11306 >>> f'{number:{field_size}}'
11307 ' 3'
11308 >>> f'{number:{field_size:05}}'
11309 '00000000000000000003'
11310
11311 However, these nested fields may not include more deeply nested
11312 replacement fields.
11313
11314 Formatted string literals cannot be used as *docstrings*, even if they
11315 do not include expressions:
11316
11317 >>> def foo():
11318 ... f"Not a docstring"
11319 ...
11320 >>> print(foo.__doc__)
11321 None
11322
11323 See also:
11324
11325 * **PEP 498** – Literal String Interpolation
11326
11327 * **PEP 701** – Syntactic formalization of f-strings
11328
11329 * "str.format()", which uses a related format string mechanism.
11330
11331
11332 t-strings
11333 =========
11334
11335 Added in version 3.14.
11336
11337 A *template string literal* or *t-string* is a string literal that is
11338 prefixed with ‘"t"’ or ‘"T"’. These strings follow the same syntax
11339 rules as formatted string literals. For differences in evaluation
11340 rules, see the Standard Library section on t-strings
11341
11342
11343 Formal grammar for f-strings
11344 ============================
11345
11346 F-strings are handled partly by the *lexical analyzer*, which produces
11347 the tokens "FSTRING_START", "FSTRING_MIDDLE" and "FSTRING_END", and
11348 partly by the parser, which handles expressions in the replacement
11349 field. The exact way the work is split is a CPython implementation
11350 detail.
11351
11352 Correspondingly, the f-string grammar is a mix of lexical and
11353 syntactic definitions.
11354
11355 Whitespace is significant in these situations:
11356
11357 * There may be no whitespace in "FSTRING_START" (between the prefix
11358 and quote).
11359
11360 * Whitespace in "FSTRING_MIDDLE" is part of the literal string
11361 contents.
11362
11363 * In "fstring_replacement_field", if "f_debug_specifier" is present,
11364 all whitespace after the opening brace until the
11365 "f_debug_specifier", as well as whitespace immediately following
11366 "f_debug_specifier", is retained as part of the expression.
11367
11368 **CPython implementation detail:** The expression is not handled in
11369 the tokenization phase; it is retrieved from the source code using
11370 locations of the "{" token and the token after "=".
11371
11372 The "FSTRING_MIDDLE" definition uses negative lookaheads ("!") to
11373 indicate special characters (backslash, newline, "{", "}") and
11374 sequences ("f_quote").
11375
11376 fstring: FSTRING_START fstring_middle* FSTRING_END
11377
11378 FSTRING_START: fstringprefix ("'" | '"' | "\'\'\'" | '"""')
11379 FSTRING_END: f_quote
11380 fstringprefix: <("f" | "fr" | "rf"), case-insensitive>
11381 f_debug_specifier: '='
11382 f_quote: <the quote character(s) used in FSTRING_START>
11383
11384 fstring_middle:
11385 | fstring_replacement_field
11386 | FSTRING_MIDDLE
11387 FSTRING_MIDDLE:
11388 | (!"\\" !newline !'{' !'}' !f_quote) source_character
11389 | stringescapeseq
11390 | "{{"
11391 | "}}"
11392 | <newline, in triple-quoted f-strings only>
11393 fstring_replacement_field:
11394 | '{' f_expression [f_debug_specifier] [fstring_conversion]
11395 [fstring_full_format_spec] '}'
11396 fstring_conversion:
11397 | "!" ("s" | "r" | "a")
11398 fstring_full_format_spec:
11399 | ':' fstring_format_spec*
11400 fstring_format_spec:
11401 | FSTRING_MIDDLE
11402 | fstring_replacement_field
11403 f_expression:
11404 | ','.(conditional_expression | "*" or_expr)+ [","]
11405 | yield_expression
11406
11407 Note:
11408
11409 In the above grammar snippet, the "f_quote" and "FSTRING_MIDDLE"
11410 rules are context-sensitive – they depend on the contents of
11411 "FSTRING_START" of the nearest enclosing "fstring".Constructing a
11412 more traditional formal grammar from this template is left as an
11413 exercise for the reader.
11414
11415 The grammar for t-strings is identical to the one for f-strings, with
11416 *t* instead of *f* at the beginning of rule and token names and in the
11417 prefix.
11418
11419 tstring: TSTRING_START tstring_middle* TSTRING_END
11420
11421 <rest of the t-string grammar is omitted; see above>
11422 ''',
11423 'subscriptions': r'''Subscriptions and slicings
11424 **************************
11425
11426 The *subscription* syntax is usually used for selecting an element
11427 from a container – for example, to get a value from a "dict":
11428
11429 >>> digits_by_name = {'one': 1, 'two': 2}
11430 >>> digits_by_name['two'] # Subscripting a dictionary using the key 'two'
11431 2
11432
11433 In the subscription syntax, the object being subscribed – a primary –
11434 is followed by a *subscript* in square brackets. In the simplest case,
11435 the subscript is a single expression.
11436
11437 Depending on the type of the object being subscribed, the subscript is
11438 sometimes called a *key* (for mappings), *index* (for sequences), or
11439 *type argument* (for *generic types*). Syntactically, these are all
11440 equivalent:
11441
11442 >>> colors = ['red', 'blue', 'green', 'black']
11443 >>> colors[3] # Subscripting a list using the index 3
11444 'black'
11445
11446 >>> list[str] # Parameterizing the list type using the type argument str
11447 list[str]
11448
11449 At runtime, the interpreter will evaluate the primary and the
11450 subscript, and call the primary’s "__getitem__()" or
11451 "__class_getitem__()" *special method* with the subscript as argument.
11452 For more details on which of these methods is called, see
11453 __class_getitem__ versus __getitem__.
11454
11455 To show how subscription works, we can define a custom object that
11456 implements "__getitem__()" and prints out the value of the subscript:
11457
11458 >>> class SubscriptionDemo:
11459 ... def __getitem__(self, key):
11460 ... print(f'subscripted with: {key!r}')
11461 ...
11462 >>> demo = SubscriptionDemo()
11463 >>> demo[1]
11464 subscripted with: 1
11465 >>> demo['a' * 3]
11466 subscripted with: 'aaa'
11467
11468 See "__getitem__()" documentation for how built-in types handle
11469 subscription.
11470
11471 Subscriptions may also be used as targets in assignment or deletion
11472 statements. In these cases, the interpreter will call the subscripted
11473 object’s "__setitem__()" or "__delitem__()" *special method*,
11474 respectively, instead of "__getitem__()".
11475
11476 >>> colors = ['red', 'blue', 'green', 'black']
11477 >>> colors[3] = 'white' # Setting item at index
11478 >>> colors
11479 ['red', 'blue', 'green', 'white']
11480 >>> del colors[3] # Deleting item at index 3
11481 >>> colors
11482 ['red', 'blue', 'green']
11483
11484 All advanced forms of *subscript* documented in the following sections
11485 are also usable for assignment and deletion.
11486
11487
11488 Slicings
11489 ========
11490
11491 A more advanced form of subscription, *slicing*, is commonly used to
11492 extract a portion of a sequence. In this form, the subscript is a
11493 *slice*: up to three expressions separated by colons. Any of the
11494 expressions may be omitted, but a slice must contain at least one
11495 colon:
11496
11497 >>> number_names = ['zero', 'one', 'two', 'three', 'four', 'five']
11498 >>> number_names[1:3]
11499 ['one', 'two']
11500 >>> number_names[1:]
11501 ['one', 'two', 'three', 'four', 'five']
11502 >>> number_names[:3]
11503 ['zero', 'one', 'two']
11504 >>> number_names[:]
11505 ['zero', 'one', 'two', 'three', 'four', 'five']
11506 >>> number_names[::2]
11507 ['zero', 'two', 'four']
11508 >>> number_names[:-3]
11509 ['zero', 'one', 'two']
11510 >>> del number_names[4:]
11511 >>> number_names
11512 ['zero', 'one', 'two', 'three']
11513
11514 When a slice is evaluated, the interpreter constructs a "slice" object
11515 whose "start", "stop" and "step" attributes, respectively, are the
11516 results of the expressions between the colons. Any missing expression
11517 evaluates to "None". This "slice" object is then passed to the
11518 "__getitem__()" or "__class_getitem__()" *special method*, as above.
11519
11520 # continuing with the SubscriptionDemo instance defined above:
11521 >>> demo[2:3]
11522 subscripted with: slice(2, 3, None)
11523 >>> demo[::'spam']
11524 subscripted with: slice(None, None, 'spam')
11525
11526
11527 Comma-separated subscripts
11528 ==========================
11529
11530 The subscript can also be given as two or more comma-separated
11531 expressions or slices:
11532
11533 # continuing with the SubscriptionDemo instance defined above:
11534 >>> demo[1, 2, 3]
11535 subscripted with: (1, 2, 3)
11536 >>> demo[1:2, 3]
11537 subscripted with: (slice(1, 2, None), 3)
11538
11539 This form is commonly used with numerical libraries for slicing multi-
11540 dimensional data. In this case, the interpreter constructs a "tuple"
11541 of the results of the expressions or slices, and passes this tuple to
11542 the "__getitem__()" or "__class_getitem__()" *special method*, as
11543 above.
11544
11545 The subscript may also be given as a single expression or slice
11546 followed by a comma, to specify a one-element tuple:
11547
11548 >>> demo['spam',]
11549 subscripted with: ('spam',)
11550
11551
11552 “Starred” subscriptions
11553 =======================
11554
11555 Added in version 3.11: Expressions in *tuple_slices* may be starred.
11556 See **PEP 646**.
11557
11558 The subscript can also contain a starred expression. In this case, the
11559 interpreter unpacks the result into a tuple, and passes this tuple to
11560 "__getitem__()" or "__class_getitem__()":
11561
11562 # continuing with the SubscriptionDemo instance defined above:
11563 >>> demo[*range(10)]
11564 subscripted with: (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
11565
11566 Starred expressions may be combined with comma-separated expressions
11567 and slices:
11568
11569 >>> demo['a', 'b', *range(3), 'c']
11570 subscripted with: ('a', 'b', 0, 1, 2, 'c')
11571
11572
11573 Formal subscription grammar
11574 ===========================
11575
11576 subscription: primary '[' subscript ']'
11577 subscript: single_subscript | tuple_subscript
11578 single_subscript: proper_slice | assignment_expression
11579 proper_slice: [expression] ":" [expression] [ ":" [expression] ]
11580 tuple_subscript: ','.(single_subscript | starred_expression)+ [',']
11581
11582 Recall that the "|" operator denotes ordered choice. Specifically, in
11583 "subscript", if both alternatives would match, the first
11584 ("single_subscript") has priority.
11585 ''',
11586 'truth': r'''Truth Value Testing
11587 *******************
11588
11589 Any object can be tested for truth value, for use in an "if" or
11590 "while" condition or as operand of the Boolean operations below.
11591
11592 By default, an object is considered true unless its class defines
11593 either a "__bool__()" method that returns "False" or a "__len__()"
11594 method that returns zero, when called with the object. [1] If one of
11595 the methods raises an exception when called, the exception is
11596 propagated and the object does not have a truth value (for example,
11597 "NotImplemented"). Here are most of the built-in objects considered
11598 false:
11599
11600 * constants defined to be false: "None" and "False"
11601
11602 * zero of any numeric type: "0", "0.0", "0j", "Decimal(0)",
11603 "Fraction(0, 1)"
11604
11605 * empty sequences and collections: "''", "()", "[]", "{}", "set()",
11606 "range(0)"
11607
11608 Operations and built-in functions that have a Boolean result always
11609 return "0" or "False" for false and "1" or "True" for true, unless
11610 otherwise stated. (Important exception: the Boolean operations "or"
11611 and "and" always return one of their operands.)
11612 ''',
11613 'try': r'''The "try" statement
11614 *******************
11615
11616 The "try" statement specifies exception handlers and/or cleanup code
11617 for a group of statements:
11618
11619 try_stmt: try1_stmt | try2_stmt | try3_stmt
11620 try1_stmt: "try" ":" suite
11621 ("except" [expression ["as" identifier]] ":" suite)+
11622 ["else" ":" suite]
11623 ["finally" ":" suite]
11624 try2_stmt: "try" ":" suite
11625 ("except" "*" expression ["as" identifier] ":" suite)+
11626 ["else" ":" suite]
11627 ["finally" ":" suite]
11628 try3_stmt: "try" ":" suite
11629 "finally" ":" suite
11630
11631 Additional information on exceptions can be found in section
11632 Exceptions, and information on using the "raise" statement to generate
11633 exceptions may be found in section The raise statement.
11634
11635 Changed in version 3.14: Support for optionally dropping grouping
11636 parentheses when using multiple exception types. See **PEP 758**.
11637
11638
11639 "except" clause
11640 ===============
11641
11642 The "except" clause(s) specify one or more exception handlers. When no
11643 exception occurs in the "try" clause, no exception handler is
11644 executed. When an exception occurs in the "try" suite, a search for an
11645 exception handler is started. This search inspects the "except"
11646 clauses in turn until one is found that matches the exception. An
11647 expression-less "except" clause, if present, must be last; it matches
11648 any exception.
11649
11650 For an "except" clause with an expression, the expression must
11651 evaluate to an exception type or a tuple of exception types.
11652 Parentheses can be dropped if multiple exception types are provided
11653 and the "as" clause is not used. The raised exception matches an
11654 "except" clause whose expression evaluates to the class or a *non-
11655 virtual base class* of the exception object, or to a tuple that
11656 contains such a class.
11657
11658 If no "except" clause matches the exception, the search for an
11659 exception handler continues in the surrounding code and on the
11660 invocation stack. [1]
11661
11662 If the evaluation of an expression in the header of an "except" clause
11663 raises an exception, the original search for a handler is canceled and
11664 a search starts for the new exception in the surrounding code and on
11665 the call stack (it is treated as if the entire "try" statement raised
11666 the exception).
11667
11668 When a matching "except" clause is found, the exception is assigned to
11669 the target specified after the "as" keyword in that "except" clause,
11670 if present, and the "except" clause’s suite is executed. All "except"
11671 clauses must have an executable block. When the end of this block is
11672 reached, execution continues normally after the entire "try"
11673 statement. (This means that if two nested handlers exist for the same
11674 exception, and the exception occurs in the "try" clause of the inner
11675 handler, the outer handler will not handle the exception.)
11676
11677 When an exception has been assigned using "as target", it is cleared
11678 at the end of the "except" clause. This is as if
11679
11680 except E as N:
11681 foo
11682
11683 was translated to
11684
11685 except E as N:
11686 try:
11687 foo
11688 finally:
11689 del N
11690
11691 This means the exception must be assigned to a different name to be
11692 able to refer to it after the "except" clause. Exceptions are cleared
11693 because with the traceback attached to them, they form a reference
11694 cycle with the stack frame, keeping all locals in that frame alive
11695 until the next garbage collection occurs.
11696
11697 Before an "except" clause’s suite is executed, the exception is stored
11698 in the "sys" module, where it can be accessed from within the body of
11699 the "except" clause by calling "sys.exception()". When leaving an
11700 exception handler, the exception stored in the "sys" module is reset
11701 to its previous value:
11702
11703 >>> print(sys.exception())
11704 None
11705 >>> try:
11706 ... raise TypeError
11707 ... except:
11708 ... print(repr(sys.exception()))
11709 ... try:
11710 ... raise ValueError
11711 ... except:
11712 ... print(repr(sys.exception()))
11713 ... print(repr(sys.exception()))
11714 ...
11715 TypeError()
11716 ValueError()
11717 TypeError()
11718 >>> print(sys.exception())
11719 None
11720
11721
11722 "except*" clause
11723 ================
11724
11725 The "except*" clause(s) specify one or more handlers for groups of
11726 exceptions ("BaseExceptionGroup" instances). A "try" statement can
11727 have either "except" or "except*" clauses, but not both. The exception
11728 type for matching is mandatory in the case of "except*", so "except*:"
11729 is a syntax error. The type is interpreted as in the case of "except",
11730 but matching is performed on the exceptions contained in the group
11731 that is being handled. An "TypeError" is raised if a matching type is
11732 a subclass of "BaseExceptionGroup", because that would have ambiguous
11733 semantics.
11734
11735 When an exception group is raised in the try block, each "except*"
11736 clause splits (see "split()") it into the subgroups of matching and
11737 non-matching exceptions. If the matching subgroup is not empty, it
11738 becomes the handled exception (the value returned from
11739 "sys.exception()") and assigned to the target of the "except*" clause
11740 (if there is one). Then, the body of the "except*" clause executes. If
11741 the non-matching subgroup is not empty, it is processed by the next
11742 "except*" in the same manner. This continues until all exceptions in
11743 the group have been matched, or the last "except*" clause has run.
11744
11745 After all "except*" clauses execute, the group of unhandled exceptions
11746 is merged with any exceptions that were raised or re-raised from
11747 within "except*" clauses. This merged exception group propagates on.:
11748
11749 >>> try:
11750 ... raise ExceptionGroup("eg",
11751 ... [ValueError(1), TypeError(2), OSError(3), OSError(4)])
11752 ... except* TypeError as e:
11753 ... print(f'caught {type(e)} with nested {e.exceptions}')
11754 ... except* OSError as e:
11755 ... print(f'caught {type(e)} with nested {e.exceptions}')
11756 ...
11757 caught <class 'ExceptionGroup'> with nested (TypeError(2),)
11758 caught <class 'ExceptionGroup'> with nested (OSError(3), OSError(4))
11759 + Exception Group Traceback (most recent call last):
11760 | File "<doctest default[0]>", line 2, in <module>
11761 | raise ExceptionGroup("eg",
11762 | [ValueError(1), TypeError(2), OSError(3), OSError(4)])
11763 | ExceptionGroup: eg (1 sub-exception)
11764 +-+---------------- 1 ----------------
11765 | ValueError: 1
11766 +------------------------------------
11767
11768 If the exception raised from the "try" block is not an exception group
11769 and its type matches one of the "except*" clauses, it is caught and
11770 wrapped by an exception group with an empty message string. This
11771 ensures that the type of the target "e" is consistently
11772 "BaseExceptionGroup":
11773
11774 >>> try:
11775 ... raise BlockingIOError
11776 ... except* BlockingIOError as e:
11777 ... print(repr(e))
11778 ...
11779 ExceptionGroup('', (BlockingIOError(),))
11780
11781 "break", "continue" and "return" cannot appear in an "except*" clause.
11782
11783
11784 "else" clause
11785 =============
11786
11787 The optional "else" clause is executed if the control flow leaves the
11788 "try" suite, no exception was raised, and no "return", "continue", or
11789 "break" statement was executed. Exceptions in the "else" clause are
11790 not handled by the preceding "except" clauses.
11791
11792
11793 "finally" clause
11794 ================
11795
11796 If "finally" is present, it specifies a ‘cleanup’ handler. The "try"
11797 clause is executed, including any "except" and "else" clauses. If an
11798 exception occurs in any of the clauses and is not handled, the
11799 exception is temporarily saved. The "finally" clause is executed. If
11800 there is a saved exception it is re-raised at the end of the "finally"
11801 clause. If the "finally" clause raises another exception, the saved
11802 exception is set as the context of the new exception. If the "finally"
11803 clause executes a "return", "break" or "continue" statement, the saved
11804 exception is discarded. For example, this function returns 42.
11805
11806 def f():
11807 try:
11808 1/0
11809 finally:
11810 return 42
11811
11812 The exception information is not available to the program during
11813 execution of the "finally" clause.
11814
11815 When a "return", "break" or "continue" statement is executed in the
11816 "try" suite of a "try"…"finally" statement, the "finally" clause is
11817 also executed ‘on the way out.’
11818
11819 The return value of a function is determined by the last "return"
11820 statement executed. Since the "finally" clause always executes, a
11821 "return" statement executed in the "finally" clause will always be the
11822 last one executed. The following function returns ‘finally’.
11823
11824 def foo():
11825 try:
11826 return 'try'
11827 finally:
11828 return 'finally'
11829
11830 Changed in version 3.8: Prior to Python 3.8, a "continue" statement
11831 was illegal in the "finally" clause due to a problem with the
11832 implementation.
11833
11834 Changed in version 3.14: The compiler emits a "SyntaxWarning" when a
11835 "return", "break" or "continue" appears in a "finally" block (see
11836 **PEP 765**).
11837 ''',
11838 'types': r'''The standard type hierarchy
11839 ***************************
11840
11841 Below is a list of the types that are built into Python. Extension
11842 modules (written in C, Java, or other languages, depending on the
11843 implementation) can define additional types. Future versions of
11844 Python may add types to the type hierarchy (e.g., rational numbers,
11845 efficiently stored arrays of integers, etc.), although such additions
11846 will often be provided via the standard library instead.
11847
11848 Some of the type descriptions below contain a paragraph listing
11849 ‘special attributes.’ These are attributes that provide access to the
11850 implementation and are not intended for general use. Their definition
11851 may change in the future.
11852
11853
11854 None
11855 ====
11856
11857 This type has a single value. There is a single object with this
11858 value. This object is accessed through the built-in name "None". It is
11859 used to signify the absence of a value in many situations, e.g., it is
11860 returned from functions that don’t explicitly return anything. Its
11861 truth value is false.
11862
11863
11864 NotImplemented
11865 ==============
11866
11867 This type has a single value. There is a single object with this
11868 value. This object is accessed through the built-in name
11869 "NotImplemented". Numeric methods and rich comparison methods should
11870 return this value if they do not implement the operation for the
11871 operands provided. (The interpreter will then try the reflected
11872 operation, or some other fallback, depending on the operator.) It
11873 should not be evaluated in a boolean context.
11874
11875 See Implementing the arithmetic operations for more details.
11876
11877 Changed in version 3.9: Evaluating "NotImplemented" in a boolean
11878 context was deprecated.
11879
11880 Changed in version 3.14: Evaluating "NotImplemented" in a boolean
11881 context now raises a "TypeError". It previously evaluated to "True"
11882 and emitted a "DeprecationWarning" since Python 3.9.
11883
11884
11885 Ellipsis
11886 ========
11887
11888 This type has a single value. There is a single object with this
11889 value. This object is accessed through the literal "..." or the built-
11890 in name "Ellipsis". Its truth value is true.
11891
11892
11893 "numbers.Number"
11894 ================
11895
11896 These are created by numeric literals and returned as results by
11897 arithmetic operators and arithmetic built-in functions. Numeric
11898 objects are immutable; once created their value never changes. Python
11899 numbers are of course strongly related to mathematical numbers, but
11900 subject to the limitations of numerical representation in computers.
11901
11902 The string representations of the numeric classes, computed by
11903 "__repr__()" and "__str__()", have the following properties:
11904
11905 * They are valid numeric literals which, when passed to their class
11906 constructor, produce an object having the value of the original
11907 numeric.
11908
11909 * The representation is in base 10, when possible.
11910
11911 * Leading zeros, possibly excepting a single zero before a decimal
11912 point, are not shown.
11913
11914 * Trailing zeros, possibly excepting a single zero after a decimal
11915 point, are not shown.
11916
11917 * A sign is shown only when the number is negative.
11918
11919 Python distinguishes between integers, floating-point numbers, and
11920 complex numbers:
11921
11922
11923 "numbers.Integral"
11924 ------------------
11925
11926 These represent elements from the mathematical set of integers
11927 (positive and negative).
11928
11929 Note:
11930
11931 The rules for integer representation are intended to give the most
11932 meaningful interpretation of shift and mask operations involving
11933 negative integers.
11934
11935 There are two types of integers:
11936
11937 Integers ("int")
11938 These represent numbers in an unlimited range, subject to available
11939 (virtual) memory only. For the purpose of shift and mask
11940 operations, a binary representation is assumed, and negative
11941 numbers are represented in a variant of 2’s complement which gives
11942 the illusion of an infinite string of sign bits extending to the
11943 left.
11944
11945 Booleans ("bool")
11946 These represent the truth values False and True. The two objects
11947 representing the values "False" and "True" are the only Boolean
11948 objects. The Boolean type is a subtype of the integer type, and
11949 Boolean values behave like the values 0 and 1, respectively, in
11950 almost all contexts, the exception being that when converted to a
11951 string, the strings ""False"" or ""True"" are returned,
11952 respectively.
11953
11954
11955 "numbers.Real" ("float")
11956 ------------------------
11957
11958 These represent machine-level double precision floating-point numbers.
11959 You are at the mercy of the underlying machine architecture (and C or
11960 Java implementation) for the accepted range and handling of overflow.
11961 Python does not support single-precision floating-point numbers; the
11962 savings in processor and memory usage that are usually the reason for
11963 using these are dwarfed by the overhead of using objects in Python, so
11964 there is no reason to complicate the language with two kinds of
11965 floating-point numbers.
11966
11967
11968 "numbers.Complex" ("complex")
11969 -----------------------------
11970
11971 These represent complex numbers as a pair of machine-level double
11972 precision floating-point numbers. The same caveats apply as for
11973 floating-point numbers. The real and imaginary parts of a complex
11974 number "z" can be retrieved through the read-only attributes "z.real"
11975 and "z.imag".
11976
11977
11978 Sequences
11979 =========
11980
11981 These represent finite ordered sets indexed by non-negative numbers.
11982 The built-in function "len()" returns the number of items of a
11983 sequence. When the length of a sequence is *n*, the index set contains
11984 the numbers 0, 1, …, *n*-1. Item *i* of sequence *a* is selected by
11985 "a[i]". Some sequences, including built-in sequences, interpret
11986 negative subscripts by adding the sequence length. For example,
11987 "a[-2]" equals "a[n-2]", the second to last item of sequence a with
11988 length "n".
11989
11990 The resulting value must be a nonnegative integer less than the number
11991 of items in the sequence. If it is not, an "IndexError" is raised.
11992
11993 Sequences also support slicing: "a[start:stop]" selects all items with
11994 index *k* such that *start* "<=" *k* "<" *stop*. When used as an
11995 expression, a slice is a sequence of the same type. The comment above
11996 about negative subscripts also applies to negative slice positions.
11997 Note that no error is raised if a slice position is less than zero or
11998 larger than the length of the sequence.
11999
12000 If *start* is missing or "None", slicing behaves as if *start* was
12001 zero. If *stop* is missing or "None", slicing behaves as if *stop* was
12002 equal to the length of the sequence.
12003
12004 Some sequences also support “extended slicing” with a third “step”
12005 parameter: "a[i:j:k]" selects all items of *a* with index *x* where "x
12006 = i + n*k", *n* ">=" "0" and *i* "<=" *x* "<" *j*.
12007
12008 Sequences are distinguished according to their mutability:
12009
12010
12011 Immutable sequences
12012 -------------------
12013
12014 An object of an immutable sequence type cannot change once it is
12015 created. (If the object contains references to other objects, these
12016 other objects may be mutable and may be changed; however, the
12017 collection of objects directly referenced by an immutable object
12018 cannot change.)
12019
12020 The following types are immutable sequences:
12021
12022 Strings
12023 A string ("str") is a sequence of values that represent
12024 *characters*, or more formally, *Unicode code points*. All the code
12025 points in the range "0" to "0x10FFFF" can be represented in a
12026 string.
12027
12028 Python doesn’t have a dedicated *character* type. Instead, every
12029 code point in the string is represented as a string object with
12030 length "1".
12031
12032 The built-in function "ord()" converts a code point from its string
12033 form to an integer in the range "0" to "0x10FFFF"; "chr()" converts
12034 an integer in the range "0" to "0x10FFFF" to the corresponding
12035 length "1" string object. "str.encode()" can be used to convert a
12036 "str" to "bytes" using the given text encoding, and
12037 "bytes.decode()" can be used to achieve the opposite.
12038
12039 Tuples
12040 The items of a "tuple" are arbitrary Python objects. Tuples of two
12041 or more items are formed by comma-separated lists of expressions.
12042 A tuple of one item (a ‘singleton’) can be formed by affixing a
12043 comma to an expression (an expression by itself does not create a
12044 tuple, since parentheses must be usable for grouping of
12045 expressions). An empty tuple can be formed by an empty pair of
12046 parentheses.
12047
12048 Bytes
12049 A "bytes" object is an immutable array. The items are 8-bit bytes,
12050 represented by integers in the range 0 <= x < 256. Bytes literals
12051 (like "b'abc'") and the built-in "bytes()" constructor can be used
12052 to create bytes objects. Also, bytes objects can be decoded to
12053 strings via the "decode()" method.
12054
12055
12056 Mutable sequences
12057 -----------------
12058
12059 Mutable sequences can be changed after they are created. The
12060 subscription and slicing notations can be used as the target of
12061 assignment and "del" (delete) statements.
12062
12063 Note:
12064
12065 The "collections" and "array" module provide additional examples of
12066 mutable sequence types.
12067
12068 There are currently two intrinsic mutable sequence types:
12069
12070 Lists
12071 The items of a list are arbitrary Python objects. Lists are formed
12072 by placing a comma-separated list of expressions in square
12073 brackets. (Note that there are no special cases needed to form
12074 lists of length 0 or 1.)
12075
12076 Byte Arrays
12077 A bytearray object is a mutable array. They are created by the
12078 built-in "bytearray()" constructor. Aside from being mutable (and
12079 hence unhashable), byte arrays otherwise provide the same interface
12080 and functionality as immutable "bytes" objects.
12081
12082
12083 Set types
12084 =========
12085
12086 These represent unordered, finite sets of unique, immutable objects.
12087 As such, they cannot be indexed by any subscript. However, they can be
12088 iterated over, and the built-in function "len()" returns the number of
12089 items in a set. Common uses for sets are fast membership testing,
12090 removing duplicates from a sequence, and computing mathematical
12091 operations such as intersection, union, difference, and symmetric
12092 difference.
12093
12094 For set elements, the same immutability rules apply as for dictionary
12095 keys. Note that numeric types obey the normal rules for numeric
12096 comparison: if two numbers compare equal (e.g., "1" and "1.0"), only
12097 one of them can be contained in a set.
12098
12099 There are currently two intrinsic set types:
12100
12101 Sets
12102 These represent a mutable set. They are created by the built-in
12103 "set()" constructor and can be modified afterwards by several
12104 methods, such as "add()".
12105
12106 Frozen sets
12107 These represent an immutable set. They are created by the built-in
12108 "frozenset()" constructor. As a frozenset is immutable and
12109 *hashable*, it can be used again as an element of another set, or
12110 as a dictionary key.
12111
12112
12113 Mappings
12114 ========
12115
12116 These represent finite sets of objects indexed by arbitrary index
12117 sets. The subscript notation "a[k]" selects the item indexed by "k"
12118 from the mapping "a"; this can be used in expressions and as the
12119 target of assignments or "del" statements. The built-in function
12120 "len()" returns the number of items in a mapping.
12121
12122 There is currently a single intrinsic mapping type:
12123
12124
12125 Dictionaries
12126 ------------
12127
12128 These represent finite sets of objects indexed by nearly arbitrary
12129 values. The only types of values not acceptable as keys are values
12130 containing lists or dictionaries or other mutable types that are
12131 compared by value rather than by object identity, the reason being
12132 that the efficient implementation of dictionaries requires a key’s
12133 hash value to remain constant. Numeric types used for keys obey the
12134 normal rules for numeric comparison: if two numbers compare equal
12135 (e.g., "1" and "1.0") then they can be used interchangeably to index
12136 the same dictionary entry.
12137
12138 Dictionaries preserve insertion order, meaning that keys will be
12139 produced in the same order they were added sequentially over the
12140 dictionary. Replacing an existing key does not change the order,
12141 however removing a key and re-inserting it will add it to the end
12142 instead of keeping its old place.
12143
12144 Dictionaries are mutable; they can be created by the "{}" notation
12145 (see section Dictionary displays).
12146
12147 The extension modules "dbm.ndbm" and "dbm.gnu" provide additional
12148 examples of mapping types, as does the "collections" module.
12149
12150 Changed in version 3.7: Dictionaries did not preserve insertion order
12151 in versions of Python before 3.6. In CPython 3.6, insertion order was
12152 preserved, but it was considered an implementation detail at that time
12153 rather than a language guarantee.
12154
12155
12156 Callable types
12157 ==============
12158
12159 These are the types to which the function call operation (see section
12160 Calls) can be applied:
12161
12162
12163 User-defined functions
12164 ----------------------
12165
12166 A user-defined function object is created by a function definition
12167 (see section Function definitions). It should be called with an
12168 argument list containing the same number of items as the function’s
12169 formal parameter list.
12170
12171
12172 Special read-only attributes
12173 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
12174
12175 +----------------------------------------------------+----------------------------------------------------+
12176 | Attribute | Meaning |
12177 |====================================================|====================================================|
12178 | function.__builtins__ | A reference to the "dictionary" that holds the |
12179 | | function’s builtins namespace. Added in version |
12180 | | 3.10. |
12181 +----------------------------------------------------+----------------------------------------------------+
12182 | function.__globals__ | A reference to the "dictionary" that holds the |
12183 | | function’s global variables – the global namespace |
12184 | | of the module in which the function was defined. |
12185 +----------------------------------------------------+----------------------------------------------------+
12186 | function.__closure__ | "None" or a "tuple" of cells that contain bindings |
12187 | | for the names specified in the "co_freevars" |
12188 | | attribute of the function’s "code object". A cell |
12189 | | object has the attribute "cell_contents". This can |
12190 | | be used to get the value of the cell, as well as |
12191 | | set the value. |
12192 +----------------------------------------------------+----------------------------------------------------+
12193
12194
12195 Special writable attributes
12196 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
12197
12198 Most of these attributes check the type of the assigned value:
12199
12200 +----------------------------------------------------+----------------------------------------------------+
12201 | Attribute | Meaning |
12202 |====================================================|====================================================|
12203 | function.__doc__ | The function’s documentation string, or "None" if |
12204 | | unavailable. |
12205 +----------------------------------------------------+----------------------------------------------------+
12206 | function.__name__ | The function’s name. See also: "__name__ |
12207 | | attributes". |
12208 +----------------------------------------------------+----------------------------------------------------+
12209 | function.__qualname__ | The function’s *qualified name*. See also: |
12210 | | "__qualname__ attributes". Added in version 3.3. |
12211 +----------------------------------------------------+----------------------------------------------------+
12212 | function.__module__ | The name of the module the function was defined |
12213 | | in, or "None" if unavailable. |
12214 +----------------------------------------------------+----------------------------------------------------+
12215 | function.__defaults__ | A "tuple" containing default *parameter* values |
12216 | | for those parameters that have defaults, or "None" |
12217 | | if no parameters have a default value. |
12218 +----------------------------------------------------+----------------------------------------------------+
12219 | function.__code__ | The code object representing the compiled function |
12220 | | body. |
12221 +----------------------------------------------------+----------------------------------------------------+
12222 | function.__dict__ | The namespace supporting arbitrary function |
12223 | | attributes. See also: "__dict__ attributes". |
12224 +----------------------------------------------------+----------------------------------------------------+
12225 | function.__annotations__ | A "dictionary" containing annotations of |
12226 | | *parameters*. The keys of the dictionary are the |
12227 | | parameter names, and "'return'" for the return |
12228 | | annotation, if provided. See also: |
12229 | | "object.__annotations__". Changed in version |
12230 | | 3.14: Annotations are now lazily evaluated. See |
12231 | | **PEP 649**. |
12232 +----------------------------------------------------+----------------------------------------------------+
12233 | function.__annotate__ | The *annotate function* for this function, or |
12234 | | "None" if the function has no annotations. See |
12235 | | "object.__annotate__". Added in version 3.14. |
12236 +----------------------------------------------------+----------------------------------------------------+
12237 | function.__kwdefaults__ | A "dictionary" containing defaults for keyword- |
12238 | | only *parameters*. |
12239 +----------------------------------------------------+----------------------------------------------------+
12240 | function.__type_params__ | A "tuple" containing the type parameters of a |
12241 | | generic function. Added in version 3.12. |
12242 +----------------------------------------------------+----------------------------------------------------+
12243
12244 Function objects also support getting and setting arbitrary
12245 attributes, which can be used, for example, to attach metadata to
12246 functions. Regular attribute dot-notation is used to get and set such
12247 attributes.
12248
12249 **CPython implementation detail:** CPython’s current implementation
12250 only supports function attributes on user-defined functions. Function
12251 attributes on built-in functions may be supported in the future.
12252
12253 Additional information about a function’s definition can be retrieved
12254 from its code object (accessible via the "__code__" attribute).
12255
12256
12257 Instance methods
12258 ----------------
12259
12260 An instance method object combines a class, a class instance and any
12261 callable object (normally a user-defined function).
12262
12263 Special read-only attributes:
12264
12265 +----------------------------------------------------+----------------------------------------------------+
12266 | method.__self__ | Refers to the class instance object to which the |
12267 | | method is bound |
12268 +----------------------------------------------------+----------------------------------------------------+
12269 | method.__func__ | Refers to the original function object |
12270 +----------------------------------------------------+----------------------------------------------------+
12271 | method.__doc__ | The method’s documentation (same as |
12272 | | "method.__func__.__doc__"). A "string" if the |
12273 | | original function had a docstring, else "None". |
12274 +----------------------------------------------------+----------------------------------------------------+
12275 | method.__name__ | The name of the method (same as |
12276 | | "method.__func__.__name__") |
12277 +----------------------------------------------------+----------------------------------------------------+
12278 | method.__module__ | The name of the module the method was defined in, |
12279 | | or "None" if unavailable. |
12280 +----------------------------------------------------+----------------------------------------------------+
12281
12282 Methods also support accessing (but not setting) the arbitrary
12283 function attributes on the underlying function object.
12284
12285 User-defined method objects may be created when getting an attribute
12286 of a class (perhaps via an instance of that class), if that attribute
12287 is a user-defined function object or a "classmethod" object.
12288
12289 When an instance method object is created by retrieving a user-defined
12290 function object from a class via one of its instances, its "__self__"
12291 attribute is the instance, and the method object is said to be
12292 *bound*. The new method’s "__func__" attribute is the original
12293 function object.
12294
12295 When an instance method object is created by retrieving a
12296 "classmethod" object from a class or instance, its "__self__"
12297 attribute is the class itself, and its "__func__" attribute is the
12298 function object underlying the class method.
12299
12300 When an instance method object is called, the underlying function
12301 ("__func__") is called, inserting the class instance ("__self__") in
12302 front of the argument list. For instance, when "C" is a class which
12303 contains a definition for a function "f()", and "x" is an instance of
12304 "C", calling "x.f(1)" is equivalent to calling "C.f(x, 1)".
12305
12306 When an instance method object is derived from a "classmethod" object,
12307 the “class instance” stored in "__self__" will actually be the class
12308 itself, so that calling either "x.f(1)" or "C.f(1)" is equivalent to
12309 calling "f(C,1)" where "f" is the underlying function.
12310
12311 It is important to note that user-defined functions which are
12312 attributes of a class instance are not converted to bound methods;
12313 this *only* happens when the function is an attribute of the class.
12314
12315
12316 Generator functions
12317 -------------------
12318
12319 A function or method which uses the "yield" statement (see section The
12320 yield statement) is called a *generator function*. Such a function,
12321 when called, always returns an *iterator* object which can be used to
12322 execute the body of the function: calling the iterator’s
12323 "iterator.__next__()" method will cause the function to execute until
12324 it provides a value using the "yield" statement. When the function
12325 executes a "return" statement or falls off the end, a "StopIteration"
12326 exception is raised and the iterator will have reached the end of the
12327 set of values to be returned.
12328
12329
12330 Coroutine functions
12331 -------------------
12332
12333 A function or method which is defined using "async def" is called a
12334 *coroutine function*. Such a function, when called, returns a
12335 *coroutine* object. It may contain "await" expressions, as well as
12336 "async with" and "async for" statements. See also the Coroutine
12337 Objects section.
12338
12339
12340 Asynchronous generator functions
12341 --------------------------------
12342
12343 A function or method which is defined using "async def" and which uses
12344 the "yield" statement is called a *asynchronous generator function*.
12345 Such a function, when called, returns an *asynchronous iterator*
12346 object which can be used in an "async for" statement to execute the
12347 body of the function.
12348
12349 Calling the asynchronous iterator’s "aiterator.__anext__" method will
12350 return an *awaitable* which when awaited will execute until it
12351 provides a value using the "yield" expression. When the function
12352 executes an empty "return" statement or falls off the end, a
12353 "StopAsyncIteration" exception is raised and the asynchronous iterator
12354 will have reached the end of the set of values to be yielded.
12355
12356
12357 Built-in functions
12358 ------------------
12359
12360 A built-in function object is a wrapper around a C function. Examples
12361 of built-in functions are "len()" and "math.sin()" ("math" is a
12362 standard built-in module). The number and type of the arguments are
12363 determined by the C function. Special read-only attributes:
12364
12365 * "__doc__" is the function’s documentation string, or "None" if
12366 unavailable. See "function.__doc__".
12367
12368 * "__name__" is the function’s name. See "function.__name__".
12369
12370 * "__self__" is set to "None" (but see the next item).
12371
12372 * "__module__" is the name of the module the function was defined in
12373 or "None" if unavailable. See "function.__module__".
12374
12375
12376 Built-in methods
12377 ----------------
12378
12379 This is really a different disguise of a built-in function, this time
12380 containing an object passed to the C function as an implicit extra
12381 argument. An example of a built-in method is "alist.append()",
12382 assuming *alist* is a list object. In this case, the special read-only
12383 attribute "__self__" is set to the object denoted by *alist*. (The
12384 attribute has the same semantics as it does with "other instance
12385 methods".)
12386
12387
12388 Classes
12389 -------
12390
12391 Classes are callable. These objects normally act as factories for new
12392 instances of themselves, but variations are possible for class types
12393 that override "__new__()". The arguments of the call are passed to
12394 "__new__()" and, in the typical case, to "__init__()" to initialize
12395 the new instance.
12396
12397
12398 Class Instances
12399 ---------------
12400
12401 Instances of arbitrary classes can be made callable by defining a
12402 "__call__()" method in their class.
12403
12404
12405 Modules
12406 =======
12407
12408 Modules are a basic organizational unit of Python code, and are
12409 created by the import system as invoked either by the "import"
12410 statement, or by calling functions such as "importlib.import_module()"
12411 and built-in "__import__()". A module object has a namespace
12412 implemented by a "dictionary" object (this is the dictionary
12413 referenced by the "__globals__" attribute of functions defined in the
12414 module). Attribute references are translated to lookups in this
12415 dictionary, e.g., "m.x" is equivalent to "m.__dict__["x"]". A module
12416 object does not contain the code object used to initialize the module
12417 (since it isn’t needed once the initialization is done).
12418
12419 Attribute assignment updates the module’s namespace dictionary, e.g.,
12420 "m.x = 1" is equivalent to "m.__dict__["x"] = 1".
12421
12422
12423 Import-related attributes on module objects
12424 -------------------------------------------
12425
12426 Module objects have the following attributes that relate to the import
12427 system. When a module is created using the machinery associated with
12428 the import system, these attributes are filled in based on the
12429 module’s *spec*, before the *loader* executes and loads the module.
12430
12431 To create a module dynamically rather than using the import system,
12432 it’s recommended to use "importlib.util.module_from_spec()", which
12433 will set the various import-controlled attributes to appropriate
12434 values. It’s also possible to use the "types.ModuleType" constructor
12435 to create modules directly, but this technique is more error-prone, as
12436 most attributes must be manually set on the module object after it has
12437 been created when using this approach.
12438
12439 Caution:
12440
12441 With the exception of "__name__", it is **strongly** recommended
12442 that you rely on "__spec__" and its attributes instead of any of the
12443 other individual attributes listed in this subsection. Note that
12444 updating an attribute on "__spec__" will not update the
12445 corresponding attribute on the module itself:
12446
12447 >>> import typing
12448 >>> typing.__name__, typing.__spec__.name
12449 ('typing', 'typing')
12450 >>> typing.__spec__.name = 'spelling'
12451 >>> typing.__name__, typing.__spec__.name
12452 ('typing', 'spelling')
12453 >>> typing.__name__ = 'keyboard_smashing'
12454 >>> typing.__name__, typing.__spec__.name
12455 ('keyboard_smashing', 'spelling')
12456
12457 module.__name__
12458
12459 The name used to uniquely identify the module in the import system.
12460 For a directly executed module, this will be set to ""__main__"".
12461
12462 This attribute must be set to the fully qualified name of the
12463 module. It is expected to match the value of
12464 "module.__spec__.name".
12465
12466 module.__spec__
12467
12468 A record of the module’s import-system-related state.
12469
12470 Set to the "module spec" that was used when importing the module.
12471 See Module specs for more details.
12472
12473 Added in version 3.4.
12474
12475 module.__package__
12476
12477 The *package* a module belongs to.
12478
12479 If the module is top-level (that is, not a part of any specific
12480 package) then the attribute should be set to "''" (the empty
12481 string). Otherwise, it should be set to the name of the module’s
12482 package (which can be equal to "module.__name__" if the module
12483 itself is a package). See **PEP 366** for further details.
12484
12485 This attribute is used instead of "__name__" to calculate explicit
12486 relative imports for main modules. It defaults to "None" for
12487 modules created dynamically using the "types.ModuleType"
12488 constructor; use "importlib.util.module_from_spec()" instead to
12489 ensure the attribute is set to a "str".
12490
12491 It is **strongly** recommended that you use
12492 "module.__spec__.parent" instead of "module.__package__".
12493 "__package__" is now only used as a fallback if "__spec__.parent"
12494 is not set, and this fallback path is deprecated.
12495
12496 Changed in version 3.4: This attribute now defaults to "None" for
12497 modules created dynamically using the "types.ModuleType"
12498 constructor. Previously the attribute was optional.
12499
12500 Changed in version 3.6: The value of "__package__" is expected to
12501 be the same as "__spec__.parent". "__package__" is now only used as
12502 a fallback during import resolution if "__spec__.parent" is not
12503 defined.
12504
12505 Changed in version 3.10: "ImportWarning" is raised if an import
12506 resolution falls back to "__package__" instead of
12507 "__spec__.parent".
12508
12509 Changed in version 3.12: Raise "DeprecationWarning" instead of
12510 "ImportWarning" when falling back to "__package__" during import
12511 resolution.
12512
12513 Deprecated since version 3.13, will be removed in version 3.15:
12514 "__package__" will cease to be set or taken into consideration by
12515 the import system or standard library.
12516
12517 module.__loader__
12518
12519 The *loader* object that the import machinery used to load the
12520 module.
12521
12522 This attribute is mostly useful for introspection, but can be used
12523 for additional loader-specific functionality, for example getting
12524 data associated with a loader.
12525
12526 "__loader__" defaults to "None" for modules created dynamically
12527 using the "types.ModuleType" constructor; use
12528 "importlib.util.module_from_spec()" instead to ensure the attribute
12529 is set to a *loader* object.
12530
12531 It is **strongly** recommended that you use
12532 "module.__spec__.loader" instead of "module.__loader__".
12533
12534 Changed in version 3.4: This attribute now defaults to "None" for
12535 modules created dynamically using the "types.ModuleType"
12536 constructor. Previously the attribute was optional.
12537
12538 Deprecated since version 3.12, will be removed in version 3.16:
12539 Setting "__loader__" on a module while failing to set
12540 "__spec__.loader" is deprecated. In Python 3.16, "__loader__" will
12541 cease to be set or taken into consideration by the import system or
12542 the standard library.
12543
12544 module.__path__
12545
12546 A (possibly empty) *sequence* of strings enumerating the locations
12547 where the package’s submodules will be found. Non-package modules
12548 should not have a "__path__" attribute. See __path__ attributes on
12549 modules for more details.
12550
12551 It is **strongly** recommended that you use
12552 "module.__spec__.submodule_search_locations" instead of
12553 "module.__path__".
12554
12555 module.__file__
12556
12557 module.__cached__
12558
12559 "__file__" and "__cached__" are both optional attributes that may
12560 or may not be set. Both attributes should be a "str" when they are
12561 available.
12562
12563 "__file__" indicates the pathname of the file from which the module
12564 was loaded (if loaded from a file), or the pathname of the shared
12565 library file for extension modules loaded dynamically from a shared
12566 library. It might be missing for certain types of modules, such as
12567 C modules that are statically linked into the interpreter, and the
12568 import system may opt to leave it unset if it has no semantic
12569 meaning (for example, a module loaded from a database).
12570
12571 If "__file__" is set then the "__cached__" attribute might also be
12572 set, which is the path to any compiled version of the code (for
12573 example, a byte-compiled file). The file does not need to exist to
12574 set this attribute; the path can simply point to where the compiled
12575 file *would* exist (see **PEP 3147**).
12576
12577 Note that "__cached__" may be set even if "__file__" is not set.
12578 However, that scenario is quite atypical. Ultimately, the *loader*
12579 is what makes use of the module spec provided by the *finder* (from
12580 which "__file__" and "__cached__" are derived). So if a loader can
12581 load from a cached module but otherwise does not load from a file,
12582 that atypical scenario may be appropriate.
12583
12584 It is **strongly** recommended that you use
12585 "module.__spec__.cached" instead of "module.__cached__".
12586
12587 Deprecated since version 3.13, will be removed in version 3.15:
12588 Setting "__cached__" on a module while failing to set
12589 "__spec__.cached" is deprecated. In Python 3.15, "__cached__" will
12590 cease to be set or taken into consideration by the import system or
12591 standard library.
12592
12593
12594 Other writable attributes on module objects
12595 -------------------------------------------
12596
12597 As well as the import-related attributes listed above, module objects
12598 also have the following writable attributes:
12599
12600 module.__doc__
12601
12602 The module’s documentation string, or "None" if unavailable. See
12603 also: "__doc__ attributes".
12604
12605 module.__annotations__
12606
12607 A dictionary containing *variable annotations* collected during
12608 module body execution. For best practices on working with
12609 "__annotations__", see "annotationlib".
12610
12611 Changed in version 3.14: Annotations are now lazily evaluated. See
12612 **PEP 649**.
12613
12614 module.__annotate__
12615
12616 The *annotate function* for this module, or "None" if the module
12617 has no annotations. See also: "__annotate__" attributes.
12618
12619 Added in version 3.14.
12620
12621
12622 Module dictionaries
12623 -------------------
12624
12625 Module objects also have the following special read-only attribute:
12626
12627 module.__dict__
12628
12629 The module’s namespace as a dictionary object. Uniquely among the
12630 attributes listed here, "__dict__" cannot be accessed as a global
12631 variable from within a module; it can only be accessed as an
12632 attribute on module objects.
12633
12634 **CPython implementation detail:** Because of the way CPython
12635 clears module dictionaries, the module dictionary will be cleared
12636 when the module falls out of scope even if the dictionary still has
12637 live references. To avoid this, copy the dictionary or keep the
12638 module around while using its dictionary directly.
12639
12640
12641 Custom classes
12642 ==============
12643
12644 Custom class types are typically created by class definitions (see
12645 section Class definitions). A class has a namespace implemented by a
12646 dictionary object. Class attribute references are translated to
12647 lookups in this dictionary, e.g., "C.x" is translated to
12648 "C.__dict__["x"]" (although there are a number of hooks which allow
12649 for other means of locating attributes). When the attribute name is
12650 not found there, the attribute search continues in the base classes.
12651 This search of the base classes uses the C3 method resolution order
12652 which behaves correctly even in the presence of ‘diamond’ inheritance
12653 structures where there are multiple inheritance paths leading back to
12654 a common ancestor. Additional details on the C3 MRO used by Python can
12655 be found at The Python 2.3 Method Resolution Order.
12656
12657 When a class attribute reference (for class "C", say) would yield a
12658 class method object, it is transformed into an instance method object
12659 whose "__self__" attribute is "C". When it would yield a
12660 "staticmethod" object, it is transformed into the object wrapped by
12661 the static method object. See section Implementing Descriptors for
12662 another way in which attributes retrieved from a class may differ from
12663 those actually contained in its "__dict__".
12664
12665 Class attribute assignments update the class’s dictionary, never the
12666 dictionary of a base class.
12667
12668 A class object can be called (see above) to yield a class instance
12669 (see below).
12670
12671
12672 Special attributes
12673 ------------------
12674
12675 +----------------------------------------------------+----------------------------------------------------+
12676 | Attribute | Meaning |
12677 |====================================================|====================================================|
12678 | type.__name__ | The class’s name. See also: "__name__ attributes". |
12679 +----------------------------------------------------+----------------------------------------------------+
12680 | type.__qualname__ | The class’s *qualified name*. See also: |
12681 | | "__qualname__ attributes". |
12682 +----------------------------------------------------+----------------------------------------------------+
12683 | type.__module__ | The name of the module in which the class was |
12684 | | defined. |
12685 +----------------------------------------------------+----------------------------------------------------+
12686 | type.__dict__ | A "mapping proxy" providing a read-only view of |
12687 | | the class’s namespace. See also: "__dict__ |
12688 | | attributes". |
12689 +----------------------------------------------------+----------------------------------------------------+
12690 | type.__bases__ | A "tuple" containing the class’s bases. In most |
12691 | | cases, for a class defined as "class X(A, B, C)", |
12692 | | "X.__bases__" will be exactly equal to "(A, B, |
12693 | | C)". |
12694 +----------------------------------------------------+----------------------------------------------------+
12695 | type.__base__ | **CPython implementation detail:** The single base |
12696 | | class in the inheritance chain that is responsible |
12697 | | for the memory layout of instances. This attribute |
12698 | | corresponds to "tp_base" at the C level. |
12699 +----------------------------------------------------+----------------------------------------------------+
12700 | type.__doc__ | The class’s documentation string, or "None" if |
12701 | | undefined. Not inherited by subclasses. |
12702 +----------------------------------------------------+----------------------------------------------------+
12703 | type.__annotations__ | A dictionary containing *variable annotations* |
12704 | | collected during class body execution. See also: |
12705 | | "__annotations__ attributes". For best practices |
12706 | | on working with "__annotations__", please see |
12707 | | "annotationlib". Use |
12708 | | "annotationlib.get_annotations()" instead of |
12709 | | accessing this attribute directly. Warning: |
12710 | | Accessing the "__annotations__" attribute directly |
12711 | | on a class object may return annotations for the |
12712 | | wrong class, specifically in certain cases where |
12713 | | the class, its base class, or a metaclass is |
12714 | | defined under "from __future__ import |
12715 | | annotations". See **749** for details.This |
12716 | | attribute does not exist on certain builtin |
12717 | | classes. On user-defined classes without |
12718 | | "__annotations__", it is an empty dictionary. |
12719 | | Changed in version 3.14: Annotations are now |
12720 | | lazily evaluated. See **PEP 649**. |
12721 +----------------------------------------------------+----------------------------------------------------+
12722 | type.__annotate__() | The *annotate function* for this class, or "None" |
12723 | | if the class has no annotations. See also: |
12724 | | "__annotate__ attributes". Added in version 3.14. |
12725 +----------------------------------------------------+----------------------------------------------------+
12726 | type.__type_params__ | A "tuple" containing the type parameters of a |
12727 | | generic class. Added in version 3.12. |
12728 +----------------------------------------------------+----------------------------------------------------+
12729 | type.__static_attributes__ | A "tuple" containing names of attributes of this |
12730 | | class which are assigned through "self.X" from any |
12731 | | function in its body. Added in version 3.13. |
12732 +----------------------------------------------------+----------------------------------------------------+
12733 | type.__firstlineno__ | The line number of the first line of the class |
12734 | | definition, including decorators. Setting the |
12735 | | "__module__" attribute removes the |
12736 | | "__firstlineno__" item from the type’s dictionary. |
12737 | | Added in version 3.13. |
12738 +----------------------------------------------------+----------------------------------------------------+
12739 | type.__mro__ | The "tuple" of classes that are considered when |
12740 | | looking for base classes during method resolution. |
12741 +----------------------------------------------------+----------------------------------------------------+
12742
12743
12744 Special methods
12745 ---------------
12746
12747 In addition to the special attributes described above, all Python
12748 classes also have the following two methods available:
12749
12750 type.mro()
12751
12752 This method can be overridden by a metaclass to customize the
12753 method resolution order for its instances. It is called at class
12754 instantiation, and its result is stored in "__mro__".
12755
12756 type.__subclasses__()
12757
12758 Each class keeps a list of weak references to its immediate
12759 subclasses. This method returns a list of all those references
12760 still alive. The list is in definition order. Example:
12761
12762 >>> class A: pass
12763 >>> class B(A): pass
12764 >>> A.__subclasses__()
12765 [<class 'B'>]
12766
12767
12768 Class instances
12769 ===============
12770
12771 A class instance is created by calling a class object (see above). A
12772 class instance has a namespace implemented as a dictionary which is
12773 the first place in which attribute references are searched. When an
12774 attribute is not found there, and the instance’s class has an
12775 attribute by that name, the search continues with the class
12776 attributes. If a class attribute is found that is a user-defined
12777 function object, it is transformed into an instance method object
12778 whose "__self__" attribute is the instance. Static method and class
12779 method objects are also transformed; see above under “Classes”. See
12780 section Implementing Descriptors for another way in which attributes
12781 of a class retrieved via its instances may differ from the objects
12782 actually stored in the class’s "__dict__". If no class attribute is
12783 found, and the object’s class has a "__getattr__()" method, that is
12784 called to satisfy the lookup.
12785
12786 Attribute assignments and deletions update the instance’s dictionary,
12787 never a class’s dictionary. If the class has a "__setattr__()" or
12788 "__delattr__()" method, this is called instead of updating the
12789 instance dictionary directly.
12790
12791 Class instances can pretend to be numbers, sequences, or mappings if
12792 they have methods with certain special names. See section Special
12793 method names.
12794
12795
12796 Special attributes
12797 ------------------
12798
12799 object.__class__
12800
12801 The class to which a class instance belongs.
12802
12803 object.__dict__
12804
12805 A dictionary or other mapping object used to store an object’s
12806 (writable) attributes. Not all instances have a "__dict__"
12807 attribute; see the section on __slots__ for more details.
12808
12809
12810 I/O objects (also known as file objects)
12811 ========================================
12812
12813 A *file object* represents an open file. Various shortcuts are
12814 available to create file objects: the "open()" built-in function, and
12815 also "os.popen()", "os.fdopen()", and the "makefile()" method of
12816 socket objects (and perhaps by other functions or methods provided by
12817 extension modules).
12818
12819 File objects implement common methods, listed below, to simplify usage
12820 in generic code. They are expected to be With Statement Context
12821 Managers.
12822
12823 The objects "sys.stdin", "sys.stdout" and "sys.stderr" are initialized
12824 to file objects corresponding to the interpreter’s standard input,
12825 output and error streams; they are all open in text mode and therefore
12826 follow the interface defined by the "io.TextIOBase" abstract class.
12827
12828 file.read(size=-1, /)
12829
12830 Retrieve up to *size* data from the file. As a convenience if
12831 *size* is unspecified or -1 retrieve all data available.
12832
12833 file.write(data, /)
12834
12835 Store *data* to the file.
12836
12837 file.close()
12838
12839 Flush any buffers and close the underlying file.
12840
12841
12842 Internal types
12843 ==============
12844
12845 A few types used internally by the interpreter are exposed to the
12846 user. Their definitions may change with future versions of the
12847 interpreter, but they are mentioned here for completeness.
12848
12849
12850 Code objects
12851 ------------
12852
12853 Code objects represent *byte-compiled* executable Python code, or
12854 *bytecode*. The difference between a code object and a function object
12855 is that the function object contains an explicit reference to the
12856 function’s globals (the module in which it was defined), while a code
12857 object contains no context; also the default argument values are
12858 stored in the function object, not in the code object (because they
12859 represent values calculated at run-time). Unlike function objects,
12860 code objects are immutable and contain no references (directly or
12861 indirectly) to mutable objects.
12862
12863
12864 Special read-only attributes
12865 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
12866
12867 +----------------------------------------------------+----------------------------------------------------+
12868 | codeobject.co_name | The function name |
12869 +----------------------------------------------------+----------------------------------------------------+
12870 | codeobject.co_qualname | The fully qualified function name Added in |
12871 | | version 3.11. |
12872 +----------------------------------------------------+----------------------------------------------------+
12873 | codeobject.co_argcount | The total number of positional *parameters* |
12874 | | (including positional-only parameters and |
12875 | | parameters with default values) that the function |
12876 | | has |
12877 +----------------------------------------------------+----------------------------------------------------+
12878 | codeobject.co_posonlyargcount | The number of positional-only *parameters* |
12879 | | (including arguments with default values) that the |
12880 | | function has |
12881 +----------------------------------------------------+----------------------------------------------------+
12882 | codeobject.co_kwonlyargcount | The number of keyword-only *parameters* (including |
12883 | | arguments with default values) that the function |
12884 | | has |
12885 +----------------------------------------------------+----------------------------------------------------+
12886 | codeobject.co_nlocals | The number of local variables used by the function |
12887 | | (including parameters) |
12888 +----------------------------------------------------+----------------------------------------------------+
12889 | codeobject.co_varnames | A "tuple" containing the names of the local |
12890 | | variables in the function (starting with the |
12891 | | parameter names) |
12892 +----------------------------------------------------+----------------------------------------------------+
12893 | codeobject.co_cellvars | A "tuple" containing the names of local variables |
12894 | | that are referenced from at least one *nested |
12895 | | scope* inside the function |
12896 +----------------------------------------------------+----------------------------------------------------+
12897 | codeobject.co_freevars | A "tuple" containing the names of *free (closure) |
12898 | | variables* that a *nested scope* references in an |
12899 | | outer scope. See also "function.__closure__". |
12900 | | Note: references to global and builtin names are |
12901 | | *not* included. |
12902 +----------------------------------------------------+----------------------------------------------------+
12903 | codeobject.co_code | A string representing the sequence of *bytecode* |
12904 | | instructions in the function |
12905 +----------------------------------------------------+----------------------------------------------------+
12906 | codeobject.co_consts | A "tuple" containing the literals used by the |
12907 | | *bytecode* in the function |
12908 +----------------------------------------------------+----------------------------------------------------+
12909 | codeobject.co_names | A "tuple" containing the names used by the |
12910 | | *bytecode* in the function |
12911 +----------------------------------------------------+----------------------------------------------------+
12912 | codeobject.co_filename | The name of the file from which the code was |
12913 | | compiled |
12914 +----------------------------------------------------+----------------------------------------------------+
12915 | codeobject.co_firstlineno | The line number of the first line of the function |
12916 +----------------------------------------------------+----------------------------------------------------+
12917 | codeobject.co_lnotab | A string encoding the mapping from *bytecode* |
12918 | | offsets to line numbers. For details, see the |
12919 | | source code of the interpreter. Deprecated since |
12920 | | version 3.12: This attribute of code objects is |
12921 | | deprecated, and may be removed in Python 3.15. |
12922 +----------------------------------------------------+----------------------------------------------------+
12923 | codeobject.co_stacksize | The required stack size of the code object |
12924 +----------------------------------------------------+----------------------------------------------------+
12925 | codeobject.co_flags | An "integer" encoding a number of flags for the |
12926 | | interpreter. |
12927 +----------------------------------------------------+----------------------------------------------------+
12928
12929 The following flag bits are defined for "co_flags": bit "0x04" is set
12930 if the function uses the "*arguments" syntax to accept an arbitrary
12931 number of positional arguments; bit "0x08" is set if the function uses
12932 the "**keywords" syntax to accept arbitrary keyword arguments; bit
12933 "0x20" is set if the function is a generator. See Code Objects Bit
12934 Flags for details on the semantics of each flags that might be
12935 present.
12936
12937 Future feature declarations (for example, "from __future__ import
12938 division") also use bits in "co_flags" to indicate whether a code
12939 object was compiled with a particular feature enabled. See
12940 "compiler_flag".
12941
12942 Other bits in "co_flags" are reserved for internal use.
12943
12944 If a code object represents a function and has a docstring, the
12945 "CO_HAS_DOCSTRING" bit is set in "co_flags" and the first item in
12946 "co_consts" is the docstring of the function.
12947
12948
12949 Methods on code objects
12950 ~~~~~~~~~~~~~~~~~~~~~~~
12951
12952 codeobject.co_positions()
12953
12954 Returns an iterable over the source code positions of each
12955 *bytecode* instruction in the code object.
12956
12957 The iterator returns "tuple"s containing the "(start_line,
12958 end_line, start_column, end_column)". The *i-th* tuple corresponds
12959 to the position of the source code that compiled to the *i-th* code
12960 unit. Column information is 0-indexed utf-8 byte offsets on the
12961 given source line.
12962
12963 This positional information can be missing. A non-exhaustive lists
12964 of cases where this may happen:
12965
12966 * Running the interpreter with "-X" "no_debug_ranges".
12967
12968 * Loading a pyc file compiled while using "-X" "no_debug_ranges".
12969
12970 * Position tuples corresponding to artificial instructions.
12971
12972 * Line and column numbers that can’t be represented due to
12973 implementation specific limitations.
12974
12975 When this occurs, some or all of the tuple elements can be "None".
12976
12977 Added in version 3.11.
12978
12979 Note:
12980
12981 This feature requires storing column positions in code objects
12982 which may result in a small increase of disk usage of compiled
12983 Python files or interpreter memory usage. To avoid storing the
12984 extra information and/or deactivate printing the extra traceback
12985 information, the "-X" "no_debug_ranges" command line flag or the
12986 "PYTHONNODEBUGRANGES" environment variable can be used.
12987
12988 codeobject.co_lines()
12989
12990 Returns an iterator that yields information about successive ranges
12991 of *bytecode*s. Each item yielded is a "(start, end, lineno)"
12992 "tuple":
12993
12994 * "start" (an "int") represents the offset (inclusive) of the start
12995 of the *bytecode* range
12996
12997 * "end" (an "int") represents the offset (exclusive) of the end of
12998 the *bytecode* range
12999
13000 * "lineno" is an "int" representing the line number of the
13001 *bytecode* range, or "None" if the bytecodes in the given range
13002 have no line number
13003
13004 The items yielded will have the following properties:
13005
13006 * The first range yielded will have a "start" of 0.
13007
13008 * The "(start, end)" ranges will be non-decreasing and consecutive.
13009 That is, for any pair of "tuple"s, the "start" of the second will
13010 be equal to the "end" of the first.
13011
13012 * No range will be backwards: "end >= start" for all triples.
13013
13014 * The last "tuple" yielded will have "end" equal to the size of the
13015 *bytecode*.
13016
13017 Zero-width ranges, where "start == end", are allowed. Zero-width
13018 ranges are used for lines that are present in the source code, but
13019 have been eliminated by the *bytecode* compiler.
13020
13021 Added in version 3.10.
13022
13023 See also:
13024
13025 **PEP 626** - Precise line numbers for debugging and other tools.
13026 The PEP that introduced the "co_lines()" method.
13027
13028 codeobject.replace(**kwargs)
13029
13030 Return a copy of the code object with new values for the specified
13031 fields.
13032
13033 Code objects are also supported by the generic function
13034 "copy.replace()".
13035
13036 Added in version 3.8.
13037
13038
13039 Frame objects
13040 -------------
13041
13042 Frame objects represent execution frames. They may occur in traceback
13043 objects, and are also passed to registered trace functions.
13044
13045
13046 Special read-only attributes
13047 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
13048
13049 +----------------------------------------------------+----------------------------------------------------+
13050 | frame.f_back | Points to the previous stack frame (towards the |
13051 | | caller), or "None" if this is the bottom stack |
13052 | | frame |
13053 +----------------------------------------------------+----------------------------------------------------+
13054 | frame.f_code | The code object being executed in this frame. |
13055 | | Accessing this attribute raises an auditing event |
13056 | | "object.__getattr__" with arguments "obj" and |
13057 | | ""f_code"". |
13058 +----------------------------------------------------+----------------------------------------------------+
13059 | frame.f_locals | The mapping used by the frame to look up local |
13060 | | variables. If the frame refers to an *optimized |
13061 | | scope*, this may return a write-through proxy |
13062 | | object. Changed in version 3.13: Return a proxy |
13063 | | for optimized scopes. |
13064 +----------------------------------------------------+----------------------------------------------------+
13065 | frame.f_globals | The dictionary used by the frame to look up global |
13066 | | variables |
13067 +----------------------------------------------------+----------------------------------------------------+
13068 | frame.f_builtins | The dictionary used by the frame to look up built- |
13069 | | in (intrinsic) names |
13070 +----------------------------------------------------+----------------------------------------------------+
13071 | frame.f_lasti | The “precise instruction” of the frame object |
13072 | | (this is an index into the *bytecode* string of |
13073 | | the code object) |
13074 +----------------------------------------------------+----------------------------------------------------+
13075 | frame.f_generator | The *generator* or *coroutine* object that owns |
13076 | | this frame, or "None" if the frame is a normal |
13077 | | function. Added in version 3.14. |
13078 +----------------------------------------------------+----------------------------------------------------+
13079
13080
13081 Special writable attributes
13082 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
13083
13084 +----------------------------------------------------+----------------------------------------------------+
13085 | frame.f_trace | If not "None", this is a function called for |
13086 | | various events during code execution (this is used |
13087 | | by debuggers). Normally an event is triggered for |
13088 | | each new source line (see "f_trace_lines"). |
13089 +----------------------------------------------------+----------------------------------------------------+
13090 | frame.f_trace_lines | Set this attribute to "False" to disable |
13091 | | triggering a tracing event for each source line. |
13092 +----------------------------------------------------+----------------------------------------------------+
13093 | frame.f_trace_opcodes | Set this attribute to "True" to allow per-opcode |
13094 | | events to be requested. Note that this may lead to |
13095 | | undefined interpreter behaviour if exceptions |
13096 | | raised by the trace function escape to the |
13097 | | function being traced. |
13098 +----------------------------------------------------+----------------------------------------------------+
13099 | frame.f_lineno | The current line number of the frame – writing to |
13100 | | this from within a trace function jumps to the |
13101 | | given line (only for the bottom-most frame). A |
13102 | | debugger can implement a Jump command (aka Set |
13103 | | Next Statement) by writing to this attribute. |
13104 +----------------------------------------------------+----------------------------------------------------+
13105
13106
13107 Frame object methods
13108 ~~~~~~~~~~~~~~~~~~~~
13109
13110 Frame objects support one method:
13111
13112 frame.clear()
13113
13114 This method clears all references to local variables held by the
13115 frame. Also, if the frame belonged to a *generator*, the generator
13116 is finalized. This helps break reference cycles involving frame
13117 objects (for example when catching an exception and storing its
13118 traceback for later use).
13119
13120 "RuntimeError" is raised if the frame is currently executing or
13121 suspended.
13122
13123 Added in version 3.4.
13124
13125 Changed in version 3.13: Attempting to clear a suspended frame
13126 raises "RuntimeError" (as has always been the case for executing
13127 frames).
13128
13129
13130 Traceback objects
13131 -----------------
13132
13133 Traceback objects represent the stack trace of an exception. A
13134 traceback object is implicitly created when an exception occurs, and
13135 may also be explicitly created by calling "types.TracebackType".
13136
13137 Changed in version 3.7: Traceback objects can now be explicitly
13138 instantiated from Python code.
13139
13140 For implicitly created tracebacks, when the search for an exception
13141 handler unwinds the execution stack, at each unwound level a traceback
13142 object is inserted in front of the current traceback. When an
13143 exception handler is entered, the stack trace is made available to the
13144 program. (See section The try statement.) It is accessible as the
13145 third item of the tuple returned by "sys.exc_info()", and as the
13146 "__traceback__" attribute of the caught exception.
13147
13148 When the program contains no suitable handler, the stack trace is
13149 written (nicely formatted) to the standard error stream; if the
13150 interpreter is interactive, it is also made available to the user as
13151 "sys.last_traceback".
13152
13153 For explicitly created tracebacks, it is up to the creator of the
13154 traceback to determine how the "tb_next" attributes should be linked
13155 to form a full stack trace.
13156
13157 Special read-only attributes:
13158
13159 +----------------------------------------------------+----------------------------------------------------+
13160 | traceback.tb_frame | Points to the execution frame of the current |
13161 | | level. Accessing this attribute raises an |
13162 | | auditing event "object.__getattr__" with arguments |
13163 | | "obj" and ""tb_frame"". |
13164 +----------------------------------------------------+----------------------------------------------------+
13165 | traceback.tb_lineno | Gives the line number where the exception occurred |
13166 +----------------------------------------------------+----------------------------------------------------+
13167 | traceback.tb_lasti | Indicates the “precise instruction”. |
13168 +----------------------------------------------------+----------------------------------------------------+
13169
13170 The line number and last instruction in the traceback may differ from
13171 the line number of its frame object if the exception occurred in a
13172 "try" statement with no matching except clause or with a "finally"
13173 clause.
13174
13175 traceback.tb_next
13176
13177 The special writable attribute "tb_next" is the next level in the
13178 stack trace (towards the frame where the exception occurred), or
13179 "None" if there is no next level.
13180
13181 Changed in version 3.7: This attribute is now writable
13182
13183
13184 Slice objects
13185 -------------
13186
13187 Slice objects are used to represent slices for "__getitem__()"
13188 methods. They are also created by the built-in "slice()" function.
13189
13190 Special read-only attributes: "start" is the lower bound; "stop" is
13191 the upper bound; "step" is the step value; each is "None" if omitted.
13192 These attributes can have any type.
13193
13194 Slice objects support one method:
13195
13196 slice.indices(self, length)
13197
13198 This method takes a single integer argument *length* and computes
13199 information about the slice that the slice object would describe if
13200 applied to a sequence of *length* items. It returns a tuple of
13201 three integers; respectively these are the *start* and *stop*
13202 indices and the *step* or stride length of the slice. Missing or
13203 out-of-bounds indices are handled in a manner consistent with
13204 regular slices.
13205
13206
13207 Static method objects
13208 ---------------------
13209
13210 Static method objects provide a way of defeating the transformation of
13211 function objects to method objects described above. A static method
13212 object is a wrapper around any other object, usually a user-defined
13213 method object. When a static method object is retrieved from a class
13214 or a class instance, the object actually returned is the wrapped
13215 object, which is not subject to any further transformation. Static
13216 method objects are also callable. Static method objects are created by
13217 the built-in "staticmethod()" constructor.
13218
13219
13220 Class method objects
13221 --------------------
13222
13223 A class method object, like a static method object, is a wrapper
13224 around another object that alters the way in which that object is
13225 retrieved from classes and class instances. The behaviour of class
13226 method objects upon such retrieval is described above, under “instance
13227 methods”. Class method objects are created by the built-in
13228 "classmethod()" constructor.
13229 ''',
13230 'typesfunctions': r'''Functions
13231 *********
13232
13233 Function objects are created by function definitions. The only
13234 operation on a function object is to call it: "func(argument-list)".
13235
13236 There are really two flavors of function objects: built-in functions
13237 and user-defined functions. Both support the same operation (to call
13238 the function), but the implementation is different, hence the
13239 different object types.
13240
13241 See Function definitions for more information.
13242 ''',
13243 'typesmapping': r'''Mapping Types — "dict"
13244 **********************
13245
13246 A *mapping* object maps *hashable* values to arbitrary objects.
13247 Mappings are mutable objects. There is currently only one standard
13248 mapping type, the *dictionary*. (For other containers see the built-
13249 in "list", "set", and "tuple" classes, and the "collections" module.)
13250
13251 A dictionary’s keys are *almost* arbitrary values. Values that are
13252 not *hashable*, that is, values containing lists, dictionaries or
13253 other mutable types (that are compared by value rather than by object
13254 identity) may not be used as keys. Values that compare equal (such as
13255 "1", "1.0", and "True") can be used interchangeably to index the same
13256 dictionary entry.
13257
13258 class dict(**kwargs)
13259 class dict(mapping, /, **kwargs)
13260 class dict(iterable, /, **kwargs)
13261
13262 Return a new dictionary initialized from an optional positional
13263 argument and a possibly empty set of keyword arguments.
13264
13265 Dictionaries can be created by several means:
13266
13267 * Use a comma-separated list of "key: value" pairs within braces:
13268 "{'jack': 4098, 'sjoerd': 4127}" or "{4098: 'jack', 4127:
13269 'sjoerd'}"
13270
13271 * Use a dict comprehension: "{}", "{x: x ** 2 for x in range(10)}"
13272
13273 * Use the type constructor: "dict()", "dict([('foo', 100), ('bar',
13274 200)])", "dict(foo=100, bar=200)"
13275
13276 If no positional argument is given, an empty dictionary is created.
13277 If a positional argument is given and it defines a "keys()" method,
13278 a dictionary is created by calling "__getitem__()" on the argument
13279 with each returned key from the method. Otherwise, the positional
13280 argument must be an *iterable* object. Each item in the iterable
13281 must itself be an iterable with exactly two elements. The first
13282 element of each item becomes a key in the new dictionary, and the
13283 second element the corresponding value. If a key occurs more than
13284 once, the last value for that key becomes the corresponding value
13285 in the new dictionary.
13286
13287 If keyword arguments are given, the keyword arguments and their
13288 values are added to the dictionary created from the positional
13289 argument. If a key being added is already present, the value from
13290 the keyword argument replaces the value from the positional
13291 argument.
13292
13293 Dictionaries compare equal if and only if they have the same "(key,
13294 value)" pairs (regardless of ordering). Order comparisons (‘<’,
13295 ‘<=’, ‘>=’, ‘>’) raise "TypeError". To illustrate dictionary
13296 creation and equality, the following examples all return a
13297 dictionary equal to "{"one": 1, "two": 2, "three": 3}":
13298
13299 >>> a = dict(one=1, two=2, three=3)
13300 >>> b = {'one': 1, 'two': 2, 'three': 3}
13301 >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
13302 >>> d = dict([('two', 2), ('one', 1), ('three', 3)])
13303 >>> e = dict({'three': 3, 'one': 1, 'two': 2})
13304 >>> f = dict({'one': 1, 'three': 3}, two=2)
13305 >>> a == b == c == d == e == f
13306 True
13307
13308 Providing keyword arguments as in the first example only works for
13309 keys that are valid Python identifiers. Otherwise, any valid keys
13310 can be used.
13311
13312 Dictionaries preserve insertion order. Note that updating a key
13313 does not affect the order. Keys added after deletion are inserted
13314 at the end.
13315
13316 >>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
13317 >>> d
13318 {'one': 1, 'two': 2, 'three': 3, 'four': 4}
13319 >>> list(d)
13320 ['one', 'two', 'three', 'four']
13321 >>> list(d.values())
13322 [1, 2, 3, 4]
13323 >>> d["one"] = 42
13324 >>> d
13325 {'one': 42, 'two': 2, 'three': 3, 'four': 4}
13326 >>> del d["two"]
13327 >>> d["two"] = None
13328 >>> d
13329 {'one': 42, 'three': 3, 'four': 4, 'two': None}
13330
13331 Changed in version 3.7: Dictionary order is guaranteed to be
13332 insertion order. This behavior was an implementation detail of
13333 CPython from 3.6.
13334
13335 Dictionaries are generic over two types, signifying (respectively)
13336 the types of the dictionary’s keys and values.
13337
13338 These are the operations that dictionaries support (and therefore,
13339 custom mapping types should support too):
13340
13341 list(d)
13342
13343 Return a list of all the keys used in the dictionary *d*.
13344
13345 len(d)
13346
13347 Return the number of items in the dictionary *d*.
13348
13349 d[key]
13350
13351 Return the item of *d* with key *key*. Raises a "KeyError" if
13352 *key* is not in the map.
13353
13354 If a subclass of dict defines a method "__missing__()" and *key*
13355 is not present, the "d[key]" operation calls that method with
13356 the key *key* as argument. The "d[key]" operation then returns
13357 or raises whatever is returned or raised by the
13358 "__missing__(key)" call. No other operations or methods invoke
13359 "__missing__()". If "__missing__()" is not defined, "KeyError"
13360 is raised. "__missing__()" must be a method; it cannot be an
13361 instance variable:
13362
13363 >>> class Counter(dict):
13364 ... def __missing__(self, key):
13365 ... return 0
13366 ...
13367 >>> c = Counter()
13368 >>> c['red']
13369 0
13370 >>> c['red'] += 1
13371 >>> c['red']
13372 1
13373
13374 The example above shows part of the implementation of
13375 "collections.Counter". A different "__missing__()" method is
13376 used by "collections.defaultdict".
13377
13378 d[key] = value
13379
13380 Set "d[key]" to *value*.
13381
13382 del d[key]
13383
13384 Remove "d[key]" from *d*. Raises a "KeyError" if *key* is not
13385 in the map.
13386
13387 key in d
13388
13389 Return "True" if *d* has a key *key*, else "False".
13390
13391 key not in d
13392
13393 Equivalent to "not key in d".
13394
13395 iter(d)
13396
13397 Return an iterator over the keys of the dictionary. This is a
13398 shortcut for "iter(d.keys())".
13399
13400 clear()
13401
13402 Remove all items from the dictionary.
13403
13404 copy()
13405
13406 Return a shallow copy of the dictionary.
13407
13408 classmethod fromkeys(iterable, value=None, /)
13409
13410 Create a new dictionary with keys from *iterable* and values set
13411 to *value*.
13412
13413 "fromkeys()" is a class method that returns a new dictionary.
13414 *value* defaults to "None". All of the values refer to just a
13415 single instance, so it generally doesn’t make sense for *value*
13416 to be a mutable object such as an empty list. To get distinct
13417 values, use a dict comprehension instead.
13418
13419 get(key, default=None, /)
13420
13421 Return the value for *key* if *key* is in the dictionary, else
13422 *default*. If *default* is not given, it defaults to "None", so
13423 that this method never raises a "KeyError".
13424
13425 items()
13426
13427 Return a new view of the dictionary’s items ("(key, value)"
13428 pairs). See the documentation of view objects.
13429
13430 keys()
13431
13432 Return a new view of the dictionary’s keys. See the
13433 documentation of view objects.
13434
13435 pop(key, /)
13436 pop(key, default, /)
13437
13438 If *key* is in the dictionary, remove it and return its value,
13439 else return *default*. If *default* is not given and *key* is
13440 not in the dictionary, a "KeyError" is raised.
13441
13442 popitem()
13443
13444 Remove and return a "(key, value)" pair from the dictionary.
13445 Pairs are returned in LIFO (last-in, first-out) order.
13446
13447 "popitem()" is useful to destructively iterate over a
13448 dictionary, as often used in set algorithms. If the dictionary
13449 is empty, calling "popitem()" raises a "KeyError".
13450
13451 Changed in version 3.7: LIFO order is now guaranteed. In prior
13452 versions, "popitem()" would return an arbitrary key/value pair.
13453
13454 reversed(d)
13455
13456 Return a reverse iterator over the keys of the dictionary. This
13457 is a shortcut for "reversed(d.keys())".
13458
13459 Added in version 3.8.
13460
13461 setdefault(key, default=None, /)
13462
13463 If *key* is in the dictionary, return its value. If not, insert
13464 *key* with a value of *default* and return *default*. *default*
13465 defaults to "None".
13466
13467 update(**kwargs)
13468 update(mapping, /, **kwargs)
13469 update(iterable, /, **kwargs)
13470
13471 Update the dictionary with the key/value pairs from *mapping* or
13472 *iterable* and *kwargs*, overwriting existing keys. Return
13473 "None".
13474
13475 "update()" accepts either another object with a "keys()" method
13476 (in which case "__getitem__()" is called with every key returned
13477 from the method) or an iterable of key/value pairs (as tuples or
13478 other iterables of length two). If keyword arguments are
13479 specified, the dictionary is then updated with those key/value
13480 pairs: "d.update(red=1, blue=2)".
13481
13482 values()
13483
13484 Return a new view of the dictionary’s values. See the
13485 documentation of view objects.
13486
13487 An equality comparison between one "dict.values()" view and
13488 another will always return "False". This also applies when
13489 comparing "dict.values()" to itself:
13490
13491 >>> d = {'a': 1}
13492 >>> d.values() == d.values()
13493 False
13494
13495 d | other
13496
13497 Create a new dictionary with the merged keys and values of *d*
13498 and *other*, which must both be dictionaries. The values of
13499 *other* take priority when *d* and *other* share keys.
13500
13501 Added in version 3.9.
13502
13503 d |= other
13504
13505 Update the dictionary *d* with keys and values from *other*,
13506 which may be either a *mapping* or an *iterable* of key/value
13507 pairs. The values of *other* take priority when *d* and *other*
13508 share keys.
13509
13510 Added in version 3.9.
13511
13512 Dictionaries and dictionary views are reversible.
13513
13514 >>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
13515 >>> d
13516 {'one': 1, 'two': 2, 'three': 3, 'four': 4}
13517 >>> list(reversed(d))
13518 ['four', 'three', 'two', 'one']
13519 >>> list(reversed(d.values()))
13520 [4, 3, 2, 1]
13521 >>> list(reversed(d.items()))
13522 [('four', 4), ('three', 3), ('two', 2), ('one', 1)]
13523
13524 Changed in version 3.8: Dictionaries are now reversible.
13525
13526 See also:
13527
13528 "types.MappingProxyType" can be used to create a read-only view of a
13529 "dict".
13530
13531 See also:
13532
13533 For detailed information on thread-safety guarantees for "dict"
13534 objects, see Thread safety for dict objects.
13535
13536
13537 Dictionary view objects
13538 =======================
13539
13540 The objects returned by "dict.keys()", "dict.values()" and
13541 "dict.items()" are *view objects*. They provide a dynamic view on the
13542 dictionary’s entries, which means that when the dictionary changes,
13543 the view reflects these changes.
13544
13545 Dictionary views can be iterated over to yield their respective data,
13546 and support membership tests:
13547
13548 len(dictview)
13549
13550 Return the number of entries in the dictionary.
13551
13552 iter(dictview)
13553
13554 Return an iterator over the keys, values or items (represented as
13555 tuples of "(key, value)") in the dictionary.
13556
13557 Keys and values are iterated over in insertion order. This allows
13558 the creation of "(value, key)" pairs using "zip()": "pairs =
13559 zip(d.values(), d.keys())". Another way to create the same list is
13560 "pairs = [(v, k) for (k, v) in d.items()]".
13561
13562 Iterating views while adding or deleting entries in the dictionary
13563 may raise a "RuntimeError" or fail to iterate over all entries.
13564
13565 Changed in version 3.7: Dictionary order is guaranteed to be
13566 insertion order.
13567
13568 x in dictview
13569
13570 Return "True" if *x* is in the underlying dictionary’s keys, values
13571 or items (in the latter case, *x* should be a "(key, value)"
13572 tuple).
13573
13574 reversed(dictview)
13575
13576 Return a reverse iterator over the keys, values or items of the
13577 dictionary. The view will be iterated in reverse order of the
13578 insertion.
13579
13580 Changed in version 3.8: Dictionary views are now reversible.
13581
13582 dictview.mapping
13583
13584 Return a "types.MappingProxyType" that wraps the original
13585 dictionary to which the view refers.
13586
13587 Added in version 3.10.
13588
13589 Keys views are set-like since their entries are unique and *hashable*.
13590 Items views also have set-like operations since the (key, value) pairs
13591 are unique and the keys are hashable. If all values in an items view
13592 are hashable as well, then the items view can interoperate with other
13593 sets. (Values views are not treated as set-like since the entries are
13594 generally not unique.) For set-like views, all of the operations
13595 defined for the abstract base class "collections.abc.Set" are
13596 available (for example, "==", "<", or "^"). While using set
13597 operators, set-like views accept any iterable as the other operand,
13598 unlike sets which only accept sets as the input.
13599
13600 An example of dictionary view usage:
13601
13602 >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
13603 >>> keys = dishes.keys()
13604 >>> values = dishes.values()
13605
13606 >>> # iteration
13607 >>> n = 0
13608 >>> for val in values:
13609 ... n += val
13610 ...
13611 >>> print(n)
13612 504
13613
13614 >>> # keys and values are iterated over in the same order (insertion order)
13615 >>> list(keys)
13616 ['eggs', 'sausage', 'bacon', 'spam']
13617 >>> list(values)
13618 [2, 1, 1, 500]
13619
13620 >>> # view objects are dynamic and reflect dict changes
13621 >>> del dishes['eggs']
13622 >>> del dishes['sausage']
13623 >>> list(keys)
13624 ['bacon', 'spam']
13625
13626 >>> # set operations
13627 >>> keys & {'eggs', 'bacon', 'salad'}
13628 {'bacon'}
13629 >>> keys ^ {'sausage', 'juice'} == {'juice', 'sausage', 'bacon', 'spam'}
13630 True
13631 >>> keys | ['juice', 'juice', 'juice'] == {'bacon', 'spam', 'juice'}
13632 True
13633
13634 >>> # get back a read-only proxy for the original dictionary
13635 >>> values.mapping
13636 mappingproxy({'bacon': 1, 'spam': 500})
13637 >>> values.mapping['spam']
13638 500
13639 ''',
13640 'typesmethods': r'''Methods
13641 *******
13642
13643 Methods are functions that are called using the attribute notation.
13644 There are two flavors: built-in methods (such as "append()" on lists)
13645 and class instance method. Built-in methods are described with the
13646 types that support them.
13647
13648 If you access a method (a function defined in a class namespace)
13649 through an instance, you get a special object: a *bound method* (also
13650 called instance method) object. When called, it will add the "self"
13651 argument to the argument list. Bound methods have two special read-
13652 only attributes: "m.__self__" is the object on which the method
13653 operates, and "m.__func__" is the function implementing the method.
13654 Calling "m(arg-1, arg-2, ..., arg-n)" is completely equivalent to
13655 calling "m.__func__(m.__self__, arg-1, arg-2, ..., arg-n)".
13656
13657 Like function objects, bound method objects support getting arbitrary
13658 attributes. However, since method attributes are actually stored on
13659 the underlying function object ("method.__func__"), setting method
13660 attributes on bound methods is disallowed. Attempting to set an
13661 attribute on a method results in an "AttributeError" being raised. In
13662 order to set a method attribute, you need to explicitly set it on the
13663 underlying function object:
13664
13665 >>> class C:
13666 ... def method(self):
13667 ... pass
13668 ...
13669 >>> c = C()
13670 >>> c.method.whoami = 'my name is method' # can't set on the method
13671 Traceback (most recent call last):
13672 File "<stdin>", line 1, in <module>
13673 AttributeError: 'method' object has no attribute 'whoami'
13674 >>> c.method.__func__.whoami = 'my name is method'
13675 >>> c.method.whoami
13676 'my name is method'
13677
13678 See Instance methods for more information.
13679 ''',
13680 'typesmodules': r'''Modules
13681 *******
13682
13683 The only special operation on a module is attribute access: "m.name",
13684 where *m* is a module and *name* accesses a name defined in *m*’s
13685 symbol table. Module attributes can be assigned to. (Note that the
13686 "import" statement is not, strictly speaking, an operation on a module
13687 object; "import foo" does not require a module object named *foo* to
13688 exist, rather it requires an (external) *definition* for a module
13689 named *foo* somewhere.)
13690
13691 A special attribute of every module is "__dict__". This is the
13692 dictionary containing the module’s symbol table. Modifying this
13693 dictionary will actually change the module’s symbol table, but direct
13694 assignment to the "__dict__" attribute is not possible (you can write
13695 "m.__dict__['a'] = 1", which defines "m.a" to be "1", but you can’t
13696 write "m.__dict__ = {}"). Modifying "__dict__" directly is not
13697 recommended.
13698
13699 Modules built into the interpreter are written like this: "<module
13700 'sys' (built-in)>". If loaded from a file, they are written as
13701 "<module 'os' from '/usr/local/lib/pythonX.Y/os.pyc'>".
13702 ''',
13703 'typesseq': r'''Sequence Types — "list", "tuple", "range"
13704 *****************************************
13705
13706 There are three basic sequence types: lists, tuples, and range
13707 objects. Additional sequence types tailored for processing of binary
13708 data and text strings are described in dedicated sections.
13709
13710
13711 Common Sequence Operations
13712 ==========================
13713
13714 The operations in the following table are supported by most sequence
13715 types, both mutable and immutable. The "collections.abc.Sequence" ABC
13716 is provided to make it easier to correctly implement these operations
13717 on custom sequence types.
13718
13719 This table lists the sequence operations sorted in ascending priority.
13720 In the table, *s* and *t* are sequences of the same type, *n*, *i*,
13721 *j* and *k* are integers and *x* is an arbitrary object that meets any
13722 type and value restrictions imposed by *s*.
13723
13724 The "in" and "not in" operations have the same priorities as the
13725 comparison operations. The "+" (concatenation) and "*" (repetition)
13726 operations have the same priority as the corresponding numeric
13727 operations. [3]
13728
13729 +----------------------------+----------------------------------+------------+
13730 | Operation | Result | Notes |
13731 |============================|==================================|============|
13732 | "x in s" | "True" if an item of *s* is | (1) |
13733 | | equal to *x*, else "False" | |
13734 +----------------------------+----------------------------------+------------+
13735 | "x not in s" | "False" if an item of *s* is | (1) |
13736 | | equal to *x*, else "True" | |
13737 +----------------------------+----------------------------------+------------+
13738 | "s + t" | the concatenation of *s* and *t* | (6)(7) |
13739 +----------------------------+----------------------------------+------------+
13740 | "s * n" or "n * s" | equivalent to adding *s* to | (2)(7) |
13741 | | itself *n* times | |
13742 +----------------------------+----------------------------------+------------+
13743 | "s[i]" | *i*th item of *s*, origin 0 | (3)(8) |
13744 +----------------------------+----------------------------------+------------+
13745 | "s[i:j]" | slice of *s* from *i* to *j* | (3)(4) |
13746 +----------------------------+----------------------------------+------------+
13747 | "s[i:j:k]" | slice of *s* from *i* to *j* | (3)(5) |
13748 | | with step *k* | |
13749 +----------------------------+----------------------------------+------------+
13750 | "len(s)" | length of *s* | |
13751 +----------------------------+----------------------------------+------------+
13752 | "min(s)" | smallest item of *s* | |
13753 +----------------------------+----------------------------------+------------+
13754 | "max(s)" | largest item of *s* | |
13755 +----------------------------+----------------------------------+------------+
13756
13757 Sequences of the same type also support comparisons. In particular,
13758 tuples and lists are compared lexicographically by comparing
13759 corresponding elements. This means that to compare equal, every
13760 element must compare equal and the two sequences must be of the same
13761 type and have the same length. (For full details see Comparisons in
13762 the language reference.)
13763
13764 Forward and reversed iterators over mutable sequences access values
13765 using an index. That index will continue to march forward (or
13766 backward) even if the underlying sequence is mutated. The iterator
13767 terminates only when an "IndexError" or a "StopIteration" is
13768 encountered (or when the index drops below zero).
13769
13770 Notes:
13771
13772 1. While the "in" and "not in" operations are used only for simple
13773 containment testing in the general case, some specialised sequences
13774 (such as "str", "bytes" and "bytearray") also use them for
13775 subsequence testing:
13776
13777 >>> "gg" in "eggs"
13778 True
13779
13780 2. Values of *n* less than "0" are treated as "0" (which yields an
13781 empty sequence of the same type as *s*). Note that items in the
13782 sequence *s* are not copied; they are referenced multiple times.
13783 This often haunts new Python programmers; consider:
13784
13785 >>> lists = [[]] * 3
13786 >>> lists
13787 [[], [], []]
13788 >>> lists[0].append(3)
13789 >>> lists
13790 [[3], [3], [3]]
13791
13792 What has happened is that "[[]]" is a one-element list containing
13793 an empty list, so all three elements of "[[]] * 3" are references
13794 to this single empty list. Modifying any of the elements of
13795 "lists" modifies this single list. You can create a list of
13796 different lists this way:
13797
13798 >>> lists = [[] for i in range(3)]
13799 >>> lists[0].append(3)
13800 >>> lists[1].append(5)
13801 >>> lists[2].append(7)
13802 >>> lists
13803 [[3], [5], [7]]
13804
13805 Further explanation is available in the FAQ entry How do I create a
13806 multidimensional list?.
13807
13808 3. If *i* or *j* is negative, the index is relative to the end of
13809 sequence *s*: "len(s) + i" or "len(s) + j" is substituted. But
13810 note that "-0" is still "0".
13811
13812 4. The slice of *s* from *i* to *j* is defined as the sequence of
13813 items with index *k* such that "i <= k < j".
13814
13815 * If *i* is omitted or "None", use "0".
13816
13817 * If *j* is omitted or "None", use "len(s)".
13818
13819 * If *i* or *j* is less than "-len(s)", use "0".
13820
13821 * If *i* or *j* is greater than "len(s)", use "len(s)".
13822
13823 * If *i* is greater than or equal to *j*, the slice is empty.
13824
13825 5. The slice of *s* from *i* to *j* with step *k* is defined as the
13826 sequence of items with index "x = i + n*k" such that "0 <= n <
13827 (j-i)/k". In other words, the indices are "i", "i+k", "i+2*k",
13828 "i+3*k" and so on, stopping when *j* is reached (but never
13829 including *j*). When *k* is positive, *i* and *j* are reduced to
13830 "len(s)" if they are greater. When *k* is negative, *i* and *j* are
13831 reduced to "len(s) - 1" if they are greater. If *i* or *j* are
13832 omitted or "None", they become “end” values (which end depends on
13833 the sign of *k*). Note, *k* cannot be zero. If *k* is "None", it
13834 is treated like "1".
13835
13836 6. Concatenating immutable sequences always results in a new object.
13837 This means that building up a sequence by repeated concatenation
13838 will have a quadratic runtime cost in the total sequence length.
13839 To get a linear runtime cost, you must switch to one of the
13840 alternatives below:
13841
13842 * if concatenating "str" objects, you can build a list and use
13843 "str.join()" at the end or else write to an "io.StringIO"
13844 instance and retrieve its value when complete
13845
13846 * if concatenating "bytes" objects, you can similarly use
13847 "bytes.join()" or "io.BytesIO", or you can do in-place
13848 concatenation with a "bytearray" object. "bytearray" objects are
13849 mutable and have an efficient overallocation mechanism
13850
13851 * if concatenating "tuple" objects, extend a "list" instead
13852
13853 * for other types, investigate the relevant class documentation
13854
13855 7. Some sequence types (such as "range") only support item sequences
13856 that follow specific patterns, and hence don’t support sequence
13857 concatenation or repetition.
13858
13859 8. An "IndexError" is raised if *i* is outside the sequence range.
13860
13861 -[ Sequence Methods ]-
13862
13863 Sequence types also support the following methods:
13864
13865 sequence.count(value, /)
13866
13867 Return the total number of occurrences of *value* in *sequence*.
13868
13869 sequence.index(value[, start[, stop]])
13870
13871 Return the index of the first occurrence of *value* in *sequence*.
13872
13873 Raises "ValueError" if *value* is not found in *sequence*.
13874
13875 The *start* or *stop* arguments allow for efficient searching of
13876 subsections of the sequence, beginning at *start* and ending at
13877 *stop*. This is roughly equivalent to "start +
13878 sequence[start:stop].index(value)", only without copying any data.
13879
13880 Caution:
13881
13882 Not all sequence types support passing the *start* and *stop*
13883 arguments.
13884
13885
13886 Immutable Sequence Types
13887 ========================
13888
13889 The only operation that immutable sequence types generally implement
13890 that is not also implemented by mutable sequence types is support for
13891 the "hash()" built-in.
13892
13893 This support allows immutable sequences, such as "tuple" instances, to
13894 be used as "dict" keys and stored in "set" and "frozenset" instances.
13895
13896 Attempting to hash an immutable sequence that contains unhashable
13897 values will result in "TypeError".
13898
13899
13900 Mutable Sequence Types
13901 ======================
13902
13903 The operations in the following table are defined on mutable sequence
13904 types. The "collections.abc.MutableSequence" ABC is provided to make
13905 it easier to correctly implement these operations on custom sequence
13906 types.
13907
13908 In the table *s* is an instance of a mutable sequence type, *t* is any
13909 iterable object and *x* is an arbitrary object that meets any type and
13910 value restrictions imposed by *s* (for example, "bytearray" only
13911 accepts integers that meet the value restriction "0 <= x <= 255").
13912
13913 +--------------------------------+----------------------------------+-----------------------+
13914 | Operation | Result | Notes |
13915 |================================|==================================|=======================|
13916 | "s[i] = x" | item *i* of *s* is replaced by | |
13917 | | *x* | |
13918 +--------------------------------+----------------------------------+-----------------------+
13919 | "del s[i]" | removes item *i* of *s* | |
13920 +--------------------------------+----------------------------------+-----------------------+
13921 | "s[i:j] = t" | slice of *s* from *i* to *j* is | |
13922 | | replaced by the contents of the | |
13923 | | iterable *t* | |
13924 +--------------------------------+----------------------------------+-----------------------+
13925 | "del s[i:j]" | removes the elements of "s[i:j]" | |
13926 | | from the list (same as "s[i:j] = | |
13927 | | []") | |
13928 +--------------------------------+----------------------------------+-----------------------+
13929 | "s[i:j:k] = t" | the elements of "s[i:j:k]" are | (1) |
13930 | | replaced by those of *t* | |
13931 +--------------------------------+----------------------------------+-----------------------+
13932 | "del s[i:j:k]" | removes the elements of | |
13933 | | "s[i:j:k]" from the list | |
13934 +--------------------------------+----------------------------------+-----------------------+
13935 | "s += t" | extends *s* with the contents of | |
13936 | | *t* (for the most part the same | |
13937 | | as "s[len(s):len(s)] = t") | |
13938 +--------------------------------+----------------------------------+-----------------------+
13939 | "s *= n" | updates *s* with its contents | (2) |
13940 | | repeated *n* times | |
13941 +--------------------------------+----------------------------------+-----------------------+
13942
13943 Notes:
13944
13945 1. If *k* is not equal to "1", *t* must have the same length as the
13946 slice it is replacing.
13947
13948 2. The value *n* is an integer, or an object implementing
13949 "__index__()". Zero and negative values of *n* clear the sequence.
13950 Items in the sequence are not copied; they are referenced multiple
13951 times, as explained for "s * n" under Common Sequence Operations.
13952
13953 -[ Mutable Sequence Methods ]-
13954
13955 Mutable sequence types also support the following methods:
13956
13957 sequence.append(value, /)
13958
13959 Append *value* to the end of the sequence. This is equivalent to
13960 writing "seq[len(seq):len(seq)] = [value]".
13961
13962 sequence.clear()
13963
13964 Added in version 3.3.
13965
13966 Remove all items from *sequence*. This is equivalent to writing
13967 "del sequence[:]".
13968
13969 sequence.copy()
13970
13971 Added in version 3.3.
13972
13973 Create a shallow copy of *sequence*. This is equivalent to writing
13974 "sequence[:]".
13975
13976 Hint:
13977
13978 The "copy()" method is not part of the "MutableSequence" "ABC",
13979 but most concrete mutable sequence types provide it.
13980
13981 sequence.extend(iterable, /)
13982
13983 Extend *sequence* with the contents of *iterable*. For the most
13984 part, this is the same as writing "seq[len(seq):len(seq)] =
13985 iterable".
13986
13987 sequence.insert(index, value, /)
13988
13989 Insert *value* into *sequence* at the given *index*. This is
13990 equivalent to writing "sequence[index:index] = [value]".
13991
13992 sequence.pop(index=-1, /)
13993
13994 Retrieve the item at *index* and also removes it from *sequence*.
13995 By default, the last item in *sequence* is removed and returned.
13996
13997 sequence.remove(value, /)
13998
13999 Remove the first item from *sequence* where "sequence[i] == value".
14000
14001 Raises "ValueError" if *value* is not found in *sequence*.
14002
14003 sequence.reverse()
14004
14005 Reverse the items of *sequence* in place. This method maintains
14006 economy of space when reversing a large sequence. To remind users
14007 that it operates by side-effect, it returns "None".
14008
14009
14010 Lists
14011 =====
14012
14013 Lists are mutable sequences, typically used to store collections of
14014 homogeneous items (where the precise degree of similarity will vary by
14015 application).
14016
14017 class list(iterable=(), /)
14018
14019 Lists may be constructed in several ways:
14020
14021 * Using a pair of square brackets to denote the empty list: "[]"
14022
14023 * Using square brackets, separating items with commas: "[a]", "[a,
14024 b, c]"
14025
14026 * Using a list comprehension: "[x for x in iterable]"
14027
14028 * Using the type constructor: "list()" or "list(iterable)"
14029
14030 The constructor builds a list whose items are the same and in the
14031 same order as *iterable*’s items. *iterable* may be either a
14032 sequence, a container that supports iteration, or an iterator
14033 object. If *iterable* is already a list, a copy is made and
14034 returned, similar to "iterable[:]". For example, "list('abc')"
14035 returns "['a', 'b', 'c']" and "list( (1, 2, 3) )" returns "[1, 2,
14036 3]". If no argument is given, the constructor creates a new empty
14037 list, "[]".
14038
14039 Many other operations also produce lists, including the "sorted()"
14040 built-in.
14041
14042 Lists are generic over the types of their items.
14043
14044 Lists implement all of the common and mutable sequence operations.
14045 Lists also provide the following additional method:
14046
14047 sort(*, key=None, reverse=False)
14048
14049 This method sorts the list in place, using only "<" comparisons
14050 between items. Exceptions are not suppressed - if any comparison
14051 operations fail, the entire sort operation will fail (and the
14052 list will likely be left in a partially modified state).
14053
14054 "sort()" accepts two arguments that can only be passed by
14055 keyword (keyword-only arguments):
14056
14057 *key* specifies a function of one argument that is used to
14058 extract a comparison key from each list element (for example,
14059 "key=str.lower"). The key corresponding to each item in the list
14060 is calculated once and then used for the entire sorting process.
14061 The default value of "None" means that list items are sorted
14062 directly without calculating a separate key value.
14063
14064 The "functools.cmp_to_key()" utility is available to convert a
14065 2.x style *cmp* function to a *key* function.
14066
14067 *reverse* is a boolean value. If set to "True", then the list
14068 elements are sorted as if each comparison were reversed.
14069
14070 This method modifies the sequence in place for economy of space
14071 when sorting a large sequence. To remind users that it operates
14072 by side effect, it does not return the sorted sequence (use
14073 "sorted()" to explicitly request a new sorted list instance).
14074
14075 The "sort()" method is guaranteed to be stable. A sort is
14076 stable if it guarantees not to change the relative order of
14077 elements that compare equal — this is helpful for sorting in
14078 multiple passes (for example, sort by department, then by salary
14079 grade).
14080
14081 For sorting examples and a brief sorting tutorial, see Sorting
14082 Techniques.
14083
14084 **CPython implementation detail:** While a list is being sorted,
14085 the effect of attempting to mutate, or even inspect, the list is
14086 undefined. The C implementation of Python makes the list appear
14087 empty for the duration, and raises "ValueError" if it can detect
14088 that the list has been mutated during a sort.
14089
14090 See also:
14091
14092 For detailed information on thread-safety guarantees for "list"
14093 objects, see Thread safety for list objects.
14094
14095
14096 Tuples
14097 ======
14098
14099 Tuples are immutable sequences, typically used to store collections of
14100 heterogeneous data (such as the 2-tuples produced by the "enumerate()"
14101 built-in). Tuples are also used for cases where an immutable sequence
14102 of homogeneous data is needed (such as allowing storage in a "set" or
14103 "dict" instance).
14104
14105 class tuple(iterable=(), /)
14106
14107 Tuples may be constructed in a number of ways:
14108
14109 * Using a pair of parentheses to denote the empty tuple: "()"
14110
14111 * Using a trailing comma for a singleton tuple: "a," or "(a,)"
14112
14113 * Separating items with commas: "a, b, c" or "(a, b, c)"
14114
14115 * Using the "tuple()" built-in: "tuple()" or "tuple(iterable)"
14116
14117 The constructor builds a tuple whose items are the same and in the
14118 same order as *iterable*’s items. *iterable* may be either a
14119 sequence, a container that supports iteration, or an iterator
14120 object. If *iterable* is already a tuple, it is returned
14121 unchanged. For example, "tuple('abc')" returns "('a', 'b', 'c')"
14122 and "tuple( [1, 2, 3] )" returns "(1, 2, 3)". If no argument is
14123 given, the constructor creates a new empty tuple, "()".
14124
14125 Note that it is actually the comma which makes a tuple, not the
14126 parentheses. The parentheses are optional, except in the empty
14127 tuple case, or when they are needed to avoid syntactic ambiguity.
14128 For example, "f(a, b, c)" is a function call with three arguments,
14129 while "f((a, b, c))" is a function call with a 3-tuple as the sole
14130 argument.
14131
14132 Tuples implement all of the common sequence operations.
14133
14134 Tuples are generic over the types of their contents. For more
14135 information, refer to the typing documentation on annotating
14136 tuples.
14137
14138 For heterogeneous collections of data where access by name is clearer
14139 than access by index, "collections.namedtuple()" may be a more
14140 appropriate choice than a simple tuple object.
14141
14142
14143 Ranges
14144 ======
14145
14146 The "range" type represents an immutable sequence of numbers and is
14147 commonly used for looping a specific number of times in "for" loops.
14148
14149 class range(stop, /)
14150 class range(start, stop, step=1, /)
14151
14152 The arguments to the range constructor must be integers (either
14153 built-in "int" or any object that implements the "__index__()"
14154 special method). If the *step* argument is omitted, it defaults to
14155 "1". If the *start* argument is omitted, it defaults to "0". If
14156 *step* is zero, "ValueError" is raised.
14157
14158 For a positive *step*, the contents of a range "r" are determined
14159 by the formula "r[i] = start + step*i" where "i >= 0" and "r[i] <
14160 stop".
14161
14162 For a negative *step*, the contents of the range are still
14163 determined by the formula "r[i] = start + step*i", but the
14164 constraints are "i >= 0" and "r[i] > stop".
14165
14166 A range object will be empty if "r[0]" does not meet the value
14167 constraint. Ranges do support negative indices, but these are
14168 interpreted as indexing from the end of the sequence determined by
14169 the positive indices.
14170
14171 Ranges containing absolute values larger than "sys.maxsize" are
14172 permitted but some features (such as "len()") may raise
14173 "OverflowError".
14174
14175 Range examples:
14176
14177 >>> list(range(10))
14178 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
14179 >>> list(range(1, 11))
14180 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
14181 >>> list(range(0, 30, 5))
14182 [0, 5, 10, 15, 20, 25]
14183 >>> list(range(0, 10, 3))
14184 [0, 3, 6, 9]
14185 >>> list(range(0, -10, -1))
14186 [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
14187 >>> list(range(0))
14188 []
14189 >>> list(range(1, 0))
14190 []
14191
14192 Ranges implement all of the common sequence operations except
14193 concatenation and repetition (due to the fact that range objects
14194 can only represent sequences that follow a strict pattern and
14195 repetition and concatenation will usually violate that pattern).
14196
14197 start
14198
14199 The value of the *start* parameter (or "0" if the parameter was
14200 not supplied)
14201
14202 stop
14203
14204 The value of the *stop* parameter
14205
14206 step
14207
14208 The value of the *step* parameter (or "1" if the parameter was
14209 not supplied)
14210
14211 The advantage of the "range" type over a regular "list" or "tuple" is
14212 that a "range" object will always take the same (small) amount of
14213 memory, no matter the size of the range it represents (as it only
14214 stores the "start", "stop" and "step" values, calculating individual
14215 items and subranges as needed).
14216
14217 Range objects implement the "collections.abc.Sequence" ABC, and
14218 provide features such as containment tests, element index lookup,
14219 slicing and support for negative indices (see Sequence Types — list,
14220 tuple, range):
14221
14222 >>> r = range(0, 20, 2)
14223 >>> r
14224 range(0, 20, 2)
14225 >>> 11 in r
14226 False
14227 >>> 10 in r
14228 True
14229 >>> r.index(10)
14230 5
14231 >>> r[5]
14232 10
14233 >>> r[:5]
14234 range(0, 10, 2)
14235 >>> r[-1]
14236 18
14237
14238 Testing range objects for equality with "==" and "!=" compares them as
14239 sequences. That is, two range objects are considered equal if they
14240 represent the same sequence of values. (Note that two range objects
14241 that compare equal might have different "start", "stop" and "step"
14242 attributes, for example "range(0) == range(2, 1, 3)" or "range(0, 3,
14243 2) == range(0, 4, 2)".)
14244
14245 Changed in version 3.2: Implement the Sequence ABC. Support slicing
14246 and negative indices. Test "int" objects for membership in constant
14247 time instead of iterating through all items.
14248
14249 Changed in version 3.3: Define ‘==’ and ‘!=’ to compare range objects
14250 based on the sequence of values they define (instead of comparing
14251 based on object identity).Added the "start", "stop" and "step"
14252 attributes.
14253
14254 See also:
14255
14256 * The linspace recipe shows how to implement a lazy version of range
14257 suitable for floating-point applications.
14258 ''',
14259 'typesseq-mutable': r'''Mutable Sequence Types
14260 **********************
14261
14262 The operations in the following table are defined on mutable sequence
14263 types. The "collections.abc.MutableSequence" ABC is provided to make
14264 it easier to correctly implement these operations on custom sequence
14265 types.
14266
14267 In the table *s* is an instance of a mutable sequence type, *t* is any
14268 iterable object and *x* is an arbitrary object that meets any type and
14269 value restrictions imposed by *s* (for example, "bytearray" only
14270 accepts integers that meet the value restriction "0 <= x <= 255").
14271
14272 +--------------------------------+----------------------------------+-----------------------+
14273 | Operation | Result | Notes |
14274 |================================|==================================|=======================|
14275 | "s[i] = x" | item *i* of *s* is replaced by | |
14276 | | *x* | |
14277 +--------------------------------+----------------------------------+-----------------------+
14278 | "del s[i]" | removes item *i* of *s* | |
14279 +--------------------------------+----------------------------------+-----------------------+
14280 | "s[i:j] = t" | slice of *s* from *i* to *j* is | |
14281 | | replaced by the contents of the | |
14282 | | iterable *t* | |
14283 +--------------------------------+----------------------------------+-----------------------+
14284 | "del s[i:j]" | removes the elements of "s[i:j]" | |
14285 | | from the list (same as "s[i:j] = | |
14286 | | []") | |
14287 +--------------------------------+----------------------------------+-----------------------+
14288 | "s[i:j:k] = t" | the elements of "s[i:j:k]" are | (1) |
14289 | | replaced by those of *t* | |
14290 +--------------------------------+----------------------------------+-----------------------+
14291 | "del s[i:j:k]" | removes the elements of | |
14292 | | "s[i:j:k]" from the list | |
14293 +--------------------------------+----------------------------------+-----------------------+
14294 | "s += t" | extends *s* with the contents of | |
14295 | | *t* (for the most part the same | |
14296 | | as "s[len(s):len(s)] = t") | |
14297 +--------------------------------+----------------------------------+-----------------------+
14298 | "s *= n" | updates *s* with its contents | (2) |
14299 | | repeated *n* times | |
14300 +--------------------------------+----------------------------------+-----------------------+
14301
14302 Notes:
14303
14304 1. If *k* is not equal to "1", *t* must have the same length as the
14305 slice it is replacing.
14306
14307 2. The value *n* is an integer, or an object implementing
14308 "__index__()". Zero and negative values of *n* clear the sequence.
14309 Items in the sequence are not copied; they are referenced multiple
14310 times, as explained for "s * n" under Common Sequence Operations.
14311
14312 -[ Mutable Sequence Methods ]-
14313
14314 Mutable sequence types also support the following methods:
14315
14316 sequence.append(value, /)
14317
14318 Append *value* to the end of the sequence. This is equivalent to
14319 writing "seq[len(seq):len(seq)] = [value]".
14320
14321 sequence.clear()
14322
14323 Added in version 3.3.
14324
14325 Remove all items from *sequence*. This is equivalent to writing
14326 "del sequence[:]".
14327
14328 sequence.copy()
14329
14330 Added in version 3.3.
14331
14332 Create a shallow copy of *sequence*. This is equivalent to writing
14333 "sequence[:]".
14334
14335 Hint:
14336
14337 The "copy()" method is not part of the "MutableSequence" "ABC",
14338 but most concrete mutable sequence types provide it.
14339
14340 sequence.extend(iterable, /)
14341
14342 Extend *sequence* with the contents of *iterable*. For the most
14343 part, this is the same as writing "seq[len(seq):len(seq)] =
14344 iterable".
14345
14346 sequence.insert(index, value, /)
14347
14348 Insert *value* into *sequence* at the given *index*. This is
14349 equivalent to writing "sequence[index:index] = [value]".
14350
14351 sequence.pop(index=-1, /)
14352
14353 Retrieve the item at *index* and also removes it from *sequence*.
14354 By default, the last item in *sequence* is removed and returned.
14355
14356 sequence.remove(value, /)
14357
14358 Remove the first item from *sequence* where "sequence[i] == value".
14359
14360 Raises "ValueError" if *value* is not found in *sequence*.
14361
14362 sequence.reverse()
14363
14364 Reverse the items of *sequence* in place. This method maintains
14365 economy of space when reversing a large sequence. To remind users
14366 that it operates by side-effect, it returns "None".
14367 ''',
14368 'unary': r'''Unary arithmetic and bitwise operations
14369 ***************************************
14370
14371 All unary arithmetic and bitwise operations have the same priority:
14372
14373 u_expr: power | "-" u_expr | "+" u_expr | "~" u_expr
14374
14375 The unary "-" (minus) operator yields the negation of its numeric
14376 argument; the operation can be overridden with the "__neg__()" special
14377 method.
14378
14379 The unary "+" (plus) operator yields its numeric argument unchanged;
14380 the operation can be overridden with the "__pos__()" special method.
14381
14382 The unary "~" (invert) operator yields the bitwise inversion of its
14383 integer argument. The bitwise inversion of "x" is defined as
14384 "-(x+1)". It only applies to integral numbers or to custom objects
14385 that override the "__invert__()" special method.
14386
14387 In all three cases, if the argument does not have the proper type, a
14388 "TypeError" exception is raised.
14389 ''',
14390 'while': r'''The "while" statement
14391 *********************
14392
14393 The "while" statement is used for repeated execution as long as an
14394 expression is true:
14395
14396 while_stmt: "while" assignment_expression ":" suite
14397 ["else" ":" suite]
14398
14399 This repeatedly tests the expression and, if it is true, executes the
14400 first suite; if the expression is false (which may be the first time
14401 it is tested) the suite of the "else" clause, if present, is executed
14402 and the loop terminates.
14403
14404 A "break" statement executed in the first suite terminates the loop
14405 without executing the "else" clause’s suite. A "continue" statement
14406 executed in the first suite skips the rest of the suite and goes back
14407 to testing the expression.
14408 ''',
14409 'with': r'''The "with" statement
14410 ********************
14411
14412 The "with" statement is used to wrap the execution of a block with
14413 methods defined by a context manager (see section With Statement
14414 Context Managers). This allows common "try"…"except"…"finally" usage
14415 patterns to be encapsulated for convenient reuse.
14416
14417 with_stmt: "with" ( "(" with_stmt_contents ","? ")" | with_stmt_contents ) ":" suite
14418 with_stmt_contents: with_item ("," with_item)*
14419 with_item: expression ["as" target]
14420
14421 The execution of the "with" statement with one “item” proceeds as
14422 follows:
14423
14424 1. The context expression (the expression given in the "with_item") is
14425 evaluated to obtain a context manager.
14426
14427 2. The context manager’s "__enter__()" is loaded for later use.
14428
14429 3. The context manager’s "__exit__()" is loaded for later use.
14430
14431 4. The context manager’s "__enter__()" method is invoked.
14432
14433 5. If a target was included in the "with" statement, the return value
14434 from "__enter__()" is assigned to it.
14435
14436 Note:
14437
14438 The "with" statement guarantees that if the "__enter__()" method
14439 returns without an error, then "__exit__()" will always be
14440 called. Thus, if an error occurs during the assignment to the
14441 target list, it will be treated the same as an error occurring
14442 within the suite would be. See step 7 below.
14443
14444 6. The suite is executed.
14445
14446 7. The context manager’s "__exit__()" method is invoked. If an
14447 exception caused the suite to be exited, its type, value, and
14448 traceback are passed as arguments to "__exit__()". Otherwise, three
14449 "None" arguments are supplied.
14450
14451 If the suite was exited due to an exception, and the return value
14452 from the "__exit__()" method was false, the exception is reraised.
14453 If the return value was true, the exception is suppressed, and
14454 execution continues with the statement following the "with"
14455 statement.
14456
14457 If the suite was exited for any reason other than an exception, the
14458 return value from "__exit__()" is ignored, and execution proceeds
14459 at the normal location for the kind of exit that was taken.
14460
14461 The following code:
14462
14463 with EXPRESSION as TARGET:
14464 SUITE
14465
14466 is semantically equivalent to:
14467
14468 manager = (EXPRESSION)
14469 enter = manager.__enter__
14470 exit = manager.__exit__
14471 value = enter()
14472 hit_except = False
14473
14474 try:
14475 TARGET = value
14476 SUITE
14477 except:
14478 hit_except = True
14479 if not exit(*sys.exc_info()):
14480 raise
14481 finally:
14482 if not hit_except:
14483 exit(None, None, None)
14484
14485 except that implicit special method lookup is used for "__enter__()"
14486 and "__exit__()".
14487
14488 With more than one item, the context managers are processed as if
14489 multiple "with" statements were nested:
14490
14491 with A() as a, B() as b:
14492 SUITE
14493
14494 is semantically equivalent to:
14495
14496 with A() as a:
14497 with B() as b:
14498 SUITE
14499
14500 You can also write multi-item context managers in multiple lines if
14501 the items are surrounded by parentheses. For example:
14502
14503 with (
14504 A() as a,
14505 B() as b,
14506 ):
14507 SUITE
14508
14509 Changed in version 3.1: Support for multiple context expressions.
14510
14511 Changed in version 3.10: Support for using grouping parentheses to
14512 break the statement in multiple lines.
14513
14514 See also:
14515
14516 **PEP 343** - The “with” statement
14517 The specification, background, and examples for the Python "with"
14518 statement.
14519 ''',
14520 'yield': r'''The "yield" statement
14521 *********************
14522
14523 yield_stmt: yield_expression
14524
14525 A "yield" statement is semantically equivalent to a yield expression.
14526 The "yield" statement can be used to omit the parentheses that would
14527 otherwise be required in the equivalent yield expression statement.
14528 For example, the yield statements
14529
14530 yield <expr>
14531 yield from <expr>
14532
14533 are equivalent to the yield expression statements
14534
14535 (yield <expr>)
14536 (yield from <expr>)
14537
14538 Yield expressions and statements are only used when defining a
14539 *generator* function, and are only used in the body of the generator
14540 function. Using "yield" in a function definition is sufficient to
14541 cause that definition to create a generator function instead of a
14542 normal function.
14543
14544 For full details of "yield" semantics, refer to the Yield expressions
14545 section.
14546 ''',
14547 }