Debian Codegraph @

Lib/pydoc_data/topics.py

raw
1 # Autogenerated by Sphinx on Tue Feb 3 18:53:22 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 | slicing
50 | "*" target
51
52 (See section Primaries for the syntax definitions for *attributeref*,
53 *subscription*, and *slicing*.)
54
55 An assignment statement evaluates the expression list (remember that
56 this can be a single expression or a comma-separated list, the latter
57 yielding a tuple) and assigns the single resulting object to each of
58 the target lists, from left to right.
59
60 Assignment is defined recursively depending on the form of the target
61 (list). When a target is part of a mutable object (an attribute
62 reference, subscription or slicing), the mutable object must
63 ultimately perform the assignment and decide about its validity, and
64 may raise an exception if the assignment is unacceptable. The rules
65 observed by various types and the exceptions raised are given with the
66 definition of the object types (see section The standard type
67 hierarchy).
68
69 Assignment of an object to a target list, optionally enclosed in
70 parentheses or square brackets, is recursively defined as follows.
71
72 * If the target list is a single target with no trailing comma,
73 optionally in parentheses, the object is assigned to that target.
74
75 * Else:
76
77 * If the target list contains one target prefixed with an asterisk,
78 called a “starred” target: The object must be an iterable with at
79 least as many items as there are targets in the target list, minus
80 one. The first items of the iterable are assigned, from left to
81 right, to the targets before the starred target. The final items
82 of the iterable are assigned to the targets after the starred
83 target. A list of the remaining items in the iterable is then
84 assigned to the starred target (the list can be empty).
85
86 * Else: The object must be an iterable with the same number of items
87 as there are targets in the target list, and the items are
88 assigned, from left to right, to the corresponding targets.
89
90 Assignment of an object to a single target is recursively defined as
91 follows.
92
93 * If the target is an identifier (name):
94
95 * If the name does not occur in a "global" or "nonlocal" statement
96 in the current code block: the name is bound to the object in the
97 current local namespace.
98
99 * Otherwise: the name is bound to the object in the global namespace
100 or the outer namespace determined by "nonlocal", respectively.
101
102 The name is rebound if it was already bound. This may cause the
103 reference count for the object previously bound to the name to reach
104 zero, causing the object to be deallocated and its destructor (if it
105 has one) to be called.
106
107 * If the target is an attribute reference: The primary expression in
108 the reference is evaluated. It should yield an object with
109 assignable attributes; if this is not the case, "TypeError" is
110 raised. That object is then asked to assign the assigned object to
111 the given attribute; if it cannot perform the assignment, it raises
112 an exception (usually but not necessarily "AttributeError").
113
114 Note: If the object is a class instance and the attribute reference
115 occurs on both sides of the assignment operator, the right-hand side
116 expression, "a.x" can access either an instance attribute or (if no
117 instance attribute exists) a class attribute. The left-hand side
118 target "a.x" is always set as an instance attribute, creating it if
119 necessary. Thus, the two occurrences of "a.x" do not necessarily
120 refer to the same attribute: if the right-hand side expression
121 refers to a class attribute, the left-hand side creates a new
122 instance attribute as the target of the assignment:
123
124 class Cls:
125 x = 3 # class variable
126 inst = Cls()
127 inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3
128
129 This description does not necessarily apply to descriptor
130 attributes, such as properties created with "property()".
131
132 * If the target is a subscription: The primary expression in the
133 reference is evaluated. It should yield either a mutable sequence
134 object (such as a list) or a mapping object (such as a dictionary).
135 Next, the subscript expression is evaluated.
136
137 If the primary is a mutable sequence object (such as a list), the
138 subscript must yield an integer. If it is negative, the sequence’s
139 length is added to it. The resulting value must be a nonnegative
140 integer less than the sequence’s length, and the sequence is asked
141 to assign the assigned object to its item with that index. If the
142 index is out of range, "IndexError" is raised (assignment to a
143 subscripted sequence cannot add new items to a list).
144
145 If the primary is a mapping object (such as a dictionary), the
146 subscript must have a type compatible with the mapping’s key type,
147 and the mapping is then asked to create a key/value pair which maps
148 the subscript to the assigned object. This can either replace an
149 existing key/value pair with the same key value, or insert a new
150 key/value pair (if no key with the same value existed).
151
152 For user-defined objects, the "__setitem__()" method is called with
153 appropriate arguments.
154
155 * If the target is a slicing: The primary expression in the reference
156 is evaluated. It should yield a mutable sequence object (such as a
157 list). The assigned object should be a sequence object of the same
158 type. Next, the lower and upper bound expressions are evaluated,
159 insofar they are present; defaults are zero and the sequence’s
160 length. The bounds should evaluate to integers. If either bound is
161 negative, the sequence’s length is added to it. The resulting
162 bounds are clipped to lie between zero and the sequence’s length,
163 inclusive. Finally, the sequence object is asked to replace the
164 slice with the items of the assigned sequence. The length of the
165 slice may be different from the length of the assigned sequence,
166 thus changing the length of the target sequence, if the target
167 sequence allows it.
168
169 **CPython implementation detail:** In the current implementation, the
170 syntax for targets is taken to be the same as for expressions, and
171 invalid syntax is rejected during the code generation phase, causing
172 less detailed error messages.
173
174 Although the definition of assignment implies that overlaps between
175 the left-hand side and the right-hand side are ‘simultaneous’ (for
176 example "a, b = b, a" swaps two variables), overlaps *within* the
177 collection of assigned-to variables occur left-to-right, sometimes
178 resulting in confusion. For instance, the following program prints
179 "[0, 2]":
180
181 x = [0, 1]
182 i = 0
183 i, x[i] = 1, 2 # i is updated, then x[i] is updated
184 print(x)
185
186 See also:
187
188 **PEP 3132** - Extended Iterable Unpacking
189 The specification for the "*target" feature.
190
191
192 Augmented assignment statements
193 ===============================
194
195 Augmented assignment is the combination, in a single statement, of a
196 binary operation and an assignment statement:
197
198 augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)
199 augtarget ::= identifier | attributeref | subscription | slicing
200 augop ::= "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="
201 | ">>=" | "<<=" | "&=" | "^=" | "|="
202
203 (See section Primaries for the syntax definitions of the last three
204 symbols.)
205
206 An augmented assignment evaluates the target (which, unlike normal
207 assignment statements, cannot be an unpacking) and the expression
208 list, performs the binary operation specific to the type of assignment
209 on the two operands, and assigns the result to the original target.
210 The target is only evaluated once.
211
212 An augmented assignment statement like "x += 1" can be rewritten as "x
213 = x + 1" to achieve a similar, but not exactly equal effect. In the
214 augmented version, "x" is only evaluated once. Also, when possible,
215 the actual operation is performed *in-place*, meaning that rather than
216 creating a new object and assigning that to the target, the old object
217 is modified instead.
218
219 Unlike normal assignments, augmented assignments evaluate the left-
220 hand side *before* evaluating the right-hand side. For example, "a[i]
221 += f(x)" first looks-up "a[i]", then it evaluates "f(x)" and performs
222 the addition, and lastly, it writes the result back to "a[i]".
223
224 With the exception of assigning to tuples and multiple targets in a
225 single statement, the assignment done by augmented assignment
226 statements is handled the same way as normal assignments. Similarly,
227 with the exception of the possible *in-place* behavior, the binary
228 operation performed by augmented assignment is the same as the normal
229 binary operations.
230
231 For targets which are attribute references, the same caveat about
232 class and instance attributes applies as for regular assignments.
233
234
235 Annotated assignment statements
236 ===============================
237
238 *Annotation* assignment is the combination, in a single statement, of
239 a variable or attribute annotation and an optional assignment
240 statement:
241
242 annotated_assignment_stmt ::= augtarget ":" expression
243 ["=" (starred_expression | yield_expression)]
244
245 The difference from normal Assignment statements is that only a single
246 target is allowed.
247
248 The assignment target is considered “simple” if it consists of a
249 single name that is not enclosed in parentheses. For simple assignment
250 targets, if in class or module scope, the annotations are evaluated
251 and stored in a special class or module attribute "__annotations__"
252 that is a dictionary mapping from variable names (mangled if private)
253 to evaluated annotations. This attribute is writable and is
254 automatically created at the start of class or module body execution,
255 if annotations are found statically.
256
257 If the assignment target is not simple (an attribute, subscript node,
258 or parenthesized name), the annotation is evaluated if in class or
259 module scope, but not stored.
260
261 If a name is annotated in a function scope, then this name is local
262 for that scope. Annotations are never evaluated and stored in function
263 scopes.
264
265 If the right hand side is present, an annotated assignment performs
266 the actual assignment before evaluating annotations (where
267 applicable). If the right hand side is not present for an expression
268 target, then the interpreter evaluates the target except for the last
269 "__setitem__()" or "__setattr__()" call.
270
271 See also:
272
273 **PEP 526** - Syntax for Variable Annotations
274 The proposal that added syntax for annotating the types of
275 variables (including class variables and instance variables),
276 instead of expressing them through comments.
277
278 **PEP 484** - Type hints
279 The proposal that added the "typing" module to provide a standard
280 syntax for type annotations that can be used in static analysis
281 tools and IDEs.
282
283 Changed in version 3.8: Now annotated assignments allow the same
284 expressions in the right hand side as regular assignments. Previously,
285 some expressions (like un-parenthesized tuple expressions) caused a
286 syntax error.
287 ''',
288 'assignment-expressions': r'''Assignment expressions
289 **********************
290
291 assignment_expression ::= [identifier ":="] expression
292
293 An assignment expression (sometimes also called a “named expression”
294 or “walrus”) assigns an "expression" to an "identifier", while also
295 returning the value of the "expression".
296
297 One common use case is when handling matched regular expressions:
298
299 if matching := pattern.search(data):
300 do_something(matching)
301
302 Or, when processing a file stream in chunks:
303
304 while chunk := file.read(9000):
305 process(chunk)
306
307 Assignment expressions must be surrounded by parentheses when used as
308 expression statements and when used as sub-expressions in slicing,
309 conditional, lambda, keyword-argument, and comprehension-if
310 expressions and in "assert", "with", and "assignment" statements. In
311 all other places where they can be used, parentheses are not required,
312 including in "if" and "while" statements.
313
314 Added in version 3.8: See **PEP 572** for more details about
315 assignment expressions.
316 ''',
317 'async': r'''Coroutines
318 **********
319
320 Added in version 3.5.
321
322
323 Coroutine function definition
324 =============================
325
326 async_funcdef ::= [decorators] "async" "def" funcname "(" [parameter_list] ")"
327 ["->" expression] ":" suite
328
329 Execution of Python coroutines can be suspended and resumed at many
330 points (see *coroutine*). "await" expressions, "async for" and "async
331 with" can only be used in the body of a coroutine function.
332
333 Functions defined with "async def" syntax are always coroutine
334 functions, even if they do not contain "await" or "async" keywords.
335
336 It is a "SyntaxError" to use a "yield from" expression inside the body
337 of a coroutine function.
338
339 An example of a coroutine function:
340
341 async def func(param1, param2):
342 do_stuff()
343 await some_coroutine()
344
345 Changed in version 3.7: "await" and "async" are now keywords;
346 previously they were only treated as such inside the body of a
347 coroutine function.
348
349
350 The "async for" statement
351 =========================
352
353 async_for_stmt ::= "async" for_stmt
354
355 An *asynchronous iterable* provides an "__aiter__" method that
356 directly returns an *asynchronous iterator*, which can call
357 asynchronous code in its "__anext__" method.
358
359 The "async for" statement allows convenient iteration over
360 asynchronous iterables.
361
362 The following code:
363
364 async for TARGET in ITER:
365 SUITE
366 else:
367 SUITE2
368
369 Is semantically equivalent to:
370
371 iter = (ITER)
372 iter = type(iter).__aiter__(iter)
373 running = True
374
375 while running:
376 try:
377 TARGET = await type(iter).__anext__(iter)
378 except StopAsyncIteration:
379 running = False
380 else:
381 SUITE
382 else:
383 SUITE2
384
385 See also "__aiter__()" and "__anext__()" for details.
386
387 It is a "SyntaxError" to use an "async for" statement outside the body
388 of a coroutine function.
389
390
391 The "async with" statement
392 ==========================
393
394 async_with_stmt ::= "async" with_stmt
395
396 An *asynchronous context manager* is a *context manager* that is able
397 to suspend execution in its *enter* and *exit* methods.
398
399 The following code:
400
401 async with EXPRESSION as TARGET:
402 SUITE
403
404 is semantically equivalent to:
405
406 manager = (EXPRESSION)
407 aenter = type(manager).__aenter__
408 aexit = type(manager).__aexit__
409 value = await aenter(manager)
410 hit_except = False
411
412 try:
413 TARGET = value
414 SUITE
415 except:
416 hit_except = True
417 if not await aexit(manager, *sys.exc_info()):
418 raise
419 finally:
420 if not hit_except:
421 await aexit(manager, None, None, None)
422
423 See also "__aenter__()" and "__aexit__()" for details.
424
425 It is a "SyntaxError" to use an "async with" statement outside the
426 body of a coroutine function.
427
428 See also:
429
430 **PEP 492** - Coroutines with async and await syntax
431 The proposal that made coroutines a proper standalone concept in
432 Python, and added supporting syntax.
433 ''',
434 'atom-identifiers': r'''Identifiers (Names)
435 *******************
436
437 An identifier occurring as an atom is a name. See section Identifiers
438 and keywords for lexical definition and section Naming and binding for
439 documentation of naming and binding.
440
441 When the name is bound to an object, evaluation of the atom yields
442 that object. When a name is not bound, an attempt to evaluate it
443 raises a "NameError" exception.
444
445
446 Private name mangling
447 =====================
448
449 When an identifier that textually occurs in a class definition begins
450 with two or more underscore characters and does not end in two or more
451 underscores, it is considered a *private name* of that class.
452
453 See also: The class specifications.
454
455 More precisely, private names are transformed to a longer form before
456 code is generated for them. If the transformed name is longer than
457 255 characters, implementation-defined truncation may happen.
458
459 The transformation is independent of the syntactical context in which
460 the identifier is used but only the following private identifiers are
461 mangled:
462
463 * Any name used as the name of a variable that is assigned or read or
464 any name of an attribute being accessed.
465
466 The "__name__" attribute of nested functions, classes, and type
467 aliases is however not mangled.
468
469 * The name of imported modules, e.g., "__spam" in "import __spam". If
470 the module is part of a package (i.e., its name contains a dot), the
471 name is *not* mangled, e.g., the "__foo" in "import __foo.bar" is
472 not mangled.
473
474 * The name of an imported member, e.g., "__f" in "from spam import
475 __f".
476
477 The transformation rule is defined as follows:
478
479 * The class name, with leading underscores removed and a single
480 leading underscore inserted, is inserted in front of the identifier,
481 e.g., the identifier "__spam" occurring in a class named "Foo",
482 "_Foo" or "__Foo" is transformed to "_Foo__spam".
483
484 * If the class name consists only of underscores, the transformation
485 is the identity, e.g., the identifier "__spam" occurring in a class
486 named "_" or "__" is left as is.
487 ''',
488 'atom-literals': r'''Literals
489 ********
490
491 Python supports string and bytes literals and various numeric
492 literals:
493
494 literal ::= stringliteral | bytesliteral
495 | integer | floatnumber | imagnumber
496
497 Evaluation of a literal yields an object of the given type (string,
498 bytes, integer, floating-point number, complex number) with the given
499 value. The value may be approximated in the case of floating-point
500 and imaginary (complex) literals. See section Literals for details.
501
502 All literals correspond to immutable data types, and hence the
503 object’s identity is less important than its value. Multiple
504 evaluations of literals with the same value (either the same
505 occurrence in the program text or a different occurrence) may obtain
506 the same object or a different object with the same value.
507 ''',
508 'attribute-access': r'''Customizing attribute access
509 ****************************
510
511 The following methods can be defined to customize the meaning of
512 attribute access (use of, assignment to, or deletion of "x.name") for
513 class instances.
514
515 object.__getattr__(self, name)
516
517 Called when the default attribute access fails with an
518 "AttributeError" (either "__getattribute__()" raises an
519 "AttributeError" because *name* is not an instance attribute or an
520 attribute in the class tree for "self"; or "__get__()" of a *name*
521 property raises "AttributeError"). This method should either
522 return the (computed) attribute value or raise an "AttributeError"
523 exception. The "object" class itself does not provide this method.
524
525 Note that if the attribute is found through the normal mechanism,
526 "__getattr__()" is not called. (This is an intentional asymmetry
527 between "__getattr__()" and "__setattr__()".) This is done both for
528 efficiency reasons and because otherwise "__getattr__()" would have
529 no way to access other attributes of the instance. Note that at
530 least for instance variables, you can take total control by not
531 inserting any values in the instance attribute dictionary (but
532 instead inserting them in another object). See the
533 "__getattribute__()" method below for a way to actually get total
534 control over attribute access.
535
536 object.__getattribute__(self, name)
537
538 Called unconditionally to implement attribute accesses for
539 instances of the class. If the class also defines "__getattr__()",
540 the latter will not be called unless "__getattribute__()" either
541 calls it explicitly or raises an "AttributeError". This method
542 should return the (computed) attribute value or raise an
543 "AttributeError" exception. In order to avoid infinite recursion in
544 this method, its implementation should always call the base class
545 method with the same name to access any attributes it needs, for
546 example, "object.__getattribute__(self, name)".
547
548 Note:
549
550 This method may still be bypassed when looking up special methods
551 as the result of implicit invocation via language syntax or
552 built-in functions. See Special method lookup.
553
554 For certain sensitive attribute accesses, raises an auditing event
555 "object.__getattr__" with arguments "obj" and "name".
556
557 object.__setattr__(self, name, value)
558
559 Called when an attribute assignment is attempted. This is called
560 instead of the normal mechanism (i.e. store the value in the
561 instance dictionary). *name* is the attribute name, *value* is the
562 value to be assigned to it.
563
564 If "__setattr__()" wants to assign to an instance attribute, it
565 should call the base class method with the same name, for example,
566 "object.__setattr__(self, name, value)".
567
568 For certain sensitive attribute assignments, raises an auditing
569 event "object.__setattr__" with arguments "obj", "name", "value".
570
571 object.__delattr__(self, name)
572
573 Like "__setattr__()" but for attribute deletion instead of
574 assignment. This should only be implemented if "del obj.name" is
575 meaningful for the object.
576
577 For certain sensitive attribute deletions, raises an auditing event
578 "object.__delattr__" with arguments "obj" and "name".
579
580 object.__dir__(self)
581
582 Called when "dir()" is called on the object. An iterable must be
583 returned. "dir()" converts the returned iterable to a list and
584 sorts it.
585
586
587 Customizing module attribute access
588 ===================================
589
590 module.__getattr__()
591 module.__dir__()
592
593 Special names "__getattr__" and "__dir__" can be also used to
594 customize access to module attributes. The "__getattr__" function at
595 the module level should accept one argument which is the name of an
596 attribute and return the computed value or raise an "AttributeError".
597 If an attribute is not found on a module object through the normal
598 lookup, i.e. "object.__getattribute__()", then "__getattr__" is
599 searched in the module "__dict__" before raising an "AttributeError".
600 If found, it is called with the attribute name and the result is
601 returned.
602
603 The "__dir__" function should accept no arguments, and return an
604 iterable of strings that represents the names accessible on module. If
605 present, this function overrides the standard "dir()" search on a
606 module.
607
608 module.__class__
609
610 For a more fine grained customization of the module behavior (setting
611 attributes, properties, etc.), one can set the "__class__" attribute
612 of a module object to a subclass of "types.ModuleType". For example:
613
614 import sys
615 from types import ModuleType
616
617 class VerboseModule(ModuleType):
618 def __repr__(self):
619 return f'Verbose {self.__name__}'
620
621 def __setattr__(self, attr, value):
622 print(f'Setting {attr}...')
623 super().__setattr__(attr, value)
624
625 sys.modules[__name__].__class__ = VerboseModule
626
627 Note:
628
629 Defining module "__getattr__" and setting module "__class__" only
630 affect lookups made using the attribute access syntax – directly
631 accessing the module globals (whether by code within the module, or
632 via a reference to the module’s globals dictionary) is unaffected.
633
634 Changed in version 3.5: "__class__" module attribute is now writable.
635
636 Added in version 3.7: "__getattr__" and "__dir__" module attributes.
637
638 See also:
639
640 **PEP 562** - Module __getattr__ and __dir__
641 Describes the "__getattr__" and "__dir__" functions on modules.
642
643
644 Implementing Descriptors
645 ========================
646
647 The following methods only apply when an instance of the class
648 containing the method (a so-called *descriptor* class) appears in an
649 *owner* class (the descriptor must be in either the owner’s class
650 dictionary or in the class dictionary for one of its parents). In the
651 examples below, “the attribute” refers to the attribute whose name is
652 the key of the property in the owner class’ "__dict__". The "object"
653 class itself does not implement any of these protocols.
654
655 object.__get__(self, instance, owner=None)
656
657 Called to get the attribute of the owner class (class attribute
658 access) or of an instance of that class (instance attribute
659 access). The optional *owner* argument is the owner class, while
660 *instance* is the instance that the attribute was accessed through,
661 or "None" when the attribute is accessed through the *owner*.
662
663 This method should return the computed attribute value or raise an
664 "AttributeError" exception.
665
666 **PEP 252** specifies that "__get__()" is callable with one or two
667 arguments. Python’s own built-in descriptors support this
668 specification; however, it is likely that some third-party tools
669 have descriptors that require both arguments. Python’s own
670 "__getattribute__()" implementation always passes in both arguments
671 whether they are required or not.
672
673 object.__set__(self, instance, value)
674
675 Called to set the attribute on an instance *instance* of the owner
676 class to a new value, *value*.
677
678 Note, adding "__set__()" or "__delete__()" changes the kind of
679 descriptor to a “data descriptor”. See Invoking Descriptors for
680 more details.
681
682 object.__delete__(self, instance)
683
684 Called to delete the attribute on an instance *instance* of the
685 owner class.
686
687 Instances of descriptors may also have the "__objclass__" attribute
688 present:
689
690 object.__objclass__
691
692 The attribute "__objclass__" is interpreted by the "inspect" module
693 as specifying the class where this object was defined (setting this
694 appropriately can assist in runtime introspection of dynamic class
695 attributes). For callables, it may indicate that an instance of the
696 given type (or a subclass) is expected or required as the first
697 positional argument (for example, CPython sets this attribute for
698 unbound methods that are implemented in C).
699
700
701 Invoking Descriptors
702 ====================
703
704 In general, a descriptor is an object attribute with “binding
705 behavior”, one whose attribute access has been overridden by methods
706 in the descriptor protocol: "__get__()", "__set__()", and
707 "__delete__()". If any of those methods are defined for an object, it
708 is said to be a descriptor.
709
710 The default behavior for attribute access is to get, set, or delete
711 the attribute from an object’s dictionary. For instance, "a.x" has a
712 lookup chain starting with "a.__dict__['x']", then
713 "type(a).__dict__['x']", and continuing through the base classes of
714 "type(a)" excluding metaclasses.
715
716 However, if the looked-up value is an object defining one of the
717 descriptor methods, then Python may override the default behavior and
718 invoke the descriptor method instead. Where this occurs in the
719 precedence chain depends on which descriptor methods were defined and
720 how they were called.
721
722 The starting point for descriptor invocation is a binding, "a.x". How
723 the arguments are assembled depends on "a":
724
725 Direct Call
726 The simplest and least common call is when user code directly
727 invokes a descriptor method: "x.__get__(a)".
728
729 Instance Binding
730 If binding to an object instance, "a.x" is transformed into the
731 call: "type(a).__dict__['x'].__get__(a, type(a))".
732
733 Class Binding
734 If binding to a class, "A.x" is transformed into the call:
735 "A.__dict__['x'].__get__(None, A)".
736
737 Super Binding
738 A dotted lookup such as "super(A, a).x" searches
739 "a.__class__.__mro__" for a base class "B" following "A" and then
740 returns "B.__dict__['x'].__get__(a, A)". If not a descriptor, "x"
741 is returned unchanged.
742
743 For instance bindings, the precedence of descriptor invocation depends
744 on which descriptor methods are defined. A descriptor can define any
745 combination of "__get__()", "__set__()" and "__delete__()". If it
746 does not define "__get__()", then accessing the attribute will return
747 the descriptor object itself unless there is a value in the object’s
748 instance dictionary. If the descriptor defines "__set__()" and/or
749 "__delete__()", it is a data descriptor; if it defines neither, it is
750 a non-data descriptor. Normally, data descriptors define both
751 "__get__()" and "__set__()", while non-data descriptors have just the
752 "__get__()" method. Data descriptors with "__get__()" and "__set__()"
753 (and/or "__delete__()") defined always override a redefinition in an
754 instance dictionary. In contrast, non-data descriptors can be
755 overridden by instances.
756
757 Python methods (including those decorated with "@staticmethod" and
758 "@classmethod") are implemented as non-data descriptors. Accordingly,
759 instances can redefine and override methods. This allows individual
760 instances to acquire behaviors that differ from other instances of the
761 same class.
762
763 The "property()" function is implemented as a data descriptor.
764 Accordingly, instances cannot override the behavior of a property.
765
766
767 __slots__
768 =========
769
770 *__slots__* allow us to explicitly declare data members (like
771 properties) and deny the creation of "__dict__" and *__weakref__*
772 (unless explicitly declared in *__slots__* or available in a parent.)
773
774 The space saved over using "__dict__" can be significant. Attribute
775 lookup speed can be significantly improved as well.
776
777 object.__slots__
778
779 This class variable can be assigned a string, iterable, or sequence
780 of strings with variable names used by instances. *__slots__*
781 reserves space for the declared variables and prevents the
782 automatic creation of "__dict__" and *__weakref__* for each
783 instance.
784
785 Notes on using *__slots__*:
786
787 * When inheriting from a class without *__slots__*, the "__dict__" and
788 *__weakref__* attribute of the instances will always be accessible.
789
790 * Without a "__dict__" variable, instances cannot be assigned new
791 variables not listed in the *__slots__* definition. Attempts to
792 assign to an unlisted variable name raises "AttributeError". If
793 dynamic assignment of new variables is desired, then add
794 "'__dict__'" to the sequence of strings in the *__slots__*
795 declaration.
796
797 * Without a *__weakref__* variable for each instance, classes defining
798 *__slots__* do not support "weak references" to its instances. If
799 weak reference support is needed, then add "'__weakref__'" to the
800 sequence of strings in the *__slots__* declaration.
801
802 * *__slots__* are implemented at the class level by creating
803 descriptors for each variable name. As a result, class attributes
804 cannot be used to set default values for instance variables defined
805 by *__slots__*; otherwise, the class attribute would overwrite the
806 descriptor assignment.
807
808 * The action of a *__slots__* declaration is not limited to the class
809 where it is defined. *__slots__* declared in parents are available
810 in child classes. However, instances of a child subclass will get a
811 "__dict__" and *__weakref__* unless the subclass also defines
812 *__slots__* (which should only contain names of any *additional*
813 slots).
814
815 * If a class defines a slot also defined in a base class, the instance
816 variable defined by the base class slot is inaccessible (except by
817 retrieving its descriptor directly from the base class). This
818 renders the meaning of the program undefined. In the future, a
819 check may be added to prevent this.
820
821 * "TypeError" will be raised if nonempty *__slots__* are defined for a
822 class derived from a ""variable-length" built-in type" such as
823 "int", "bytes", and "tuple".
824
825 * Any non-string *iterable* may be assigned to *__slots__*.
826
827 * If a "dictionary" is used to assign *__slots__*, the dictionary keys
828 will be used as the slot names. The values of the dictionary can be
829 used to provide per-attribute docstrings that will be recognised by
830 "inspect.getdoc()" and displayed in the output of "help()".
831
832 * "__class__" assignment works only if both classes have the same
833 *__slots__*.
834
835 * Multiple inheritance with multiple slotted parent classes can be
836 used, but only one parent is allowed to have attributes created by
837 slots (the other bases must have empty slot layouts) - violations
838 raise "TypeError".
839
840 * If an *iterator* is used for *__slots__* then a *descriptor* is
841 created for each of the iterator’s values. However, the *__slots__*
842 attribute will be an empty iterator.
843 ''',
844 'attribute-references': r'''Attribute references
845 ********************
846
847 An attribute reference is a primary followed by a period and a name:
848
849 attributeref ::= primary "." identifier
850
851 The primary must evaluate to an object of a type that supports
852 attribute references, which most objects do. This object is then
853 asked to produce the attribute whose name is the identifier. The type
854 and value produced is determined by the object. Multiple evaluations
855 of the same attribute reference may yield different objects.
856
857 This production can be customized by overriding the
858 "__getattribute__()" method or the "__getattr__()" method. The
859 "__getattribute__()" method is called first and either returns a value
860 or raises "AttributeError" if the attribute is not available.
861
862 If an "AttributeError" is raised and the object has a "__getattr__()"
863 method, that method is called as a fallback.
864 ''',
865 'augassign': r'''Augmented assignment statements
866 *******************************
867
868 Augmented assignment is the combination, in a single statement, of a
869 binary operation and an assignment statement:
870
871 augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)
872 augtarget ::= identifier | attributeref | subscription | slicing
873 augop ::= "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="
874 | ">>=" | "<<=" | "&=" | "^=" | "|="
875
876 (See section Primaries for the syntax definitions of the last three
877 symbols.)
878
879 An augmented assignment evaluates the target (which, unlike normal
880 assignment statements, cannot be an unpacking) and the expression
881 list, performs the binary operation specific to the type of assignment
882 on the two operands, and assigns the result to the original target.
883 The target is only evaluated once.
884
885 An augmented assignment statement like "x += 1" can be rewritten as "x
886 = x + 1" to achieve a similar, but not exactly equal effect. In the
887 augmented version, "x" is only evaluated once. Also, when possible,
888 the actual operation is performed *in-place*, meaning that rather than
889 creating a new object and assigning that to the target, the old object
890 is modified instead.
891
892 Unlike normal assignments, augmented assignments evaluate the left-
893 hand side *before* evaluating the right-hand side. For example, "a[i]
894 += f(x)" first looks-up "a[i]", then it evaluates "f(x)" and performs
895 the addition, and lastly, it writes the result back to "a[i]".
896
897 With the exception of assigning to tuples and multiple targets in a
898 single statement, the assignment done by augmented assignment
899 statements is handled the same way as normal assignments. Similarly,
900 with the exception of the possible *in-place* behavior, the binary
901 operation performed by augmented assignment is the same as the normal
902 binary operations.
903
904 For targets which are attribute references, the same caveat about
905 class and instance attributes applies as for regular assignments.
906 ''',
907 'await': r'''Await expression
908 ****************
909
910 Suspend the execution of *coroutine* on an *awaitable* object. Can
911 only be used inside a *coroutine function*.
912
913 await_expr ::= "await" primary
914
915 Added in version 3.5.
916 ''',
917 'binary': r'''Binary arithmetic operations
918 ****************************
919
920 The binary arithmetic operations have the conventional priority
921 levels. Note that some of these operations also apply to certain non-
922 numeric types. Apart from the power operator, there are only two
923 levels, one for multiplicative operators and one for additive
924 operators:
925
926 m_expr ::= u_expr | m_expr "*" u_expr | m_expr "@" m_expr |
927 m_expr "//" u_expr | m_expr "/" u_expr |
928 m_expr "%" u_expr
929 a_expr ::= m_expr | a_expr "+" m_expr | a_expr "-" m_expr
930
931 The "*" (multiplication) operator yields the product of its arguments.
932 The arguments must either both be numbers, or one argument must be an
933 integer and the other must be a sequence. In the former case, the
934 numbers are converted to a common type and then multiplied together.
935 In the latter case, sequence repetition is performed; a negative
936 repetition factor yields an empty sequence.
937
938 This operation can be customized using the special "__mul__()" and
939 "__rmul__()" methods.
940
941 The "@" (at) operator is intended to be used for matrix
942 multiplication. No builtin Python types implement this operator.
943
944 This operation can be customized using the special "__matmul__()" and
945 "__rmatmul__()" methods.
946
947 Added in version 3.5.
948
949 The "/" (division) and "//" (floor division) operators yield the
950 quotient of their arguments. The numeric arguments are first
951 converted to a common type. Division of integers yields a float, while
952 floor division of integers results in an integer; the result is that
953 of mathematical division with the ‘floor’ function applied to the
954 result. Division by zero raises the "ZeroDivisionError" exception.
955
956 The division operation can be customized using the special
957 "__truediv__()" and "__rtruediv__()" methods. The floor division
958 operation can be customized using the special "__floordiv__()" and
959 "__rfloordiv__()" methods.
960
961 The "%" (modulo) operator yields the remainder from the division of
962 the first argument by the second. The numeric arguments are first
963 converted to a common type. A zero right argument raises the
964 "ZeroDivisionError" exception. The arguments may be floating-point
965 numbers, e.g., "3.14%0.7" equals "0.34" (since "3.14" equals "4*0.7 +
966 0.34".) The modulo operator always yields a result with the same sign
967 as its second operand (or zero); the absolute value of the result is
968 strictly smaller than the absolute value of the second operand [1].
969
970 The floor division and modulo operators are connected by the following
971 identity: "x == (x//y)*y + (x%y)". Floor division and modulo are also
972 connected with the built-in function "divmod()": "divmod(x, y) ==
973 (x//y, x%y)". [2].
974
975 In addition to performing the modulo operation on numbers, the "%"
976 operator is also overloaded by string objects to perform old-style
977 string formatting (also known as interpolation). The syntax for
978 string formatting is described in the Python Library Reference,
979 section printf-style String Formatting.
980
981 The *modulo* operation can be customized using the special "__mod__()"
982 and "__rmod__()" methods.
983
984 The floor division operator, the modulo operator, and the "divmod()"
985 function are not defined for complex numbers. Instead, convert to a
986 floating-point number using the "abs()" function if appropriate.
987
988 The "+" (addition) operator yields the sum of its arguments. The
989 arguments must either both be numbers or both be sequences of the same
990 type. In the former case, the numbers are converted to a common type
991 and then added together. In the latter case, the sequences are
992 concatenated.
993
994 This operation can be customized using the special "__add__()" and
995 "__radd__()" methods.
996
997 The "-" (subtraction) operator yields the difference of its arguments.
998 The numeric arguments are first converted to a common type.
999
1000 This operation can be customized using the special "__sub__()" and
1001 "__rsub__()" methods.
1002 ''',
1003 'bitwise': r'''Binary bitwise operations
1004 *************************
1005
1006 Each of the three bitwise operations has a different priority level:
1007
1008 and_expr ::= shift_expr | and_expr "&" shift_expr
1009 xor_expr ::= and_expr | xor_expr "^" and_expr
1010 or_expr ::= xor_expr | or_expr "|" xor_expr
1011
1012 The "&" operator yields the bitwise AND of its arguments, which must
1013 be integers or one of them must be a custom object overriding
1014 "__and__()" or "__rand__()" special methods.
1015
1016 The "^" operator yields the bitwise XOR (exclusive OR) of its
1017 arguments, which must be integers or one of them must be a custom
1018 object overriding "__xor__()" or "__rxor__()" special methods.
1019
1020 The "|" operator yields the bitwise (inclusive) OR of its arguments,
1021 which must be integers or one of them must be a custom object
1022 overriding "__or__()" or "__ror__()" special methods.
1023 ''',
1024 'bltin-code-objects': r'''Code Objects
1025 ************
1026
1027 Code objects are used by the implementation to represent “pseudo-
1028 compiled” executable Python code such as a function body. They differ
1029 from function objects because they don’t contain a reference to their
1030 global execution environment. Code objects are returned by the built-
1031 in "compile()" function and can be extracted from function objects
1032 through their "__code__" attribute. See also the "code" module.
1033
1034 Accessing "__code__" raises an auditing event "object.__getattr__"
1035 with arguments "obj" and ""__code__"".
1036
1037 A code object can be executed or evaluated by passing it (instead of a
1038 source string) to the "exec()" or "eval()" built-in functions.
1039
1040 See The standard type hierarchy for more information.
1041 ''',
1042 'bltin-ellipsis-object': r'''The Ellipsis Object
1043 *******************
1044
1045 This object is commonly used to indicate that something is omitted. It
1046 supports no special operations. There is exactly one ellipsis object,
1047 named "Ellipsis" (a built-in name). "type(Ellipsis)()" produces the
1048 "Ellipsis" singleton.
1049
1050 It is written as "Ellipsis" or "...".
1051
1052 In typical use, "..." as the "Ellipsis" object appears in a few
1053 different places, for instance:
1054
1055 * In type annotations, such as callable arguments or tuple elements.
1056
1057 * As the body of a function instead of a pass statement.
1058
1059 * In third-party libraries, such as Numpy’s slicing and striding.
1060
1061 Python also uses three dots in ways that are not "Ellipsis" objects,
1062 for instance:
1063
1064 * Doctest’s "ELLIPSIS", as a pattern for missing content.
1065
1066 * The default Python prompt of the *interactive* shell when partial
1067 input is incomplete.
1068
1069 Lastly, the Python documentation often uses three dots in conventional
1070 English usage to mean omitted content, even in code examples that also
1071 use them as the "Ellipsis".
1072 ''',
1073 'bltin-null-object': r'''The Null Object
1074 ***************
1075
1076 This object is returned by functions that don’t explicitly return a
1077 value. It supports no special operations. There is exactly one null
1078 object, named "None" (a built-in name). "type(None)()" produces the
1079 same singleton.
1080
1081 It is written as "None".
1082 ''',
1083 'bltin-type-objects': r'''Type Objects
1084 ************
1085
1086 Type objects represent the various object types. An object’s type is
1087 accessed by the built-in function "type()". There are no special
1088 operations on types. The standard module "types" defines names for
1089 all standard built-in types.
1090
1091 Types are written like this: "<class 'int'>".
1092 ''',
1093 'booleans': r'''Boolean operations
1094 ******************
1095
1096 or_test ::= and_test | or_test "or" and_test
1097 and_test ::= not_test | and_test "and" not_test
1098 not_test ::= comparison | "not" not_test
1099
1100 In the context of Boolean operations, and also when expressions are
1101 used by control flow statements, the following values are interpreted
1102 as false: "False", "None", numeric zero of all types, and empty
1103 strings and containers (including strings, tuples, lists,
1104 dictionaries, sets and frozensets). All other values are interpreted
1105 as true. User-defined objects can customize their truth value by
1106 providing a "__bool__()" method.
1107
1108 The operator "not" yields "True" if its argument is false, "False"
1109 otherwise.
1110
1111 The expression "x and y" first evaluates *x*; if *x* is false, its
1112 value is returned; otherwise, *y* is evaluated and the resulting value
1113 is returned.
1114
1115 The expression "x or y" first evaluates *x*; if *x* is true, its value
1116 is returned; otherwise, *y* is evaluated and the resulting value is
1117 returned.
1118
1119 Note that neither "and" nor "or" restrict the value and type they
1120 return to "False" and "True", but rather return the last evaluated
1121 argument. This is sometimes useful, e.g., if "s" is a string that
1122 should be replaced by a default value if it is empty, the expression
1123 "s or 'foo'" yields the desired value. Because "not" has to create a
1124 new value, it returns a boolean value regardless of the type of its
1125 argument (for example, "not 'foo'" produces "False" rather than "''".)
1126 ''',
1127 'break': r'''The "break" statement
1128 *********************
1129
1130 break_stmt ::= "break"
1131
1132 "break" may only occur syntactically nested in a "for" or "while"
1133 loop, but not nested in a function or class definition within that
1134 loop.
1135
1136 It terminates the nearest enclosing loop, skipping the optional "else"
1137 clause if the loop has one.
1138
1139 If a "for" loop is terminated by "break", the loop control target
1140 keeps its current value.
1141
1142 When "break" passes control out of a "try" statement with a "finally"
1143 clause, that "finally" clause is executed before really leaving the
1144 loop.
1145 ''',
1146 'callable-types': r'''Emulating callable objects
1147 **************************
1148
1149 object.__call__(self[, args...])
1150
1151 Called when the instance is “called” as a function; if this method
1152 is defined, "x(arg1, arg2, ...)" roughly translates to
1153 "type(x).__call__(x, arg1, ...)". The "object" class itself does
1154 not provide this method.
1155 ''',
1156 'calls': r'''Calls
1157 *****
1158
1159 A call calls a callable object (e.g., a *function*) with a possibly
1160 empty series of *arguments*:
1161
1162 call ::= primary "(" [argument_list [","] | comprehension] ")"
1163 argument_list ::= positional_arguments ["," starred_and_keywords]
1164 ["," keywords_arguments]
1165 | starred_and_keywords ["," keywords_arguments]
1166 | keywords_arguments
1167 positional_arguments ::= positional_item ("," positional_item)*
1168 positional_item ::= assignment_expression | "*" expression
1169 starred_and_keywords ::= ("*" expression | keyword_item)
1170 ("," "*" expression | "," keyword_item)*
1171 keywords_arguments ::= (keyword_item | "**" expression)
1172 ("," keyword_item | "," "**" expression)*
1173 keyword_item ::= identifier "=" expression
1174
1175 An optional trailing comma may be present after the positional and
1176 keyword arguments but does not affect the semantics.
1177
1178 The primary must evaluate to a callable object (user-defined
1179 functions, built-in functions, methods of built-in objects, class
1180 objects, methods of class instances, and all objects having a
1181 "__call__()" method are callable). All argument expressions are
1182 evaluated before the call is attempted. Please refer to section
1183 Function definitions for the syntax of formal *parameter* lists.
1184
1185 If keyword arguments are present, they are first converted to
1186 positional arguments, as follows. First, a list of unfilled slots is
1187 created for the formal parameters. If there are N positional
1188 arguments, they are placed in the first N slots. Next, for each
1189 keyword argument, the identifier is used to determine the
1190 corresponding slot (if the identifier is the same as the first formal
1191 parameter name, the first slot is used, and so on). If the slot is
1192 already filled, a "TypeError" exception is raised. Otherwise, the
1193 argument is placed in the slot, filling it (even if the expression is
1194 "None", it fills the slot). When all arguments have been processed,
1195 the slots that are still unfilled are filled with the corresponding
1196 default value from the function definition. (Default values are
1197 calculated, once, when the function is defined; thus, a mutable object
1198 such as a list or dictionary used as default value will be shared by
1199 all calls that don’t specify an argument value for the corresponding
1200 slot; this should usually be avoided.) If there are any unfilled
1201 slots for which no default value is specified, a "TypeError" exception
1202 is raised. Otherwise, the list of filled slots is used as the
1203 argument list for the call.
1204
1205 **CPython implementation detail:** An implementation may provide
1206 built-in functions whose positional parameters do not have names, even
1207 if they are ‘named’ for the purpose of documentation, and which
1208 therefore cannot be supplied by keyword. In CPython, this is the case
1209 for functions implemented in C that use "PyArg_ParseTuple()" to parse
1210 their arguments.
1211
1212 If there are more positional arguments than there are formal parameter
1213 slots, a "TypeError" exception is raised, unless a formal parameter
1214 using the syntax "*identifier" is present; in this case, that formal
1215 parameter receives a tuple containing the excess positional arguments
1216 (or an empty tuple if there were no excess positional arguments).
1217
1218 If any keyword argument does not correspond to a formal parameter
1219 name, a "TypeError" exception is raised, unless a formal parameter
1220 using the syntax "**identifier" is present; in this case, that formal
1221 parameter receives a dictionary containing the excess keyword
1222 arguments (using the keywords as keys and the argument values as
1223 corresponding values), or a (new) empty dictionary if there were no
1224 excess keyword arguments.
1225
1226 If the syntax "*expression" appears in the function call, "expression"
1227 must evaluate to an *iterable*. Elements from these iterables are
1228 treated as if they were additional positional arguments. For the call
1229 "f(x1, x2, *y, x3, x4)", if *y* evaluates to a sequence *y1*, …, *yM*,
1230 this is equivalent to a call with M+4 positional arguments *x1*, *x2*,
1231 *y1*, …, *yM*, *x3*, *x4*.
1232
1233 A consequence of this is that although the "*expression" syntax may
1234 appear *after* explicit keyword arguments, it is processed *before*
1235 the keyword arguments (and any "**expression" arguments – see below).
1236 So:
1237
1238 >>> def f(a, b):
1239 ... print(a, b)
1240 ...
1241 >>> f(b=1, *(2,))
1242 2 1
1243 >>> f(a=1, *(2,))
1244 Traceback (most recent call last):
1245 File "<stdin>", line 1, in <module>
1246 TypeError: f() got multiple values for keyword argument 'a'
1247 >>> f(1, *(2,))
1248 1 2
1249
1250 It is unusual for both keyword arguments and the "*expression" syntax
1251 to be used in the same call, so in practice this confusion does not
1252 often arise.
1253
1254 If the syntax "**expression" appears in the function call,
1255 "expression" must evaluate to a *mapping*, the contents of which are
1256 treated as additional keyword arguments. If a parameter matching a key
1257 has already been given a value (by an explicit keyword argument, or
1258 from another unpacking), a "TypeError" exception is raised.
1259
1260 When "**expression" is used, each key in this mapping must be a
1261 string. Each value from the mapping is assigned to the first formal
1262 parameter eligible for keyword assignment whose name is equal to the
1263 key. A key need not be a Python identifier (e.g. ""max-temp °F"" is
1264 acceptable, although it will not match any formal parameter that could
1265 be declared). If there is no match to a formal parameter the key-value
1266 pair is collected by the "**" parameter, if there is one, or if there
1267 is not, a "TypeError" exception is raised.
1268
1269 Formal parameters using the syntax "*identifier" or "**identifier"
1270 cannot be used as positional argument slots or as keyword argument
1271 names.
1272
1273 Changed in version 3.5: Function calls accept any number of "*" and
1274 "**" unpackings, positional arguments may follow iterable unpackings
1275 ("*"), and keyword arguments may follow dictionary unpackings ("**").
1276 Originally proposed by **PEP 448**.
1277
1278 A call always returns some value, possibly "None", unless it raises an
1279 exception. How this value is computed depends on the type of the
1280 callable object.
1281
1282 If it is—
1283
1284 a user-defined function:
1285 The code block for the function is executed, passing it the
1286 argument list. The first thing the code block will do is bind the
1287 formal parameters to the arguments; this is described in section
1288 Function definitions. When the code block executes a "return"
1289 statement, this specifies the return value of the function call.
1290 If execution reaches the end of the code block without executing a
1291 "return" statement, the return value is "None".
1292
1293 a built-in function or method:
1294 The result is up to the interpreter; see Built-in Functions for the
1295 descriptions of built-in functions and methods.
1296
1297 a class object:
1298 A new instance of that class is returned.
1299
1300 a class instance method:
1301 The corresponding user-defined function is called, with an argument
1302 list that is one longer than the argument list of the call: the
1303 instance becomes the first argument.
1304
1305 a class instance:
1306 The class must define a "__call__()" method; the effect is then the
1307 same as if that method was called.
1308 ''',
1309 'class': r'''Class definitions
1310 *****************
1311
1312 A class definition defines a class object (see section The standard
1313 type hierarchy):
1314
1315 classdef ::= [decorators] "class" classname [type_params] [inheritance] ":" suite
1316 inheritance ::= "(" [argument_list] ")"
1317 classname ::= identifier
1318
1319 A class definition is an executable statement. The inheritance list
1320 usually gives a list of base classes (see Metaclasses for more
1321 advanced uses), so each item in the list should evaluate to a class
1322 object which allows subclassing. Classes without an inheritance list
1323 inherit, by default, from the base class "object"; hence,
1324
1325 class Foo:
1326 pass
1327
1328 is equivalent to
1329
1330 class Foo(object):
1331 pass
1332
1333 The class’s suite is then executed in a new execution frame (see
1334 Naming and binding), using a newly created local namespace and the
1335 original global namespace. (Usually, the suite contains mostly
1336 function definitions.) When the class’s suite finishes execution, its
1337 execution frame is discarded but its local namespace is saved. [5] A
1338 class object is then created using the inheritance list for the base
1339 classes and the saved local namespace for the attribute dictionary.
1340 The class name is bound to this class object in the original local
1341 namespace.
1342
1343 The order in which attributes are defined in the class body is
1344 preserved in the new class’s "__dict__". Note that this is reliable
1345 only right after the class is created and only for classes that were
1346 defined using the definition syntax.
1347
1348 Class creation can be customized heavily using metaclasses.
1349
1350 Classes can also be decorated: just like when decorating functions,
1351
1352 @f1(arg)
1353 @f2
1354 class Foo: pass
1355
1356 is roughly equivalent to
1357
1358 class Foo: pass
1359 Foo = f1(arg)(f2(Foo))
1360
1361 The evaluation rules for the decorator expressions are the same as for
1362 function decorators. The result is then bound to the class name.
1363
1364 Changed in version 3.9: Classes may be decorated with any valid
1365 "assignment_expression". Previously, the grammar was much more
1366 restrictive; see **PEP 614** for details.
1367
1368 A list of type parameters may be given in square brackets immediately
1369 after the class’s name. This indicates to static type checkers that
1370 the class is generic. At runtime, the type parameters can be retrieved
1371 from the class’s "__type_params__" attribute. See Generic classes for
1372 more.
1373
1374 Changed in version 3.12: Type parameter lists are new in Python 3.12.
1375
1376 **Programmer’s note:** Variables defined in the class definition are
1377 class attributes; they are shared by instances. Instance attributes
1378 can be set in a method with "self.name = value". Both class and
1379 instance attributes are accessible through the notation “"self.name"”,
1380 and an instance attribute hides a class attribute with the same name
1381 when accessed in this way. Class attributes can be used as defaults
1382 for instance attributes, but using mutable values there can lead to
1383 unexpected results. Descriptors can be used to create instance
1384 variables with different implementation details.
1385
1386 See also:
1387
1388 **PEP 3115** - Metaclasses in Python 3000
1389 The proposal that changed the declaration of metaclasses to the
1390 current syntax, and the semantics for how classes with
1391 metaclasses are constructed.
1392
1393 **PEP 3129** - Class Decorators
1394 The proposal that added class decorators. Function and method
1395 decorators were introduced in **PEP 318**.
1396 ''',
1397 'comparisons': r'''Comparisons
1398 ***********
1399
1400 Unlike C, all comparison operations in Python have the same priority,
1401 which is lower than that of any arithmetic, shifting or bitwise
1402 operation. Also unlike C, expressions like "a < b < c" have the
1403 interpretation that is conventional in mathematics:
1404
1405 comparison ::= or_expr (comp_operator or_expr)*
1406 comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="
1407 | "is" ["not"] | ["not"] "in"
1408
1409 Comparisons yield boolean values: "True" or "False". Custom *rich
1410 comparison methods* may return non-boolean values. In this case Python
1411 will call "bool()" on such value in boolean contexts.
1412
1413 Comparisons can be chained arbitrarily, e.g., "x < y <= z" is
1414 equivalent to "x < y and y <= z", except that "y" is evaluated only
1415 once (but in both cases "z" is not evaluated at all when "x < y" is
1416 found to be false).
1417
1418 Formally, if *a*, *b*, *c*, …, *y*, *z* are expressions and *op1*,
1419 *op2*, …, *opN* are comparison operators, then "a op1 b op2 c ... y
1420 opN z" is equivalent to "a op1 b and b op2 c and ... y opN z", except
1421 that each expression is evaluated at most once.
1422
1423 Note that "a op1 b op2 c" doesn’t imply any kind of comparison between
1424 *a* and *c*, so that, e.g., "x < y > z" is perfectly legal (though
1425 perhaps not pretty).
1426
1427
1428 Value comparisons
1429 =================
1430
1431 The operators "<", ">", "==", ">=", "<=", and "!=" compare the values
1432 of two objects. The objects do not need to have the same type.
1433
1434 Chapter Objects, values and types states that objects have a value (in
1435 addition to type and identity). The value of an object is a rather
1436 abstract notion in Python: For example, there is no canonical access
1437 method for an object’s value. Also, there is no requirement that the
1438 value of an object should be constructed in a particular way, e.g.
1439 comprised of all its data attributes. Comparison operators implement a
1440 particular notion of what the value of an object is. One can think of
1441 them as defining the value of an object indirectly, by means of their
1442 comparison implementation.
1443
1444 Because all types are (direct or indirect) subtypes of "object", they
1445 inherit the default comparison behavior from "object". Types can
1446 customize their comparison behavior by implementing *rich comparison
1447 methods* like "__lt__()", described in Basic customization.
1448
1449 The default behavior for equality comparison ("==" and "!=") is based
1450 on the identity of the objects. Hence, equality comparison of
1451 instances with the same identity results in equality, and equality
1452 comparison of instances with different identities results in
1453 inequality. A motivation for this default behavior is the desire that
1454 all objects should be reflexive (i.e. "x is y" implies "x == y").
1455
1456 A default order comparison ("<", ">", "<=", and ">=") is not provided;
1457 an attempt raises "TypeError". A motivation for this default behavior
1458 is the lack of a similar invariant as for equality.
1459
1460 The behavior of the default equality comparison, that instances with
1461 different identities are always unequal, may be in contrast to what
1462 types will need that have a sensible definition of object value and
1463 value-based equality. Such types will need to customize their
1464 comparison behavior, and in fact, a number of built-in types have done
1465 that.
1466
1467 The following list describes the comparison behavior of the most
1468 important built-in types.
1469
1470 * Numbers of built-in numeric types (Numeric Types — int, float,
1471 complex) and of the standard library types "fractions.Fraction" and
1472 "decimal.Decimal" can be compared within and across their types,
1473 with the restriction that complex numbers do not support order
1474 comparison. Within the limits of the types involved, they compare
1475 mathematically (algorithmically) correct without loss of precision.
1476
1477 The not-a-number values "float('NaN')" and "decimal.Decimal('NaN')"
1478 are special. Any ordered comparison of a number to a not-a-number
1479 value is false. A counter-intuitive implication is that not-a-number
1480 values are not equal to themselves. For example, if "x =
1481 float('NaN')", "3 < x", "x < 3" and "x == x" are all false, while "x
1482 != x" is true. This behavior is compliant with IEEE 754.
1483
1484 * "None" and "NotImplemented" are singletons. **PEP 8** advises that
1485 comparisons for singletons should always be done with "is" or "is
1486 not", never the equality operators.
1487
1488 * Binary sequences (instances of "bytes" or "bytearray") can be
1489 compared within and across their types. They compare
1490 lexicographically using the numeric values of their elements.
1491
1492 * Strings (instances of "str") compare lexicographically using the
1493 numerical Unicode code points (the result of the built-in function
1494 "ord()") of their characters. [3]
1495
1496 Strings and binary sequences cannot be directly compared.
1497
1498 * Sequences (instances of "tuple", "list", or "range") can be compared
1499 only within each of their types, with the restriction that ranges do
1500 not support order comparison. Equality comparison across these
1501 types results in inequality, and ordering comparison across these
1502 types raises "TypeError".
1503
1504 Sequences compare lexicographically using comparison of
1505 corresponding elements. The built-in containers typically assume
1506 identical objects are equal to themselves. That lets them bypass
1507 equality tests for identical objects to improve performance and to
1508 maintain their internal invariants.
1509
1510 Lexicographical comparison between built-in collections works as
1511 follows:
1512
1513 * For two collections to compare equal, they must be of the same
1514 type, have the same length, and each pair of corresponding
1515 elements must compare equal (for example, "[1,2] == (1,2)" is
1516 false because the type is not the same).
1517
1518 * Collections that support order comparison are ordered the same as
1519 their first unequal elements (for example, "[1,2,x] <= [1,2,y]"
1520 has the same value as "x <= y"). If a corresponding element does
1521 not exist, the shorter collection is ordered first (for example,
1522 "[1,2] < [1,2,3]" is true).
1523
1524 * Mappings (instances of "dict") compare equal if and only if they
1525 have equal "(key, value)" pairs. Equality comparison of the keys and
1526 values enforces reflexivity.
1527
1528 Order comparisons ("<", ">", "<=", and ">=") raise "TypeError".
1529
1530 * Sets (instances of "set" or "frozenset") can be compared within and
1531 across their types.
1532
1533 They define order comparison operators to mean subset and superset
1534 tests. Those relations do not define total orderings (for example,
1535 the two sets "{1,2}" and "{2,3}" are not equal, nor subsets of one
1536 another, nor supersets of one another). Accordingly, sets are not
1537 appropriate arguments for functions which depend on total ordering
1538 (for example, "min()", "max()", and "sorted()" produce undefined
1539 results given a list of sets as inputs).
1540
1541 Comparison of sets enforces reflexivity of its elements.
1542
1543 * Most other built-in types have no comparison methods implemented, so
1544 they inherit the default comparison behavior.
1545
1546 User-defined classes that customize their comparison behavior should
1547 follow some consistency rules, if possible:
1548
1549 * Equality comparison should be reflexive. In other words, identical
1550 objects should compare equal:
1551
1552 "x is y" implies "x == y"
1553
1554 * Comparison should be symmetric. In other words, the following
1555 expressions should have the same result:
1556
1557 "x == y" and "y == x"
1558
1559 "x != y" and "y != x"
1560
1561 "x < y" and "y > x"
1562
1563 "x <= y" and "y >= x"
1564
1565 * Comparison should be transitive. The following (non-exhaustive)
1566 examples illustrate that:
1567
1568 "x > y and y > z" implies "x > z"
1569
1570 "x < y and y <= z" implies "x < z"
1571
1572 * Inverse comparison should result in the boolean negation. In other
1573 words, the following expressions should have the same result:
1574
1575 "x == y" and "not x != y"
1576
1577 "x < y" and "not x >= y" (for total ordering)
1578
1579 "x > y" and "not x <= y" (for total ordering)
1580
1581 The last two expressions apply to totally ordered collections (e.g.
1582 to sequences, but not to sets or mappings). See also the
1583 "total_ordering()" decorator.
1584
1585 * The "hash()" result should be consistent with equality. Objects that
1586 are equal should either have the same hash value, or be marked as
1587 unhashable.
1588
1589 Python does not enforce these consistency rules. In fact, the
1590 not-a-number values are an example for not following these rules.
1591
1592
1593 Membership test operations
1594 ==========================
1595
1596 The operators "in" and "not in" test for membership. "x in s"
1597 evaluates to "True" if *x* is a member of *s*, and "False" otherwise.
1598 "x not in s" returns the negation of "x in s". All built-in sequences
1599 and set types support this as well as dictionary, for which "in" tests
1600 whether the dictionary has a given key. For container types such as
1601 list, tuple, set, frozenset, dict, or collections.deque, the
1602 expression "x in y" is equivalent to "any(x is e or x == e for e in
1603 y)".
1604
1605 For the string and bytes types, "x in y" is "True" if and only if *x*
1606 is a substring of *y*. An equivalent test is "y.find(x) != -1".
1607 Empty strings are always considered to be a substring of any other
1608 string, so """ in "abc"" will return "True".
1609
1610 For user-defined classes which define the "__contains__()" method, "x
1611 in y" returns "True" if "y.__contains__(x)" returns a true value, and
1612 "False" otherwise.
1613
1614 For user-defined classes which do not define "__contains__()" but do
1615 define "__iter__()", "x in y" is "True" if some value "z", for which
1616 the expression "x is z or x == z" is true, is produced while iterating
1617 over "y". If an exception is raised during the iteration, it is as if
1618 "in" raised that exception.
1619
1620 Lastly, the old-style iteration protocol is tried: if a class defines
1621 "__getitem__()", "x in y" is "True" if and only if there is a non-
1622 negative integer index *i* such that "x is y[i] or x == y[i]", and no
1623 lower integer index raises the "IndexError" exception. (If any other
1624 exception is raised, it is as if "in" raised that exception).
1625
1626 The operator "not in" is defined to have the inverse truth value of
1627 "in".
1628
1629
1630 Identity comparisons
1631 ====================
1632
1633 The operators "is" and "is not" test for an object’s identity: "x is
1634 y" is true if and only if *x* and *y* are the same object. An
1635 Object’s identity is determined using the "id()" function. "x is not
1636 y" yields the inverse truth value. [4]
1637 ''',
1638 'compound': r'''Compound statements
1639 *******************
1640
1641 Compound statements contain (groups of) other statements; they affect
1642 or control the execution of those other statements in some way. In
1643 general, compound statements span multiple lines, although in simple
1644 incarnations a whole compound statement may be contained in one line.
1645
1646 The "if", "while" and "for" statements implement traditional control
1647 flow constructs. "try" specifies exception handlers and/or cleanup
1648 code for a group of statements, while the "with" statement allows the
1649 execution of initialization and finalization code around a block of
1650 code. Function and class definitions are also syntactically compound
1651 statements.
1652
1653 A compound statement consists of one or more ‘clauses.’ A clause
1654 consists of a header and a ‘suite.’ The clause headers of a
1655 particular compound statement are all at the same indentation level.
1656 Each clause header begins with a uniquely identifying keyword and ends
1657 with a colon. A suite is a group of statements controlled by a
1658 clause. A suite can be one or more semicolon-separated simple
1659 statements on the same line as the header, following the header’s
1660 colon, or it can be one or more indented statements on subsequent
1661 lines. Only the latter form of a suite can contain nested compound
1662 statements; the following is illegal, mostly because it wouldn’t be
1663 clear to which "if" clause a following "else" clause would belong:
1664
1665 if test1: if test2: print(x)
1666
1667 Also note that the semicolon binds tighter than the colon in this
1668 context, so that in the following example, either all or none of the
1669 "print()" calls are executed:
1670
1671 if x < y < z: print(x); print(y); print(z)
1672
1673 Summarizing:
1674
1675 compound_stmt ::= if_stmt
1676 | while_stmt
1677 | for_stmt
1678 | try_stmt
1679 | with_stmt
1680 | match_stmt
1681 | funcdef
1682 | classdef
1683 | async_with_stmt
1684 | async_for_stmt
1685 | async_funcdef
1686 suite ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
1687 statement ::= stmt_list NEWLINE | compound_stmt
1688 stmt_list ::= simple_stmt (";" simple_stmt)* [";"]
1689
1690 Note that statements always end in a "NEWLINE" possibly followed by a
1691 "DEDENT". Also note that optional continuation clauses always begin
1692 with a keyword that cannot start a statement, thus there are no
1693 ambiguities (the ‘dangling "else"’ problem is solved in Python by
1694 requiring nested "if" statements to be indented).
1695
1696 The formatting of the grammar rules in the following sections places
1697 each clause on a separate line for clarity.
1698
1699
1700 The "if" statement
1701 ==================
1702
1703 The "if" statement is used for conditional execution:
1704
1705 if_stmt ::= "if" assignment_expression ":" suite
1706 ("elif" assignment_expression ":" suite)*
1707 ["else" ":" suite]
1708
1709 It selects exactly one of the suites by evaluating the expressions one
1710 by one until one is found to be true (see section Boolean operations
1711 for the definition of true and false); then that suite is executed
1712 (and no other part of the "if" statement is executed or evaluated).
1713 If all expressions are false, the suite of the "else" clause, if
1714 present, is executed.
1715
1716
1717 The "while" statement
1718 =====================
1719
1720 The "while" statement is used for repeated execution as long as an
1721 expression is true:
1722
1723 while_stmt ::= "while" assignment_expression ":" suite
1724 ["else" ":" suite]
1725
1726 This repeatedly tests the expression and, if it is true, executes the
1727 first suite; if the expression is false (which may be the first time
1728 it is tested) the suite of the "else" clause, if present, is executed
1729 and the loop terminates.
1730
1731 A "break" statement executed in the first suite terminates the loop
1732 without executing the "else" clause’s suite. A "continue" statement
1733 executed in the first suite skips the rest of the suite and goes back
1734 to testing the expression.
1735
1736
1737 The "for" statement
1738 ===================
1739
1740 The "for" statement is used to iterate over the elements of a sequence
1741 (such as a string, tuple or list) or other iterable object:
1742
1743 for_stmt ::= "for" target_list "in" starred_list ":" suite
1744 ["else" ":" suite]
1745
1746 The "starred_list" expression is evaluated once; it should yield an
1747 *iterable* object. An *iterator* is created for that iterable. The
1748 first item provided by the iterator is then assigned to the target
1749 list using the standard rules for assignments (see Assignment
1750 statements), and the suite is executed. This repeats for each item
1751 provided by the iterator. When the iterator is exhausted, the suite
1752 in the "else" clause, if present, is executed, and the loop
1753 terminates.
1754
1755 A "break" statement executed in the first suite terminates the loop
1756 without executing the "else" clause’s suite. A "continue" statement
1757 executed in the first suite skips the rest of the suite and continues
1758 with the next item, or with the "else" clause if there is no next
1759 item.
1760
1761 The for-loop makes assignments to the variables in the target list.
1762 This overwrites all previous assignments to those variables including
1763 those made in the suite of the for-loop:
1764
1765 for i in range(10):
1766 print(i)
1767 i = 5 # this will not affect the for-loop
1768 # because i will be overwritten with the next
1769 # index in the range
1770
1771 Names in the target list are not deleted when the loop is finished,
1772 but if the sequence is empty, they will not have been assigned to at
1773 all by the loop. Hint: the built-in type "range()" represents
1774 immutable arithmetic sequences of integers. For instance, iterating
1775 "range(3)" successively yields 0, 1, and then 2.
1776
1777 Changed in version 3.11: Starred elements are now allowed in the
1778 expression list.
1779
1780
1781 The "try" statement
1782 ===================
1783
1784 The "try" statement specifies exception handlers and/or cleanup code
1785 for a group of statements:
1786
1787 try_stmt ::= try1_stmt | try2_stmt | try3_stmt
1788 try1_stmt ::= "try" ":" suite
1789 ("except" [expression ["as" identifier]] ":" suite)+
1790 ["else" ":" suite]
1791 ["finally" ":" suite]
1792 try2_stmt ::= "try" ":" suite
1793 ("except" "*" expression ["as" identifier] ":" suite)+
1794 ["else" ":" suite]
1795 ["finally" ":" suite]
1796 try3_stmt ::= "try" ":" suite
1797 "finally" ":" suite
1798
1799 Additional information on exceptions can be found in section
1800 Exceptions, and information on using the "raise" statement to generate
1801 exceptions may be found in section The raise statement.
1802
1803
1804 "except" clause
1805 ---------------
1806
1807 The "except" clause(s) specify one or more exception handlers. When no
1808 exception occurs in the "try" clause, no exception handler is
1809 executed. When an exception occurs in the "try" suite, a search for an
1810 exception handler is started. This search inspects the "except"
1811 clauses in turn until one is found that matches the exception. An
1812 expression-less "except" clause, if present, must be last; it matches
1813 any exception.
1814
1815 For an "except" clause with an expression, the expression must
1816 evaluate to an exception type or a tuple of exception types. The
1817 raised exception matches an "except" clause whose expression evaluates
1818 to the class or a *non-virtual base class* of the exception object, or
1819 to a tuple that contains such a class.
1820
1821 If no "except" clause matches the exception, the search for an
1822 exception handler continues in the surrounding code and on the
1823 invocation stack. [1]
1824
1825 If the evaluation of an expression in the header of an "except" clause
1826 raises an exception, the original search for a handler is canceled and
1827 a search starts for the new exception in the surrounding code and on
1828 the call stack (it is treated as if the entire "try" statement raised
1829 the exception).
1830
1831 When a matching "except" clause is found, the exception is assigned to
1832 the target specified after the "as" keyword in that "except" clause,
1833 if present, and the "except" clause’s suite is executed. All "except"
1834 clauses must have an executable block. When the end of this block is
1835 reached, execution continues normally after the entire "try"
1836 statement. (This means that if two nested handlers exist for the same
1837 exception, and the exception occurs in the "try" clause of the inner
1838 handler, the outer handler will not handle the exception.)
1839
1840 When an exception has been assigned using "as target", it is cleared
1841 at the end of the "except" clause. This is as if
1842
1843 except E as N:
1844 foo
1845
1846 was translated to
1847
1848 except E as N:
1849 try:
1850 foo
1851 finally:
1852 del N
1853
1854 This means the exception must be assigned to a different name to be
1855 able to refer to it after the "except" clause. Exceptions are cleared
1856 because with the traceback attached to them, they form a reference
1857 cycle with the stack frame, keeping all locals in that frame alive
1858 until the next garbage collection occurs.
1859
1860 Before an "except" clause’s suite is executed, the exception is stored
1861 in the "sys" module, where it can be accessed from within the body of
1862 the "except" clause by calling "sys.exception()". When leaving an
1863 exception handler, the exception stored in the "sys" module is reset
1864 to its previous value:
1865
1866 >>> print(sys.exception())
1867 None
1868 >>> try:
1869 ... raise TypeError
1870 ... except:
1871 ... print(repr(sys.exception()))
1872 ... try:
1873 ... raise ValueError
1874 ... except:
1875 ... print(repr(sys.exception()))
1876 ... print(repr(sys.exception()))
1877 ...
1878 TypeError()
1879 ValueError()
1880 TypeError()
1881 >>> print(sys.exception())
1882 None
1883
1884
1885 "except*" clause
1886 ----------------
1887
1888 The "except*" clause(s) specify one or more handlers for groups of
1889 exceptions ("BaseExceptionGroup" instances). A "try" statement can
1890 have either "except" or "except*" clauses, but not both. The exception
1891 type for matching is mandatory in the case of "except*", so "except*:"
1892 is a syntax error. The type is interpreted as in the case of "except",
1893 but matching is performed on the exceptions contained in the group
1894 that is being handled. An "TypeError" is raised if a matching type is
1895 a subclass of "BaseExceptionGroup", because that would have ambiguous
1896 semantics.
1897
1898 When an exception group is raised in the try block, each "except*"
1899 clause splits (see "split()") it into the subgroups of matching and
1900 non-matching exceptions. If the matching subgroup is not empty, it
1901 becomes the handled exception (the value returned from
1902 "sys.exception()") and assigned to the target of the "except*" clause
1903 (if there is one). Then, the body of the "except*" clause executes. If
1904 the non-matching subgroup is not empty, it is processed by the next
1905 "except*" in the same manner. This continues until all exceptions in
1906 the group have been matched, or the last "except*" clause has run.
1907
1908 After all "except*" clauses execute, the group of unhandled exceptions
1909 is merged with any exceptions that were raised or re-raised from
1910 within "except*" clauses. This merged exception group propagates on.:
1911
1912 >>> try:
1913 ... raise ExceptionGroup("eg",
1914 ... [ValueError(1), TypeError(2), OSError(3), OSError(4)])
1915 ... except* TypeError as e:
1916 ... print(f'caught {type(e)} with nested {e.exceptions}')
1917 ... except* OSError as e:
1918 ... print(f'caught {type(e)} with nested {e.exceptions}')
1919 ...
1920 caught <class 'ExceptionGroup'> with nested (TypeError(2),)
1921 caught <class 'ExceptionGroup'> with nested (OSError(3), OSError(4))
1922 + Exception Group Traceback (most recent call last):
1923 | File "<doctest default[0]>", line 2, in <module>
1924 | raise ExceptionGroup("eg",
1925 | [ValueError(1), TypeError(2), OSError(3), OSError(4)])
1926 | ExceptionGroup: eg (1 sub-exception)
1927 +-+---------------- 1 ----------------
1928 | ValueError: 1
1929 +------------------------------------
1930
1931 If the exception raised from the "try" block is not an exception group
1932 and its type matches one of the "except*" clauses, it is caught and
1933 wrapped by an exception group with an empty message string. This
1934 ensures that the type of the target "e" is consistently
1935 "BaseExceptionGroup":
1936
1937 >>> try:
1938 ... raise BlockingIOError
1939 ... except* BlockingIOError as e:
1940 ... print(repr(e))
1941 ...
1942 ExceptionGroup('', (BlockingIOError(),))
1943
1944 "break", "continue" and "return" cannot appear in an "except*" clause.
1945
1946
1947 "else" clause
1948 -------------
1949
1950 The optional "else" clause is executed if the control flow leaves the
1951 "try" suite, no exception was raised, and no "return", "continue", or
1952 "break" statement was executed. Exceptions in the "else" clause are
1953 not handled by the preceding "except" clauses.
1954
1955
1956 "finally" clause
1957 ----------------
1958
1959 If "finally" is present, it specifies a ‘cleanup’ handler. The "try"
1960 clause is executed, including any "except" and "else" clauses. If an
1961 exception occurs in any of the clauses and is not handled, the
1962 exception is temporarily saved. The "finally" clause is executed. If
1963 there is a saved exception it is re-raised at the end of the "finally"
1964 clause. If the "finally" clause raises another exception, the saved
1965 exception is set as the context of the new exception. If the "finally"
1966 clause executes a "return", "break" or "continue" statement, the saved
1967 exception is discarded:
1968
1969 >>> def f():
1970 ... try:
1971 ... 1/0
1972 ... finally:
1973 ... return 42
1974 ...
1975 >>> f()
1976 42
1977
1978 The exception information is not available to the program during
1979 execution of the "finally" clause.
1980
1981 When a "return", "break" or "continue" statement is executed in the
1982 "try" suite of a "try"…"finally" statement, the "finally" clause is
1983 also executed ‘on the way out.’
1984
1985 The return value of a function is determined by the last "return"
1986 statement executed. Since the "finally" clause always executes, a
1987 "return" statement executed in the "finally" clause will always be the
1988 last one executed:
1989
1990 >>> def foo():
1991 ... try:
1992 ... return 'try'
1993 ... finally:
1994 ... return 'finally'
1995 ...
1996 >>> foo()
1997 'finally'
1998
1999 Changed in version 3.8: Prior to Python 3.8, a "continue" statement
2000 was illegal in the "finally" clause due to a problem with the
2001 implementation.
2002
2003
2004 The "with" statement
2005 ====================
2006
2007 The "with" statement is used to wrap the execution of a block with
2008 methods defined by a context manager (see section With Statement
2009 Context Managers). This allows common "try"…"except"…"finally" usage
2010 patterns to be encapsulated for convenient reuse.
2011
2012 with_stmt ::= "with" ( "(" with_stmt_contents ","? ")" | with_stmt_contents ) ":" suite
2013 with_stmt_contents ::= with_item ("," with_item)*
2014 with_item ::= expression ["as" target]
2015
2016 The execution of the "with" statement with one “item” proceeds as
2017 follows:
2018
2019 1. The context expression (the expression given in the "with_item") is
2020 evaluated to obtain a context manager.
2021
2022 2. The context manager’s "__enter__()" is loaded for later use.
2023
2024 3. The context manager’s "__exit__()" is loaded for later use.
2025
2026 4. The context manager’s "__enter__()" method is invoked.
2027
2028 5. If a target was included in the "with" statement, the return value
2029 from "__enter__()" is assigned to it.
2030
2031 Note:
2032
2033 The "with" statement guarantees that if the "__enter__()" method
2034 returns without an error, then "__exit__()" will always be
2035 called. Thus, if an error occurs during the assignment to the
2036 target list, it will be treated the same as an error occurring
2037 within the suite would be. See step 7 below.
2038
2039 6. The suite is executed.
2040
2041 7. The context manager’s "__exit__()" method is invoked. If an
2042 exception caused the suite to be exited, its type, value, and
2043 traceback are passed as arguments to "__exit__()". Otherwise, three
2044 "None" arguments are supplied.
2045
2046 If the suite was exited due to an exception, and the return value
2047 from the "__exit__()" method was false, the exception is reraised.
2048 If the return value was true, the exception is suppressed, and
2049 execution continues with the statement following the "with"
2050 statement.
2051
2052 If the suite was exited for any reason other than an exception, the
2053 return value from "__exit__()" is ignored, and execution proceeds
2054 at the normal location for the kind of exit that was taken.
2055
2056 The following code:
2057
2058 with EXPRESSION as TARGET:
2059 SUITE
2060
2061 is semantically equivalent to:
2062
2063 manager = (EXPRESSION)
2064 enter = type(manager).__enter__
2065 exit = type(manager).__exit__
2066 value = enter(manager)
2067 hit_except = False
2068
2069 try:
2070 TARGET = value
2071 SUITE
2072 except:
2073 hit_except = True
2074 if not exit(manager, *sys.exc_info()):
2075 raise
2076 finally:
2077 if not hit_except:
2078 exit(manager, None, None, None)
2079
2080 With more than one item, the context managers are processed as if
2081 multiple "with" statements were nested:
2082
2083 with A() as a, B() as b:
2084 SUITE
2085
2086 is semantically equivalent to:
2087
2088 with A() as a:
2089 with B() as b:
2090 SUITE
2091
2092 You can also write multi-item context managers in multiple lines if
2093 the items are surrounded by parentheses. For example:
2094
2095 with (
2096 A() as a,
2097 B() as b,
2098 ):
2099 SUITE
2100
2101 Changed in version 3.1: Support for multiple context expressions.
2102
2103 Changed in version 3.10: Support for using grouping parentheses to
2104 break the statement in multiple lines.
2105
2106 See also:
2107
2108 **PEP 343** - The “with” statement
2109 The specification, background, and examples for the Python "with"
2110 statement.
2111
2112
2113 The "match" statement
2114 =====================
2115
2116 Added in version 3.10.
2117
2118 The match statement is used for pattern matching. Syntax:
2119
2120 match_stmt ::= 'match' subject_expr ":" NEWLINE INDENT case_block+ DEDENT
2121 subject_expr ::= star_named_expression "," star_named_expressions?
2122 | named_expression
2123 case_block ::= 'case' patterns [guard] ":" block
2124
2125 Note:
2126
2127 This section uses single quotes to denote soft keywords.
2128
2129 Pattern matching takes a pattern as input (following "case") and a
2130 subject value (following "match"). The pattern (which may contain
2131 subpatterns) is matched against the subject value. The outcomes are:
2132
2133 * A match success or failure (also termed a pattern success or
2134 failure).
2135
2136 * Possible binding of matched values to a name. The prerequisites for
2137 this are further discussed below.
2138
2139 The "match" and "case" keywords are soft keywords.
2140
2141 See also:
2142
2143 * **PEP 634** – Structural Pattern Matching: Specification
2144
2145 * **PEP 636** – Structural Pattern Matching: Tutorial
2146
2147
2148 Overview
2149 --------
2150
2151 Here’s an overview of the logical flow of a match statement:
2152
2153 1. The subject expression "subject_expr" is evaluated and a resulting
2154 subject value obtained. If the subject expression contains a comma,
2155 a tuple is constructed using the standard rules.
2156
2157 2. Each pattern in a "case_block" is attempted to match with the
2158 subject value. The specific rules for success or failure are
2159 described below. The match attempt can also bind some or all of the
2160 standalone names within the pattern. The precise pattern binding
2161 rules vary per pattern type and are specified below. **Name
2162 bindings made during a successful pattern match outlive the
2163 executed block and can be used after the match statement**.
2164
2165 Note:
2166
2167 During failed pattern matches, some subpatterns may succeed. Do
2168 not rely on bindings being made for a failed match. Conversely,
2169 do not rely on variables remaining unchanged after a failed
2170 match. The exact behavior is dependent on implementation and may
2171 vary. This is an intentional decision made to allow different
2172 implementations to add optimizations.
2173
2174 3. If the pattern succeeds, the corresponding guard (if present) is
2175 evaluated. In this case all name bindings are guaranteed to have
2176 happened.
2177
2178 * If the guard evaluates as true or is missing, the "block" inside
2179 "case_block" is executed.
2180
2181 * Otherwise, the next "case_block" is attempted as described above.
2182
2183 * If there are no further case blocks, the match statement is
2184 completed.
2185
2186 Note:
2187
2188 Users should generally never rely on a pattern being evaluated.
2189 Depending on implementation, the interpreter may cache values or use
2190 other optimizations which skip repeated evaluations.
2191
2192 A sample match statement:
2193
2194 >>> flag = False
2195 >>> match (100, 200):
2196 ... case (100, 300): # Mismatch: 200 != 300
2197 ... print('Case 1')
2198 ... case (100, 200) if flag: # Successful match, but guard fails
2199 ... print('Case 2')
2200 ... case (100, y): # Matches and binds y to 200
2201 ... print(f'Case 3, y: {y}')
2202 ... case _: # Pattern not attempted
2203 ... print('Case 4, I match anything!')
2204 ...
2205 Case 3, y: 200
2206
2207 In this case, "if flag" is a guard. Read more about that in the next
2208 section.
2209
2210
2211 Guards
2212 ------
2213
2214 guard ::= "if" named_expression
2215
2216 A "guard" (which is part of the "case") must succeed for code inside
2217 the "case" block to execute. It takes the form: "if" followed by an
2218 expression.
2219
2220 The logical flow of a "case" block with a "guard" follows:
2221
2222 1. Check that the pattern in the "case" block succeeded. If the
2223 pattern failed, the "guard" is not evaluated and the next "case"
2224 block is checked.
2225
2226 2. If the pattern succeeded, evaluate the "guard".
2227
2228 * If the "guard" condition evaluates as true, the case block is
2229 selected.
2230
2231 * If the "guard" condition evaluates as false, the case block is
2232 not selected.
2233
2234 * If the "guard" raises an exception during evaluation, the
2235 exception bubbles up.
2236
2237 Guards are allowed to have side effects as they are expressions.
2238 Guard evaluation must proceed from the first to the last case block,
2239 one at a time, skipping case blocks whose pattern(s) don’t all
2240 succeed. (I.e., guard evaluation must happen in order.) Guard
2241 evaluation must stop once a case block is selected.
2242
2243
2244 Irrefutable Case Blocks
2245 -----------------------
2246
2247 An irrefutable case block is a match-all case block. A match
2248 statement may have at most one irrefutable case block, and it must be
2249 last.
2250
2251 A case block is considered irrefutable if it has no guard and its
2252 pattern is irrefutable. A pattern is considered irrefutable if we can
2253 prove from its syntax alone that it will always succeed. Only the
2254 following patterns are irrefutable:
2255
2256 * AS Patterns whose left-hand side is irrefutable
2257
2258 * OR Patterns containing at least one irrefutable pattern
2259
2260 * Capture Patterns
2261
2262 * Wildcard Patterns
2263
2264 * parenthesized irrefutable patterns
2265
2266
2267 Patterns
2268 --------
2269
2270 Note:
2271
2272 This section uses grammar notations beyond standard EBNF:
2273
2274 * the notation "SEP.RULE+" is shorthand for "RULE (SEP RULE)*"
2275
2276 * the notation "!RULE" is shorthand for a negative lookahead
2277 assertion
2278
2279 The top-level syntax for "patterns" is:
2280
2281 patterns ::= open_sequence_pattern | pattern
2282 pattern ::= as_pattern | or_pattern
2283 closed_pattern ::= | literal_pattern
2284 | capture_pattern
2285 | wildcard_pattern
2286 | value_pattern
2287 | group_pattern
2288 | sequence_pattern
2289 | mapping_pattern
2290 | class_pattern
2291
2292 The descriptions below will include a description “in simple terms” of
2293 what a pattern does for illustration purposes (credits to Raymond
2294 Hettinger for a document that inspired most of the descriptions). Note
2295 that these descriptions are purely for illustration purposes and **may
2296 not** reflect the underlying implementation. Furthermore, they do not
2297 cover all valid forms.
2298
2299
2300 OR Patterns
2301 ~~~~~~~~~~~
2302
2303 An OR pattern is two or more patterns separated by vertical bars "|".
2304 Syntax:
2305
2306 or_pattern ::= "|".closed_pattern+
2307
2308 Only the final subpattern may be irrefutable, and each subpattern must
2309 bind the same set of names to avoid ambiguity.
2310
2311 An OR pattern matches each of its subpatterns in turn to the subject
2312 value, until one succeeds. The OR pattern is then considered
2313 successful. Otherwise, if none of the subpatterns succeed, the OR
2314 pattern fails.
2315
2316 In simple terms, "P1 | P2 | ..." will try to match "P1", if it fails
2317 it will try to match "P2", succeeding immediately if any succeeds,
2318 failing otherwise.
2319
2320
2321 AS Patterns
2322 ~~~~~~~~~~~
2323
2324 An AS pattern matches an OR pattern on the left of the "as" keyword
2325 against a subject. Syntax:
2326
2327 as_pattern ::= or_pattern "as" capture_pattern
2328
2329 If the OR pattern fails, the AS pattern fails. Otherwise, the AS
2330 pattern binds the subject to the name on the right of the as keyword
2331 and succeeds. "capture_pattern" cannot be a "_".
2332
2333 In simple terms "P as NAME" will match with "P", and on success it
2334 will set "NAME = <subject>".
2335
2336
2337 Literal Patterns
2338 ~~~~~~~~~~~~~~~~
2339
2340 A literal pattern corresponds to most literals in Python. Syntax:
2341
2342 literal_pattern ::= signed_number
2343 | signed_number "+" NUMBER
2344 | signed_number "-" NUMBER
2345 | strings
2346 | "None"
2347 | "True"
2348 | "False"
2349 signed_number ::= ["-"] NUMBER
2350
2351 The rule "strings" and the token "NUMBER" are defined in the standard
2352 Python grammar. Triple-quoted strings are supported. Raw strings and
2353 byte strings are supported. f-strings are not supported.
2354
2355 The forms "signed_number '+' NUMBER" and "signed_number '-' NUMBER"
2356 are for expressing complex numbers; they require a real number on the
2357 left and an imaginary number on the right. E.g. "3 + 4j".
2358
2359 In simple terms, "LITERAL" will succeed only if "<subject> ==
2360 LITERAL". For the singletons "None", "True" and "False", the "is"
2361 operator is used.
2362
2363
2364 Capture Patterns
2365 ~~~~~~~~~~~~~~~~
2366
2367 A capture pattern binds the subject value to a name. Syntax:
2368
2369 capture_pattern ::= !'_' NAME
2370
2371 A single underscore "_" is not a capture pattern (this is what "!'_'"
2372 expresses). It is instead treated as a "wildcard_pattern".
2373
2374 In a given pattern, a given name can only be bound once. E.g. "case
2375 x, x: ..." is invalid while "case [x] | x: ..." is allowed.
2376
2377 Capture patterns always succeed. The binding follows scoping rules
2378 established by the assignment expression operator in **PEP 572**; the
2379 name becomes a local variable in the closest containing function scope
2380 unless there’s an applicable "global" or "nonlocal" statement.
2381
2382 In simple terms "NAME" will always succeed and it will set "NAME =
2383 <subject>".
2384
2385
2386 Wildcard Patterns
2387 ~~~~~~~~~~~~~~~~~
2388
2389 A wildcard pattern always succeeds (matches anything) and binds no
2390 name. Syntax:
2391
2392 wildcard_pattern ::= '_'
2393
2394 "_" is a soft keyword within any pattern, but only within patterns.
2395 It is an identifier, as usual, even within "match" subject
2396 expressions, "guard"s, and "case" blocks.
2397
2398 In simple terms, "_" will always succeed.
2399
2400
2401 Value Patterns
2402 ~~~~~~~~~~~~~~
2403
2404 A value pattern represents a named value in Python. Syntax:
2405
2406 value_pattern ::= attr
2407 attr ::= name_or_attr "." NAME
2408 name_or_attr ::= attr | NAME
2409
2410 The dotted name in the pattern is looked up using standard Python name
2411 resolution rules. The pattern succeeds if the value found compares
2412 equal to the subject value (using the "==" equality operator).
2413
2414 In simple terms "NAME1.NAME2" will succeed only if "<subject> ==
2415 NAME1.NAME2"
2416
2417 Note:
2418
2419 If the same value occurs multiple times in the same match statement,
2420 the interpreter may cache the first value found and reuse it rather
2421 than repeat the same lookup. This cache is strictly tied to a given
2422 execution of a given match statement.
2423
2424
2425 Group Patterns
2426 ~~~~~~~~~~~~~~
2427
2428 A group pattern allows users to add parentheses around patterns to
2429 emphasize the intended grouping. Otherwise, it has no additional
2430 syntax. Syntax:
2431
2432 group_pattern ::= "(" pattern ")"
2433
2434 In simple terms "(P)" has the same effect as "P".
2435
2436
2437 Sequence Patterns
2438 ~~~~~~~~~~~~~~~~~
2439
2440 A sequence pattern contains several subpatterns to be matched against
2441 sequence elements. The syntax is similar to the unpacking of a list or
2442 tuple.
2443
2444 sequence_pattern ::= "[" [maybe_sequence_pattern] "]"
2445 | "(" [open_sequence_pattern] ")"
2446 open_sequence_pattern ::= maybe_star_pattern "," [maybe_sequence_pattern]
2447 maybe_sequence_pattern ::= ",".maybe_star_pattern+ ","?
2448 maybe_star_pattern ::= star_pattern | pattern
2449 star_pattern ::= "*" (capture_pattern | wildcard_pattern)
2450
2451 There is no difference if parentheses or square brackets are used for
2452 sequence patterns (i.e. "(...)" vs "[...]" ).
2453
2454 Note:
2455
2456 A single pattern enclosed in parentheses without a trailing comma
2457 (e.g. "(3 | 4)") is a group pattern. While a single pattern enclosed
2458 in square brackets (e.g. "[3 | 4]") is still a sequence pattern.
2459
2460 At most one star subpattern may be in a sequence pattern. The star
2461 subpattern may occur in any position. If no star subpattern is
2462 present, the sequence pattern is a fixed-length sequence pattern;
2463 otherwise it is a variable-length sequence pattern.
2464
2465 The following is the logical flow for matching a sequence pattern
2466 against a subject value:
2467
2468 1. If the subject value is not a sequence [2], the sequence pattern
2469 fails.
2470
2471 2. If the subject value is an instance of "str", "bytes" or
2472 "bytearray" the sequence pattern fails.
2473
2474 3. The subsequent steps depend on whether the sequence pattern is
2475 fixed or variable-length.
2476
2477 If the sequence pattern is fixed-length:
2478
2479 1. If the length of the subject sequence is not equal to the number
2480 of subpatterns, the sequence pattern fails
2481
2482 2. Subpatterns in the sequence pattern are matched to their
2483 corresponding items in the subject sequence from left to right.
2484 Matching stops as soon as a subpattern fails. If all
2485 subpatterns succeed in matching their corresponding item, the
2486 sequence pattern succeeds.
2487
2488 Otherwise, if the sequence pattern is variable-length:
2489
2490 1. If the length of the subject sequence is less than the number of
2491 non-star subpatterns, the sequence pattern fails.
2492
2493 2. The leading non-star subpatterns are matched to their
2494 corresponding items as for fixed-length sequences.
2495
2496 3. If the previous step succeeds, the star subpattern matches a
2497 list formed of the remaining subject items, excluding the
2498 remaining items corresponding to non-star subpatterns following
2499 the star subpattern.
2500
2501 4. Remaining non-star subpatterns are matched to their
2502 corresponding subject items, as for a fixed-length sequence.
2503
2504 Note:
2505
2506 The length of the subject sequence is obtained via "len()" (i.e.
2507 via the "__len__()" protocol). This length may be cached by the
2508 interpreter in a similar manner as value patterns.
2509
2510 In simple terms "[P1, P2, P3," … ", P<N>]" matches only if all the
2511 following happens:
2512
2513 * check "<subject>" is a sequence
2514
2515 * "len(subject) == <N>"
2516
2517 * "P1" matches "<subject>[0]" (note that this match can also bind
2518 names)
2519
2520 * "P2" matches "<subject>[1]" (note that this match can also bind
2521 names)
2522
2523 * … and so on for the corresponding pattern/element.
2524
2525
2526 Mapping Patterns
2527 ~~~~~~~~~~~~~~~~
2528
2529 A mapping pattern contains one or more key-value patterns. The syntax
2530 is similar to the construction of a dictionary. Syntax:
2531
2532 mapping_pattern ::= "{" [items_pattern] "}"
2533 items_pattern ::= ",".key_value_pattern+ ","?
2534 key_value_pattern ::= (literal_pattern | value_pattern) ":" pattern
2535 | double_star_pattern
2536 double_star_pattern ::= "**" capture_pattern
2537
2538 At most one double star pattern may be in a mapping pattern. The
2539 double star pattern must be the last subpattern in the mapping
2540 pattern.
2541
2542 Duplicate keys in mapping patterns are disallowed. Duplicate literal
2543 keys will raise a "SyntaxError". Two keys that otherwise have the same
2544 value will raise a "ValueError" at runtime.
2545
2546 The following is the logical flow for matching a mapping pattern
2547 against a subject value:
2548
2549 1. If the subject value is not a mapping [3],the mapping pattern
2550 fails.
2551
2552 2. If every key given in the mapping pattern is present in the subject
2553 mapping, and the pattern for each key matches the corresponding
2554 item of the subject mapping, the mapping pattern succeeds.
2555
2556 3. If duplicate keys are detected in the mapping pattern, the pattern
2557 is considered invalid. A "SyntaxError" is raised for duplicate
2558 literal values; or a "ValueError" for named keys of the same value.
2559
2560 Note:
2561
2562 Key-value pairs are matched using the two-argument form of the
2563 mapping subject’s "get()" method. Matched key-value pairs must
2564 already be present in the mapping, and not created on-the-fly via
2565 "__missing__()" or "__getitem__()".
2566
2567 In simple terms "{KEY1: P1, KEY2: P2, ... }" matches only if all the
2568 following happens:
2569
2570 * check "<subject>" is a mapping
2571
2572 * "KEY1 in <subject>"
2573
2574 * "P1" matches "<subject>[KEY1]"
2575
2576 * … and so on for the corresponding KEY/pattern pair.
2577
2578
2579 Class Patterns
2580 ~~~~~~~~~~~~~~
2581
2582 A class pattern represents a class and its positional and keyword
2583 arguments (if any). Syntax:
2584
2585 class_pattern ::= name_or_attr "(" [pattern_arguments ","?] ")"
2586 pattern_arguments ::= positional_patterns ["," keyword_patterns]
2587 | keyword_patterns
2588 positional_patterns ::= ",".pattern+
2589 keyword_patterns ::= ",".keyword_pattern+
2590 keyword_pattern ::= NAME "=" pattern
2591
2592 The same keyword should not be repeated in class patterns.
2593
2594 The following is the logical flow for matching a class pattern against
2595 a subject value:
2596
2597 1. If "name_or_attr" is not an instance of the builtin "type" , raise
2598 "TypeError".
2599
2600 2. If the subject value is not an instance of "name_or_attr" (tested
2601 via "isinstance()"), the class pattern fails.
2602
2603 3. If no pattern arguments are present, the pattern succeeds.
2604 Otherwise, the subsequent steps depend on whether keyword or
2605 positional argument patterns are present.
2606
2607 For a number of built-in types (specified below), a single
2608 positional subpattern is accepted which will match the entire
2609 subject; for these types keyword patterns also work as for other
2610 types.
2611
2612 If only keyword patterns are present, they are processed as
2613 follows, one by one:
2614
2615 1. The keyword is looked up as an attribute on the subject.
2616
2617 * If this raises an exception other than "AttributeError", the
2618 exception bubbles up.
2619
2620 * If this raises "AttributeError", the class pattern has failed.
2621
2622 * Else, the subpattern associated with the keyword pattern is
2623 matched against the subject’s attribute value. If this fails,
2624 the class pattern fails; if this succeeds, the match proceeds
2625 to the next keyword.
2626
2627 2. If all keyword patterns succeed, the class pattern succeeds.
2628
2629 If any positional patterns are present, they are converted to
2630 keyword patterns using the "__match_args__" attribute on the class
2631 "name_or_attr" before matching:
2632
2633 1. The equivalent of "getattr(cls, "__match_args__", ())" is
2634 called.
2635
2636 * If this raises an exception, the exception bubbles up.
2637
2638 * If the returned value is not a tuple, the conversion fails and
2639 "TypeError" is raised.
2640
2641 * If there are more positional patterns than
2642 "len(cls.__match_args__)", "TypeError" is raised.
2643
2644 * Otherwise, positional pattern "i" is converted to a keyword
2645 pattern using "__match_args__[i]" as the keyword.
2646 "__match_args__[i]" must be a string; if not "TypeError" is
2647 raised.
2648
2649 * If there are duplicate keywords, "TypeError" is raised.
2650
2651 See also:
2652
2653 Customizing positional arguments in class pattern matching
2654
2655 2. Once all positional patterns have been converted to keyword
2656 patterns, the match proceeds as if there were only keyword
2657 patterns.
2658
2659 For the following built-in types the handling of positional
2660 subpatterns is different:
2661
2662 * "bool"
2663
2664 * "bytearray"
2665
2666 * "bytes"
2667
2668 * "dict"
2669
2670 * "float"
2671
2672 * "frozenset"
2673
2674 * "int"
2675
2676 * "list"
2677
2678 * "set"
2679
2680 * "str"
2681
2682 * "tuple"
2683
2684 These classes accept a single positional argument, and the pattern
2685 there is matched against the whole object rather than an attribute.
2686 For example "int(0|1)" matches the value "0", but not the value
2687 "0.0".
2688
2689 In simple terms "CLS(P1, attr=P2)" matches only if the following
2690 happens:
2691
2692 * "isinstance(<subject>, CLS)"
2693
2694 * convert "P1" to a keyword pattern using "CLS.__match_args__"
2695
2696 * For each keyword argument "attr=P2":
2697
2698 * "hasattr(<subject>, "attr")"
2699
2700 * "P2" matches "<subject>.attr"
2701
2702 * … and so on for the corresponding keyword argument/pattern pair.
2703
2704 See also:
2705
2706 * **PEP 634** – Structural Pattern Matching: Specification
2707
2708 * **PEP 636** – Structural Pattern Matching: Tutorial
2709
2710
2711 Function definitions
2712 ====================
2713
2714 A function definition defines a user-defined function object (see
2715 section The standard type hierarchy):
2716
2717 funcdef ::= [decorators] "def" funcname [type_params] "(" [parameter_list] ")"
2718 ["->" expression] ":" suite
2719 decorators ::= decorator+
2720 decorator ::= "@" assignment_expression NEWLINE
2721 parameter_list ::= defparameter ("," defparameter)* "," "/" ["," [parameter_list_no_posonly]]
2722 | parameter_list_no_posonly
2723 parameter_list_no_posonly ::= defparameter ("," defparameter)* ["," [parameter_list_starargs]]
2724 | parameter_list_starargs
2725 parameter_list_starargs ::= "*" [star_parameter] ("," defparameter)* ["," [parameter_star_kwargs]]
2726 | "*" ("," defparameter)+ ["," [parameter_star_kwargs]]
2727 | parameter_star_kwargs
2728 parameter_star_kwargs ::= "**" parameter [","]
2729 parameter ::= identifier [":" expression]
2730 star_parameter ::= identifier [":" ["*"] expression]
2731 defparameter ::= parameter ["=" expression]
2732 funcname ::= identifier
2733
2734 A function definition is an executable statement. Its execution binds
2735 the function name in the current local namespace to a function object
2736 (a wrapper around the executable code for the function). This
2737 function object contains a reference to the current global namespace
2738 as the global namespace to be used when the function is called.
2739
2740 The function definition does not execute the function body; this gets
2741 executed only when the function is called. [4]
2742
2743 A function definition may be wrapped by one or more *decorator*
2744 expressions. Decorator expressions are evaluated when the function is
2745 defined, in the scope that contains the function definition. The
2746 result must be a callable, which is invoked with the function object
2747 as the only argument. The returned value is bound to the function name
2748 instead of the function object. Multiple decorators are applied in
2749 nested fashion. For example, the following code
2750
2751 @f1(arg)
2752 @f2
2753 def func(): pass
2754
2755 is roughly equivalent to
2756
2757 def func(): pass
2758 func = f1(arg)(f2(func))
2759
2760 except that the original function is not temporarily bound to the name
2761 "func".
2762
2763 Changed in version 3.9: Functions may be decorated with any valid
2764 "assignment_expression". Previously, the grammar was much more
2765 restrictive; see **PEP 614** for details.
2766
2767 A list of type parameters may be given in square brackets between the
2768 function’s name and the opening parenthesis for its parameter list.
2769 This indicates to static type checkers that the function is generic.
2770 At runtime, the type parameters can be retrieved from the function’s
2771 "__type_params__" attribute. See Generic functions for more.
2772
2773 Changed in version 3.12: Type parameter lists are new in Python 3.12.
2774
2775 When one or more *parameters* have the form *parameter* "="
2776 *expression*, the function is said to have “default parameter values.”
2777 For a parameter with a default value, the corresponding *argument* may
2778 be omitted from a call, in which case the parameter’s default value is
2779 substituted. If a parameter has a default value, all following
2780 parameters up until the “"*"” must also have a default value — this is
2781 a syntactic restriction that is not expressed by the grammar.
2782
2783 **Default parameter values are evaluated from left to right when the
2784 function definition is executed.** This means that the expression is
2785 evaluated once, when the function is defined, and that the same “pre-
2786 computed” value is used for each call. This is especially important
2787 to understand when a default parameter value is a mutable object, such
2788 as a list or a dictionary: if the function modifies the object (e.g.
2789 by appending an item to a list), the default parameter value is in
2790 effect modified. This is generally not what was intended. A way
2791 around this is to use "None" as the default, and explicitly test for
2792 it in the body of the function, e.g.:
2793
2794 def whats_on_the_telly(penguin=None):
2795 if penguin is None:
2796 penguin = []
2797 penguin.append("property of the zoo")
2798 return penguin
2799
2800 Function call semantics are described in more detail in section Calls.
2801 A function call always assigns values to all parameters mentioned in
2802 the parameter list, either from positional arguments, from keyword
2803 arguments, or from default values. If the form “"*identifier"” is
2804 present, it is initialized to a tuple receiving any excess positional
2805 parameters, defaulting to the empty tuple. If the form
2806 “"**identifier"” is present, it is initialized to a new ordered
2807 mapping receiving any excess keyword arguments, defaulting to a new
2808 empty mapping of the same type. Parameters after “"*"” or
2809 “"*identifier"” are keyword-only parameters and may only be passed by
2810 keyword arguments. Parameters before “"/"” are positional-only
2811 parameters and may only be passed by positional arguments.
2812
2813 Changed in version 3.8: The "/" function parameter syntax may be used
2814 to indicate positional-only parameters. See **PEP 570** for details.
2815
2816 Parameters may have an *annotation* of the form “": expression"”
2817 following the parameter name. Any parameter may have an annotation,
2818 even those of the form "*identifier" or "**identifier". (As a special
2819 case, parameters of the form "*identifier" may have an annotation “":
2820 *expression"”.) Functions may have “return” annotation of the form
2821 “"-> expression"” after the parameter list. These annotations can be
2822 any valid Python expression. The presence of annotations does not
2823 change the semantics of a function. The annotation values are
2824 available as values of a dictionary keyed by the parameters’ names in
2825 the "__annotations__" attribute of the function object. If the
2826 "annotations" import from "__future__" is used, annotations are
2827 preserved as strings at runtime which enables postponed evaluation.
2828 Otherwise, they are evaluated when the function definition is
2829 executed. In this case annotations may be evaluated in a different
2830 order than they appear in the source code.
2831
2832 Changed in version 3.11: Parameters of the form “"*identifier"” may
2833 have an annotation “": *expression"”. See **PEP 646**.
2834
2835 It is also possible to create anonymous functions (functions not bound
2836 to a name), for immediate use in expressions. This uses lambda
2837 expressions, described in section Lambdas. Note that the lambda
2838 expression is merely a shorthand for a simplified function definition;
2839 a function defined in a “"def"” statement can be passed around or
2840 assigned to another name just like a function defined by a lambda
2841 expression. The “"def"” form is actually more powerful since it
2842 allows the execution of multiple statements and annotations.
2843
2844 **Programmer’s note:** Functions are first-class objects. A “"def"”
2845 statement executed inside a function definition defines a local
2846 function that can be returned or passed around. Free variables used
2847 in the nested function can access the local variables of the function
2848 containing the def. See section Naming and binding for details.
2849
2850 See also:
2851
2852 **PEP 3107** - Function Annotations
2853 The original specification for function annotations.
2854
2855 **PEP 484** - Type Hints
2856 Definition of a standard meaning for annotations: type hints.
2857
2858 **PEP 526** - Syntax for Variable Annotations
2859 Ability to type hint variable declarations, including class
2860 variables and instance variables.
2861
2862 **PEP 563** - Postponed Evaluation of Annotations
2863 Support for forward references within annotations by preserving
2864 annotations in a string form at runtime instead of eager
2865 evaluation.
2866
2867 **PEP 318** - Decorators for Functions and Methods
2868 Function and method decorators were introduced. Class decorators
2869 were introduced in **PEP 3129**.
2870
2871
2872 Class definitions
2873 =================
2874
2875 A class definition defines a class object (see section The standard
2876 type hierarchy):
2877
2878 classdef ::= [decorators] "class" classname [type_params] [inheritance] ":" suite
2879 inheritance ::= "(" [argument_list] ")"
2880 classname ::= identifier
2881
2882 A class definition is an executable statement. The inheritance list
2883 usually gives a list of base classes (see Metaclasses for more
2884 advanced uses), so each item in the list should evaluate to a class
2885 object which allows subclassing. Classes without an inheritance list
2886 inherit, by default, from the base class "object"; hence,
2887
2888 class Foo:
2889 pass
2890
2891 is equivalent to
2892
2893 class Foo(object):
2894 pass
2895
2896 The class’s suite is then executed in a new execution frame (see
2897 Naming and binding), using a newly created local namespace and the
2898 original global namespace. (Usually, the suite contains mostly
2899 function definitions.) When the class’s suite finishes execution, its
2900 execution frame is discarded but its local namespace is saved. [5] A
2901 class object is then created using the inheritance list for the base
2902 classes and the saved local namespace for the attribute dictionary.
2903 The class name is bound to this class object in the original local
2904 namespace.
2905
2906 The order in which attributes are defined in the class body is
2907 preserved in the new class’s "__dict__". Note that this is reliable
2908 only right after the class is created and only for classes that were
2909 defined using the definition syntax.
2910
2911 Class creation can be customized heavily using metaclasses.
2912
2913 Classes can also be decorated: just like when decorating functions,
2914
2915 @f1(arg)
2916 @f2
2917 class Foo: pass
2918
2919 is roughly equivalent to
2920
2921 class Foo: pass
2922 Foo = f1(arg)(f2(Foo))
2923
2924 The evaluation rules for the decorator expressions are the same as for
2925 function decorators. The result is then bound to the class name.
2926
2927 Changed in version 3.9: Classes may be decorated with any valid
2928 "assignment_expression". Previously, the grammar was much more
2929 restrictive; see **PEP 614** for details.
2930
2931 A list of type parameters may be given in square brackets immediately
2932 after the class’s name. This indicates to static type checkers that
2933 the class is generic. At runtime, the type parameters can be retrieved
2934 from the class’s "__type_params__" attribute. See Generic classes for
2935 more.
2936
2937 Changed in version 3.12: Type parameter lists are new in Python 3.12.
2938
2939 **Programmer’s note:** Variables defined in the class definition are
2940 class attributes; they are shared by instances. Instance attributes
2941 can be set in a method with "self.name = value". Both class and
2942 instance attributes are accessible through the notation “"self.name"”,
2943 and an instance attribute hides a class attribute with the same name
2944 when accessed in this way. Class attributes can be used as defaults
2945 for instance attributes, but using mutable values there can lead to
2946 unexpected results. Descriptors can be used to create instance
2947 variables with different implementation details.
2948
2949 See also:
2950
2951 **PEP 3115** - Metaclasses in Python 3000
2952 The proposal that changed the declaration of metaclasses to the
2953 current syntax, and the semantics for how classes with
2954 metaclasses are constructed.
2955
2956 **PEP 3129** - Class Decorators
2957 The proposal that added class decorators. Function and method
2958 decorators were introduced in **PEP 318**.
2959
2960
2961 Coroutines
2962 ==========
2963
2964 Added in version 3.5.
2965
2966
2967 Coroutine function definition
2968 -----------------------------
2969
2970 async_funcdef ::= [decorators] "async" "def" funcname "(" [parameter_list] ")"
2971 ["->" expression] ":" suite
2972
2973 Execution of Python coroutines can be suspended and resumed at many
2974 points (see *coroutine*). "await" expressions, "async for" and "async
2975 with" can only be used in the body of a coroutine function.
2976
2977 Functions defined with "async def" syntax are always coroutine
2978 functions, even if they do not contain "await" or "async" keywords.
2979
2980 It is a "SyntaxError" to use a "yield from" expression inside the body
2981 of a coroutine function.
2982
2983 An example of a coroutine function:
2984
2985 async def func(param1, param2):
2986 do_stuff()
2987 await some_coroutine()
2988
2989 Changed in version 3.7: "await" and "async" are now keywords;
2990 previously they were only treated as such inside the body of a
2991 coroutine function.
2992
2993
2994 The "async for" statement
2995 -------------------------
2996
2997 async_for_stmt ::= "async" for_stmt
2998
2999 An *asynchronous iterable* provides an "__aiter__" method that
3000 directly returns an *asynchronous iterator*, which can call
3001 asynchronous code in its "__anext__" method.
3002
3003 The "async for" statement allows convenient iteration over
3004 asynchronous iterables.
3005
3006 The following code:
3007
3008 async for TARGET in ITER:
3009 SUITE
3010 else:
3011 SUITE2
3012
3013 Is semantically equivalent to:
3014
3015 iter = (ITER)
3016 iter = type(iter).__aiter__(iter)
3017 running = True
3018
3019 while running:
3020 try:
3021 TARGET = await type(iter).__anext__(iter)
3022 except StopAsyncIteration:
3023 running = False
3024 else:
3025 SUITE
3026 else:
3027 SUITE2
3028
3029 See also "__aiter__()" and "__anext__()" for details.
3030
3031 It is a "SyntaxError" to use an "async for" statement outside the body
3032 of a coroutine function.
3033
3034
3035 The "async with" statement
3036 --------------------------
3037
3038 async_with_stmt ::= "async" with_stmt
3039
3040 An *asynchronous context manager* is a *context manager* that is able
3041 to suspend execution in its *enter* and *exit* methods.
3042
3043 The following code:
3044
3045 async with EXPRESSION as TARGET:
3046 SUITE
3047
3048 is semantically equivalent to:
3049
3050 manager = (EXPRESSION)
3051 aenter = type(manager).__aenter__
3052 aexit = type(manager).__aexit__
3053 value = await aenter(manager)
3054 hit_except = False
3055
3056 try:
3057 TARGET = value
3058 SUITE
3059 except:
3060 hit_except = True
3061 if not await aexit(manager, *sys.exc_info()):
3062 raise
3063 finally:
3064 if not hit_except:
3065 await aexit(manager, None, None, None)
3066
3067 See also "__aenter__()" and "__aexit__()" for details.
3068
3069 It is a "SyntaxError" to use an "async with" statement outside the
3070 body of a coroutine function.
3071
3072 See also:
3073
3074 **PEP 492** - Coroutines with async and await syntax
3075 The proposal that made coroutines a proper standalone concept in
3076 Python, and added supporting syntax.
3077
3078
3079 Type parameter lists
3080 ====================
3081
3082 Added in version 3.12.
3083
3084 Changed in version 3.13: Support for default values was added (see
3085 **PEP 696**).
3086
3087 type_params ::= "[" type_param ("," type_param)* "]"
3088 type_param ::= typevar | typevartuple | paramspec
3089 typevar ::= identifier (":" expression)? ("=" expression)?
3090 typevartuple ::= "*" identifier ("=" expression)?
3091 paramspec ::= "**" identifier ("=" expression)?
3092
3093 Functions (including coroutines), classes and type aliases may contain
3094 a type parameter list:
3095
3096 def max[T](args: list[T]) -> T:
3097 ...
3098
3099 async def amax[T](args: list[T]) -> T:
3100 ...
3101
3102 class Bag[T]:
3103 def __iter__(self) -> Iterator[T]:
3104 ...
3105
3106 def add(self, arg: T) -> None:
3107 ...
3108
3109 type ListOrSet[T] = list[T] | set[T]
3110
3111 Semantically, this indicates that the function, class, or type alias
3112 is generic over a type variable. This information is primarily used by
3113 static type checkers, and at runtime, generic objects behave much like
3114 their non-generic counterparts.
3115
3116 Type parameters are declared in square brackets ("[]") immediately
3117 after the name of the function, class, or type alias. The type
3118 parameters are accessible within the scope of the generic object, but
3119 not elsewhere. Thus, after a declaration "def func[T](): pass", the
3120 name "T" is not available in the module scope. Below, the semantics of
3121 generic objects are described with more precision. The scope of type
3122 parameters is modeled with a special function (technically, an
3123 annotation scope) that wraps the creation of the generic object.
3124
3125 Generic functions, classes, and type aliases have a "__type_params__"
3126 attribute listing their type parameters.
3127
3128 Type parameters come in three kinds:
3129
3130 * "typing.TypeVar", introduced by a plain name (e.g., "T").
3131 Semantically, this represents a single type to a type checker.
3132
3133 * "typing.TypeVarTuple", introduced by a name prefixed with a single
3134 asterisk (e.g., "*Ts"). Semantically, this stands for a tuple of any
3135 number of types.
3136
3137 * "typing.ParamSpec", introduced by a name prefixed with two asterisks
3138 (e.g., "**P"). Semantically, this stands for the parameters of a
3139 callable.
3140
3141 "typing.TypeVar" declarations can define *bounds* and *constraints*
3142 with a colon (":") followed by an expression. A single expression
3143 after the colon indicates a bound (e.g. "T: int"). Semantically, this
3144 means that the "typing.TypeVar" can only represent types that are a
3145 subtype of this bound. A parenthesized tuple of expressions after the
3146 colon indicates a set of constraints (e.g. "T: (str, bytes)"). Each
3147 member of the tuple should be a type (again, this is not enforced at
3148 runtime). Constrained type variables can only take on one of the types
3149 in the list of constraints.
3150
3151 For "typing.TypeVar"s declared using the type parameter list syntax,
3152 the bound and constraints are not evaluated when the generic object is
3153 created, but only when the value is explicitly accessed through the
3154 attributes "__bound__" and "__constraints__". To accomplish this, the
3155 bounds or constraints are evaluated in a separate annotation scope.
3156
3157 "typing.TypeVarTuple"s and "typing.ParamSpec"s cannot have bounds or
3158 constraints.
3159
3160 All three flavors of type parameters can also have a *default value*,
3161 which is used when the type parameter is not explicitly provided. This
3162 is added by appending a single equals sign ("=") followed by an
3163 expression. Like the bounds and constraints of type variables, the
3164 default value is not evaluated when the object is created, but only
3165 when the type parameter’s "__default__" attribute is accessed. To this
3166 end, the default value is evaluated in a separate annotation scope. If
3167 no default value is specified for a type parameter, the "__default__"
3168 attribute is set to the special sentinel object "typing.NoDefault".
3169
3170 The following example indicates the full set of allowed type parameter
3171 declarations:
3172
3173 def overly_generic[
3174 SimpleTypeVar,
3175 TypeVarWithDefault = int,
3176 TypeVarWithBound: int,
3177 TypeVarWithConstraints: (str, bytes),
3178 *SimpleTypeVarTuple = (int, float),
3179 **SimpleParamSpec = (str, bytearray),
3180 ](
3181 a: SimpleTypeVar,
3182 b: TypeVarWithDefault,
3183 c: TypeVarWithBound,
3184 d: Callable[SimpleParamSpec, TypeVarWithConstraints],
3185 *e: SimpleTypeVarTuple,
3186 ): ...
3187
3188
3189 Generic functions
3190 -----------------
3191
3192 Generic functions are declared as follows:
3193
3194 def func[T](arg: T): ...
3195
3196 This syntax is equivalent to:
3197
3198 annotation-def TYPE_PARAMS_OF_func():
3199 T = typing.TypeVar("T")
3200 def func(arg: T): ...
3201 func.__type_params__ = (T,)
3202 return func
3203 func = TYPE_PARAMS_OF_func()
3204
3205 Here "annotation-def" indicates an annotation scope, which is not
3206 actually bound to any name at runtime. (One other liberty is taken in
3207 the translation: the syntax does not go through attribute access on
3208 the "typing" module, but creates an instance of "typing.TypeVar"
3209 directly.)
3210
3211 The annotations of generic functions are evaluated within the
3212 annotation scope used for declaring the type parameters, but the
3213 function’s defaults and decorators are not.
3214
3215 The following example illustrates the scoping rules for these cases,
3216 as well as for additional flavors of type parameters:
3217
3218 @decorator
3219 def func[T: int, *Ts, **P](*args: *Ts, arg: Callable[P, T] = some_default):
3220 ...
3221
3222 Except for the lazy evaluation of the "TypeVar" bound, this is
3223 equivalent to:
3224
3225 DEFAULT_OF_arg = some_default
3226
3227 annotation-def TYPE_PARAMS_OF_func():
3228
3229 annotation-def BOUND_OF_T():
3230 return int
3231 # In reality, BOUND_OF_T() is evaluated only on demand.
3232 T = typing.TypeVar("T", bound=BOUND_OF_T())
3233
3234 Ts = typing.TypeVarTuple("Ts")
3235 P = typing.ParamSpec("P")
3236
3237 def func(*args: *Ts, arg: Callable[P, T] = DEFAULT_OF_arg):
3238 ...
3239
3240 func.__type_params__ = (T, Ts, P)
3241 return func
3242 func = decorator(TYPE_PARAMS_OF_func())
3243
3244 The capitalized names like "DEFAULT_OF_arg" are not actually bound at
3245 runtime.
3246
3247
3248 Generic classes
3249 ---------------
3250
3251 Generic classes are declared as follows:
3252
3253 class Bag[T]: ...
3254
3255 This syntax is equivalent to:
3256
3257 annotation-def TYPE_PARAMS_OF_Bag():
3258 T = typing.TypeVar("T")
3259 class Bag(typing.Generic[T]):
3260 __type_params__ = (T,)
3261 ...
3262 return Bag
3263 Bag = TYPE_PARAMS_OF_Bag()
3264
3265 Here again "annotation-def" (not a real keyword) indicates an
3266 annotation scope, and the name "TYPE_PARAMS_OF_Bag" is not actually
3267 bound at runtime.
3268
3269 Generic classes implicitly inherit from "typing.Generic". The base
3270 classes and keyword arguments of generic classes are evaluated within
3271 the type scope for the type parameters, and decorators are evaluated
3272 outside that scope. This is illustrated by this example:
3273
3274 @decorator
3275 class Bag(Base[T], arg=T): ...
3276
3277 This is equivalent to:
3278
3279 annotation-def TYPE_PARAMS_OF_Bag():
3280 T = typing.TypeVar("T")
3281 class Bag(Base[T], typing.Generic[T], arg=T):
3282 __type_params__ = (T,)
3283 ...
3284 return Bag
3285 Bag = decorator(TYPE_PARAMS_OF_Bag())
3286
3287
3288 Generic type aliases
3289 --------------------
3290
3291 The "type" statement can also be used to create a generic type alias:
3292
3293 type ListOrSet[T] = list[T] | set[T]
3294
3295 Except for the lazy evaluation of the value, this is equivalent to:
3296
3297 annotation-def TYPE_PARAMS_OF_ListOrSet():
3298 T = typing.TypeVar("T")
3299
3300 annotation-def VALUE_OF_ListOrSet():
3301 return list[T] | set[T]
3302 # In reality, the value is lazily evaluated
3303 return typing.TypeAliasType("ListOrSet", VALUE_OF_ListOrSet(), type_params=(T,))
3304 ListOrSet = TYPE_PARAMS_OF_ListOrSet()
3305
3306 Here, "annotation-def" (not a real keyword) indicates an annotation
3307 scope. The capitalized names like "TYPE_PARAMS_OF_ListOrSet" are not
3308 actually bound at runtime.
3309
3310 -[ Footnotes ]-
3311
3312 [1] The exception is propagated to the invocation stack unless there
3313 is a "finally" clause which happens to raise another exception.
3314 That new exception causes the old one to be lost.
3315
3316 [2] In pattern matching, a sequence is defined as one of the
3317 following:
3318
3319 * a class that inherits from "collections.abc.Sequence"
3320
3321 * a Python class that has been registered as
3322 "collections.abc.Sequence"
3323
3324 * a builtin class that has its (CPython) "Py_TPFLAGS_SEQUENCE" bit
3325 set
3326
3327 * a class that inherits from any of the above
3328
3329 The following standard library classes are sequences:
3330
3331 * "array.array"
3332
3333 * "collections.deque"
3334
3335 * "list"
3336
3337 * "memoryview"
3338
3339 * "range"
3340
3341 * "tuple"
3342
3343 Note:
3344
3345 Subject values of type "str", "bytes", and "bytearray" do not
3346 match sequence patterns.
3347
3348 [3] In pattern matching, a mapping is defined as one of the following:
3349
3350 * a class that inherits from "collections.abc.Mapping"
3351
3352 * a Python class that has been registered as
3353 "collections.abc.Mapping"
3354
3355 * a builtin class that has its (CPython) "Py_TPFLAGS_MAPPING" bit
3356 set
3357
3358 * a class that inherits from any of the above
3359
3360 The standard library classes "dict" and "types.MappingProxyType"
3361 are mappings.
3362
3363 [4] A string literal appearing as the first statement in the function
3364 body is transformed into the function’s "__doc__" attribute and
3365 therefore the function’s *docstring*.
3366
3367 [5] A string literal appearing as the first statement in the class
3368 body is transformed into the namespace’s "__doc__" item and
3369 therefore the class’s *docstring*.
3370 ''',
3371 'context-managers': r'''With Statement Context Managers
3372 *******************************
3373
3374 A *context manager* is an object that defines the runtime context to
3375 be established when executing a "with" statement. The context manager
3376 handles the entry into, and the exit from, the desired runtime context
3377 for the execution of the block of code. Context managers are normally
3378 invoked using the "with" statement (described in section The with
3379 statement), but can also be used by directly invoking their methods.
3380
3381 Typical uses of context managers include saving and restoring various
3382 kinds of global state, locking and unlocking resources, closing opened
3383 files, etc.
3384
3385 For more information on context managers, see Context Manager Types.
3386 The "object" class itself does not provide the context manager
3387 methods.
3388
3389 object.__enter__(self)
3390
3391 Enter the runtime context related to this object. The "with"
3392 statement will bind this method’s return value to the target(s)
3393 specified in the "as" clause of the statement, if any.
3394
3395 object.__exit__(self, exc_type, exc_value, traceback)
3396
3397 Exit the runtime context related to this object. The parameters
3398 describe the exception that caused the context to be exited. If the
3399 context was exited without an exception, all three arguments will
3400 be "None".
3401
3402 If an exception is supplied, and the method wishes to suppress the
3403 exception (i.e., prevent it from being propagated), it should
3404 return a true value. Otherwise, the exception will be processed
3405 normally upon exit from this method.
3406
3407 Note that "__exit__()" methods should not reraise the passed-in
3408 exception; this is the caller’s responsibility.
3409
3410 See also:
3411
3412 **PEP 343** - The “with” statement
3413 The specification, background, and examples for the Python "with"
3414 statement.
3415 ''',
3416 'continue': r'''The "continue" statement
3417 ************************
3418
3419 continue_stmt ::= "continue"
3420
3421 "continue" may only occur syntactically nested in a "for" or "while"
3422 loop, but not nested in a function or class definition within that
3423 loop. It continues with the next cycle of the nearest enclosing loop.
3424
3425 When "continue" passes control out of a "try" statement with a
3426 "finally" clause, that "finally" clause is executed before really
3427 starting the next loop cycle.
3428 ''',
3429 'conversions': r'''Arithmetic conversions
3430 **********************
3431
3432 When a description of an arithmetic operator below uses the phrase
3433 “the numeric arguments are converted to a common type”, this means
3434 that the operator implementation for built-in types works as follows:
3435
3436 * If either argument is a complex number, the other is converted to
3437 complex;
3438
3439 * otherwise, if either argument is a floating-point number, the other
3440 is converted to floating point;
3441
3442 * otherwise, both must be integers and no conversion is necessary.
3443
3444 Some additional rules apply for certain operators (e.g., a string as a
3445 left argument to the ‘%’ operator). Extensions must define their own
3446 conversion behavior.
3447 ''',
3448 'customization': r'''Basic customization
3449 *******************
3450
3451 object.__new__(cls[, ...])
3452
3453 Called to create a new instance of class *cls*. "__new__()" is a
3454 static method (special-cased so you need not declare it as such)
3455 that takes the class of which an instance was requested as its
3456 first argument. The remaining arguments are those passed to the
3457 object constructor expression (the call to the class). The return
3458 value of "__new__()" should be the new object instance (usually an
3459 instance of *cls*).
3460
3461 Typical implementations create a new instance of the class by
3462 invoking the superclass’s "__new__()" method using
3463 "super().__new__(cls[, ...])" with appropriate arguments and then
3464 modifying the newly created instance as necessary before returning
3465 it.
3466
3467 If "__new__()" is invoked during object construction and it returns
3468 an instance of *cls*, then the new instance’s "__init__()" method
3469 will be invoked like "__init__(self[, ...])", where *self* is the
3470 new instance and the remaining arguments are the same as were
3471 passed to the object constructor.
3472
3473 If "__new__()" does not return an instance of *cls*, then the new
3474 instance’s "__init__()" method will not be invoked.
3475
3476 "__new__()" is intended mainly to allow subclasses of immutable
3477 types (like int, str, or tuple) to customize instance creation. It
3478 is also commonly overridden in custom metaclasses in order to
3479 customize class creation.
3480
3481 object.__init__(self[, ...])
3482
3483 Called after the instance has been created (by "__new__()"), but
3484 before it is returned to the caller. The arguments are those
3485 passed to the class constructor expression. If a base class has an
3486 "__init__()" method, the derived class’s "__init__()" method, if
3487 any, must explicitly call it to ensure proper initialization of the
3488 base class part of the instance; for example:
3489 "super().__init__([args...])".
3490
3491 Because "__new__()" and "__init__()" work together in constructing
3492 objects ("__new__()" to create it, and "__init__()" to customize
3493 it), no non-"None" value may be returned by "__init__()"; doing so
3494 will cause a "TypeError" to be raised at runtime.
3495
3496 object.__del__(self)
3497
3498 Called when the instance is about to be destroyed. This is also
3499 called a finalizer or (improperly) a destructor. If a base class
3500 has a "__del__()" method, the derived class’s "__del__()" method,
3501 if any, must explicitly call it to ensure proper deletion of the
3502 base class part of the instance.
3503
3504 It is possible (though not recommended!) for the "__del__()" method
3505 to postpone destruction of the instance by creating a new reference
3506 to it. This is called object *resurrection*. It is
3507 implementation-dependent whether "__del__()" is called a second
3508 time when a resurrected object is about to be destroyed; the
3509 current *CPython* implementation only calls it once.
3510
3511 It is not guaranteed that "__del__()" methods are called for
3512 objects that still exist when the interpreter exits.
3513 "weakref.finalize" provides a straightforward way to register a
3514 cleanup function to be called when an object is garbage collected.
3515
3516 Note:
3517
3518 "del x" doesn’t directly call "x.__del__()" — the former
3519 decrements the reference count for "x" by one, and the latter is
3520 only called when "x"’s reference count reaches zero.
3521
3522 **CPython implementation detail:** It is possible for a reference
3523 cycle to prevent the reference count of an object from going to
3524 zero. In this case, the cycle will be later detected and deleted
3525 by the *cyclic garbage collector*. A common cause of reference
3526 cycles is when an exception has been caught in a local variable.
3527 The frame’s locals then reference the exception, which references
3528 its own traceback, which references the locals of all frames caught
3529 in the traceback.
3530
3531 See also: Documentation for the "gc" module.
3532
3533 Warning:
3534
3535 Due to the precarious circumstances under which "__del__()"
3536 methods are invoked, exceptions that occur during their execution
3537 are ignored, and a warning is printed to "sys.stderr" instead.
3538 In particular:
3539
3540 * "__del__()" can be invoked when arbitrary code is being
3541 executed, including from any arbitrary thread. If "__del__()"
3542 needs to take a lock or invoke any other blocking resource, it
3543 may deadlock as the resource may already be taken by the code
3544 that gets interrupted to execute "__del__()".
3545
3546 * "__del__()" can be executed during interpreter shutdown. As a
3547 consequence, the global variables it needs to access (including
3548 other modules) may already have been deleted or set to "None".
3549 Python guarantees that globals whose name begins with a single
3550 underscore are deleted from their module before other globals
3551 are deleted; if no other references to such globals exist, this
3552 may help in assuring that imported modules are still available
3553 at the time when the "__del__()" method is called.
3554
3555 object.__repr__(self)
3556
3557 Called by the "repr()" built-in function to compute the “official”
3558 string representation of an object. If at all possible, this
3559 should look like a valid Python expression that could be used to
3560 recreate an object with the same value (given an appropriate
3561 environment). If this is not possible, a string of the form
3562 "<...some useful description...>" should be returned. The return
3563 value must be a string object. If a class defines "__repr__()" but
3564 not "__str__()", then "__repr__()" is also used when an “informal”
3565 string representation of instances of that class is required.
3566
3567 This is typically used for debugging, so it is important that the
3568 representation is information-rich and unambiguous. A default
3569 implementation is provided by the "object" class itself.
3570
3571 object.__str__(self)
3572
3573 Called by "str(object)", the default "__format__()" implementation,
3574 and the built-in function "print()", to compute the “informal” or
3575 nicely printable string representation of an object. The return
3576 value must be a str object.
3577
3578 This method differs from "object.__repr__()" in that there is no
3579 expectation that "__str__()" return a valid Python expression: a
3580 more convenient or concise representation can be used.
3581
3582 The default implementation defined by the built-in type "object"
3583 calls "object.__repr__()".
3584
3585 object.__bytes__(self)
3586
3587 Called by bytes to compute a byte-string representation of an
3588 object. This should return a "bytes" object. The "object" class
3589 itself does not provide this method.
3590
3591 object.__format__(self, format_spec)
3592
3593 Called by the "format()" built-in function, and by extension,
3594 evaluation of formatted string literals and the "str.format()"
3595 method, to produce a “formatted” string representation of an
3596 object. The *format_spec* argument is a string that contains a
3597 description of the formatting options desired. The interpretation
3598 of the *format_spec* argument is up to the type implementing
3599 "__format__()", however most classes will either delegate
3600 formatting to one of the built-in types, or use a similar
3601 formatting option syntax.
3602
3603 See Format Specification Mini-Language for a description of the
3604 standard formatting syntax.
3605
3606 The return value must be a string object.
3607
3608 The default implementation by the "object" class should be given an
3609 empty *format_spec* string. It delegates to "__str__()".
3610
3611 Changed in version 3.4: The __format__ method of "object" itself
3612 raises a "TypeError" if passed any non-empty string.
3613
3614 Changed in version 3.7: "object.__format__(x, '')" is now
3615 equivalent to "str(x)" rather than "format(str(x), '')".
3616
3617 object.__lt__(self, other)
3618 object.__le__(self, other)
3619 object.__eq__(self, other)
3620 object.__ne__(self, other)
3621 object.__gt__(self, other)
3622 object.__ge__(self, other)
3623
3624 These are the so-called “rich comparison” methods. The
3625 correspondence between operator symbols and method names is as
3626 follows: "x<y" calls "x.__lt__(y)", "x<=y" calls "x.__le__(y)",
3627 "x==y" calls "x.__eq__(y)", "x!=y" calls "x.__ne__(y)", "x>y" calls
3628 "x.__gt__(y)", and "x>=y" calls "x.__ge__(y)".
3629
3630 A rich comparison method may return the singleton "NotImplemented"
3631 if it does not implement the operation for a given pair of
3632 arguments. By convention, "False" and "True" are returned for a
3633 successful comparison. However, these methods can return any value,
3634 so if the comparison operator is used in a Boolean context (e.g.,
3635 in the condition of an "if" statement), Python will call "bool()"
3636 on the value to determine if the result is true or false.
3637
3638 By default, "object" implements "__eq__()" by using "is", returning
3639 "NotImplemented" in the case of a false comparison: "True if x is y
3640 else NotImplemented". For "__ne__()", by default it delegates to
3641 "__eq__()" and inverts the result unless it is "NotImplemented".
3642 There are no other implied relationships among the comparison
3643 operators or default implementations; for example, the truth of
3644 "(x<y or x==y)" does not imply "x<=y". To automatically generate
3645 ordering operations from a single root operation, see
3646 "functools.total_ordering()".
3647
3648 By default, the "object" class provides implementations consistent
3649 with Value comparisons: equality compares according to object
3650 identity, and order comparisons raise "TypeError". Each default
3651 method may generate these results directly, but may also return
3652 "NotImplemented".
3653
3654 See the paragraph on "__hash__()" for some important notes on
3655 creating *hashable* objects which support custom comparison
3656 operations and are usable as dictionary keys.
3657
3658 There are no swapped-argument versions of these methods (to be used
3659 when the left argument does not support the operation but the right
3660 argument does); rather, "__lt__()" and "__gt__()" are each other’s
3661 reflection, "__le__()" and "__ge__()" are each other’s reflection,
3662 and "__eq__()" and "__ne__()" are their own reflection. If the
3663 operands are of different types, and the right operand’s type is a
3664 direct or indirect subclass of the left operand’s type, the
3665 reflected method of the right operand has priority, otherwise the
3666 left operand’s method has priority. Virtual subclassing is not
3667 considered.
3668
3669 When no appropriate method returns any value other than
3670 "NotImplemented", the "==" and "!=" operators will fall back to
3671 "is" and "is not", respectively.
3672
3673 object.__hash__(self)
3674
3675 Called by built-in function "hash()" and for operations on members
3676 of hashed collections including "set", "frozenset", and "dict".
3677 The "__hash__()" method should return an integer. The only required
3678 property is that objects which compare equal have the same hash
3679 value; it is advised to mix together the hash values of the
3680 components of the object that also play a part in comparison of
3681 objects by packing them into a tuple and hashing the tuple.
3682 Example:
3683
3684 def __hash__(self):
3685 return hash((self.name, self.nick, self.color))
3686
3687 Note:
3688
3689 "hash()" truncates the value returned from an object’s custom
3690 "__hash__()" method to the size of a "Py_ssize_t". This is
3691 typically 8 bytes on 64-bit builds and 4 bytes on 32-bit builds.
3692 If an object’s "__hash__()" must interoperate on builds of
3693 different bit sizes, be sure to check the width on all supported
3694 builds. An easy way to do this is with "python -c "import sys;
3695 print(sys.hash_info.width)"".
3696
3697 If a class does not define an "__eq__()" method it should not
3698 define a "__hash__()" operation either; if it defines "__eq__()"
3699 but not "__hash__()", its instances will not be usable as items in
3700 hashable collections. If a class defines mutable objects and
3701 implements an "__eq__()" method, it should not implement
3702 "__hash__()", since the implementation of *hashable* collections
3703 requires that a key’s hash value is immutable (if the object’s hash
3704 value changes, it will be in the wrong hash bucket).
3705
3706 User-defined classes have "__eq__()" and "__hash__()" methods by
3707 default (inherited from the "object" class); with them, all objects
3708 compare unequal (except with themselves) and "x.__hash__()" returns
3709 an appropriate value such that "x == y" implies both that "x is y"
3710 and "hash(x) == hash(y)".
3711
3712 A class that overrides "__eq__()" and does not define "__hash__()"
3713 will have its "__hash__()" implicitly set to "None". When the
3714 "__hash__()" method of a class is "None", instances of the class
3715 will raise an appropriate "TypeError" when a program attempts to
3716 retrieve their hash value, and will also be correctly identified as
3717 unhashable when checking "isinstance(obj,
3718 collections.abc.Hashable)".
3719
3720 If a class that overrides "__eq__()" needs to retain the
3721 implementation of "__hash__()" from a parent class, the interpreter
3722 must be told this explicitly by setting "__hash__ =
3723 <ParentClass>.__hash__".
3724
3725 If a class that does not override "__eq__()" wishes to suppress
3726 hash support, it should include "__hash__ = None" in the class
3727 definition. A class which defines its own "__hash__()" that
3728 explicitly raises a "TypeError" would be incorrectly identified as
3729 hashable by an "isinstance(obj, collections.abc.Hashable)" call.
3730
3731 Note:
3732
3733 By default, the "__hash__()" values of str and bytes objects are
3734 “salted” with an unpredictable random value. Although they
3735 remain constant within an individual Python process, they are not
3736 predictable between repeated invocations of Python.This is
3737 intended to provide protection against a denial-of-service caused
3738 by carefully chosen inputs that exploit the worst case
3739 performance of a dict insertion, *O*(*n*^2) complexity. See
3740 http://ocert.org/advisories/ocert-2011-003.html for
3741 details.Changing hash values affects the iteration order of sets.
3742 Python has never made guarantees about this ordering (and it
3743 typically varies between 32-bit and 64-bit builds).See also
3744 "PYTHONHASHSEED".
3745
3746 Changed in version 3.3: Hash randomization is enabled by default.
3747
3748 object.__bool__(self)
3749
3750 Called to implement truth value testing and the built-in operation
3751 "bool()"; should return "False" or "True". When this method is not
3752 defined, "__len__()" is called, if it is defined, and the object is
3753 considered true if its result is nonzero. If a class defines
3754 neither "__len__()" nor "__bool__()" (which is true of the "object"
3755 class itself), all its instances are considered true.
3756 ''',
3757 'debugger': r'''"pdb" — The Python Debugger
3758 ***************************
3759
3760 **Source code:** Lib/pdb.py
3761
3762 ======================================================================
3763
3764 The module "pdb" defines an interactive source code debugger for
3765 Python programs. It supports setting (conditional) breakpoints and
3766 single stepping at the source line level, inspection of stack frames,
3767 source code listing, and evaluation of arbitrary Python code in the
3768 context of any stack frame. It also supports post-mortem debugging
3769 and can be called under program control.
3770
3771 The debugger is extensible – it is actually defined as the class
3772 "Pdb". This is currently undocumented but easily understood by reading
3773 the source. The extension interface uses the modules "bdb" and "cmd".
3774
3775 See also:
3776
3777 Module "faulthandler"
3778 Used to dump Python tracebacks explicitly, on a fault, after a
3779 timeout, or on a user signal.
3780
3781 Module "traceback"
3782 Standard interface to extract, format and print stack traces of
3783 Python programs.
3784
3785 The typical usage to break into the debugger is to insert:
3786
3787 import pdb; pdb.set_trace()
3788
3789 Or:
3790
3791 breakpoint()
3792
3793 at the location you want to break into the debugger, and then run the
3794 program. You can then step through the code following this statement,
3795 and continue running without the debugger using the "continue"
3796 command.
3797
3798 Changed in version 3.7: The built-in "breakpoint()", when called with
3799 defaults, can be used instead of "import pdb; pdb.set_trace()".
3800
3801 def double(x):
3802 breakpoint()
3803 return x * 2
3804 val = 3
3805 print(f"{val} * 2 is {double(val)}")
3806
3807 The debugger’s prompt is "(Pdb)", which is the indicator that you are
3808 in debug mode:
3809
3810 > ...(2)double()
3811 -> breakpoint()
3812 (Pdb) p x
3813 3
3814 (Pdb) continue
3815 3 * 2 is 6
3816
3817 Changed in version 3.3: Tab-completion via the "readline" module is
3818 available for commands and command arguments, e.g. the current global
3819 and local names are offered as arguments of the "p" command.
3820
3821
3822 Command-line interface
3823 ======================
3824
3825 You can also invoke "pdb" from the command line to debug other
3826 scripts. For example:
3827
3828 python -m pdb [-c command] (-m module | pyfile) [args ...]
3829
3830 When invoked as a module, pdb will automatically enter post-mortem
3831 debugging if the program being debugged exits abnormally. After post-
3832 mortem debugging (or after normal exit of the program), pdb will
3833 restart the program. Automatic restarting preserves pdb’s state (such
3834 as breakpoints) and in most cases is more useful than quitting the
3835 debugger upon program’s exit.
3836
3837 -c, --command <command>
3838
3839 To execute commands as if given in a ".pdbrc" file; see Debugger
3840 commands.
3841
3842 Changed in version 3.2: Added the "-c" option.
3843
3844 -m <module>
3845
3846 To execute modules similar to the way "python -m" does. As with a
3847 script, the debugger will pause execution just before the first
3848 line of the module.
3849
3850 Changed in version 3.7: Added the "-m" option.
3851
3852 Typical usage to execute a statement under control of the debugger is:
3853
3854 >>> import pdb
3855 >>> def f(x):
3856 ... print(1 / x)
3857 >>> pdb.run("f(2)")
3858 > <string>(1)<module>()
3859 (Pdb) continue
3860 0.5
3861 >>>
3862
3863 The typical usage to inspect a crashed program is:
3864
3865 >>> import pdb
3866 >>> def f(x):
3867 ... print(1 / x)
3868 ...
3869 >>> f(0)
3870 Traceback (most recent call last):
3871 File "<stdin>", line 1, in <module>
3872 File "<stdin>", line 2, in f
3873 ZeroDivisionError: division by zero
3874 >>> pdb.pm()
3875 > <stdin>(2)f()
3876 (Pdb) p x
3877 0
3878 (Pdb)
3879
3880 Changed in version 3.13: The implementation of **PEP 667** means that
3881 name assignments made via "pdb" will immediately affect the active
3882 scope, even when running inside an *optimized scope*.
3883
3884 The module defines the following functions; each enters the debugger
3885 in a slightly different way:
3886
3887 pdb.run(statement, globals=None, locals=None)
3888
3889 Execute the *statement* (given as a string or a code object) under
3890 debugger control. The debugger prompt appears before any code is
3891 executed; you can set breakpoints and type "continue", or you can
3892 step through the statement using "step" or "next" (all these
3893 commands are explained below). The optional *globals* and *locals*
3894 arguments specify the environment in which the code is executed; by
3895 default the dictionary of the module "__main__" is used. (See the
3896 explanation of the built-in "exec()" or "eval()" functions.)
3897
3898 pdb.runeval(expression, globals=None, locals=None)
3899
3900 Evaluate the *expression* (given as a string or a code object)
3901 under debugger control. When "runeval()" returns, it returns the
3902 value of the *expression*. Otherwise this function is similar to
3903 "run()".
3904
3905 pdb.runcall(function, *args, **kwds)
3906
3907 Call the *function* (a function or method object, not a string)
3908 with the given arguments. When "runcall()" returns, it returns
3909 whatever the function call returned. The debugger prompt appears
3910 as soon as the function is entered.
3911
3912 pdb.set_trace(*, header=None)
3913
3914 Enter the debugger at the calling stack frame. This is useful to
3915 hard-code a breakpoint at a given point in a program, even if the
3916 code is not otherwise being debugged (e.g. when an assertion
3917 fails). If given, *header* is printed to the console just before
3918 debugging begins.
3919
3920 Changed in version 3.7: The keyword-only argument *header*.
3921
3922 Changed in version 3.13: "set_trace()" will enter the debugger
3923 immediately, rather than on the next line of code to be executed.
3924
3925 pdb.post_mortem(t=None)
3926
3927 Enter post-mortem debugging of the given exception or traceback
3928 object. If no value is given, it uses the exception that is
3929 currently being handled, or raises "ValueError" if there isn’t one.
3930
3931 Changed in version 3.13: Support for exception objects was added.
3932
3933 pdb.pm()
3934
3935 Enter post-mortem debugging of the exception found in
3936 "sys.last_exc".
3937
3938 The "run*" functions and "set_trace()" are aliases for instantiating
3939 the "Pdb" class and calling the method of the same name. If you want
3940 to access further features, you have to do this yourself:
3941
3942 class pdb.Pdb(completekey='tab', stdin=None, stdout=None, skip=None, nosigint=False, readrc=True)
3943
3944 "Pdb" is the debugger class.
3945
3946 The *completekey*, *stdin* and *stdout* arguments are passed to the
3947 underlying "cmd.Cmd" class; see the description there.
3948
3949 The *skip* argument, if given, must be an iterable of glob-style
3950 module name patterns. The debugger will not step into frames that
3951 originate in a module that matches one of these patterns. [1]
3952
3953 By default, Pdb sets a handler for the SIGINT signal (which is sent
3954 when the user presses "Ctrl"-"C" on the console) when you give a
3955 "continue" command. This allows you to break into the debugger
3956 again by pressing "Ctrl"-"C". If you want Pdb not to touch the
3957 SIGINT handler, set *nosigint* to true.
3958
3959 The *readrc* argument defaults to true and controls whether Pdb
3960 will load .pdbrc files from the filesystem.
3961
3962 Example call to enable tracing with *skip*:
3963
3964 import pdb; pdb.Pdb(skip=['django.*']).set_trace()
3965
3966 Raises an auditing event "pdb.Pdb" with no arguments.
3967
3968 Changed in version 3.1: Added the *skip* parameter.
3969
3970 Changed in version 3.2: Added the *nosigint* parameter. Previously,
3971 a SIGINT handler was never set by Pdb.
3972
3973 Changed in version 3.6: The *readrc* argument.
3974
3975 run(statement, globals=None, locals=None)
3976 runeval(expression, globals=None, locals=None)
3977 runcall(function, *args, **kwds)
3978 set_trace()
3979
3980 See the documentation for the functions explained above.
3981
3982
3983 Debugger commands
3984 =================
3985
3986 The commands recognized by the debugger are listed below. Most
3987 commands can be abbreviated to one or two letters as indicated; e.g.
3988 "h(elp)" means that either "h" or "help" can be used to enter the help
3989 command (but not "he" or "hel", nor "H" or "Help" or "HELP").
3990 Arguments to commands must be separated by whitespace (spaces or
3991 tabs). Optional arguments are enclosed in square brackets ("[]") in
3992 the command syntax; the square brackets must not be typed.
3993 Alternatives in the command syntax are separated by a vertical bar
3994 ("|").
3995
3996 Entering a blank line repeats the last command entered. Exception: if
3997 the last command was a "list" command, the next 11 lines are listed.
3998
3999 Commands that the debugger doesn’t recognize are assumed to be Python
4000 statements and are executed in the context of the program being
4001 debugged. Python statements can also be prefixed with an exclamation
4002 point ("!"). This is a powerful way to inspect the program being
4003 debugged; it is even possible to change a variable or call a function.
4004 When an exception occurs in such a statement, the exception name is
4005 printed but the debugger’s state is not changed.
4006
4007 Changed in version 3.13: Expressions/Statements whose prefix is a pdb
4008 command are now correctly identified and executed.
4009
4010 The debugger supports aliases. Aliases can have parameters which
4011 allows one a certain level of adaptability to the context under
4012 examination.
4013
4014 Multiple commands may be entered on a single line, separated by ";;".
4015 (A single ";" is not used as it is the separator for multiple commands
4016 in a line that is passed to the Python parser.) No intelligence is
4017 applied to separating the commands; the input is split at the first
4018 ";;" pair, even if it is in the middle of a quoted string. A
4019 workaround for strings with double semicolons is to use implicit
4020 string concatenation "';'';'" or "";"";"".
4021
4022 To set a temporary global variable, use a *convenience variable*. A
4023 *convenience variable* is a variable whose name starts with "$". For
4024 example, "$foo = 1" sets a global variable "$foo" which you can use in
4025 the debugger session. The *convenience variables* are cleared when
4026 the program resumes execution so it’s less likely to interfere with
4027 your program compared to using normal variables like "foo = 1".
4028
4029 There are three preset *convenience variables*:
4030
4031 * "$_frame": the current frame you are debugging
4032
4033 * "$_retval": the return value if the frame is returning
4034
4035 * "$_exception": the exception if the frame is raising an exception
4036
4037 Added in version 3.12: Added the *convenience variable* feature.
4038
4039 If a file ".pdbrc" exists in the user’s home directory or in the
4040 current directory, it is read with "'utf-8'" encoding and executed as
4041 if it had been typed at the debugger prompt, with the exception that
4042 empty lines and lines starting with "#" are ignored. This is
4043 particularly useful for aliases. If both files exist, the one in the
4044 home directory is read first and aliases defined there can be
4045 overridden by the local file.
4046
4047 Changed in version 3.2: ".pdbrc" can now contain commands that
4048 continue debugging, such as "continue" or "next". Previously, these
4049 commands had no effect.
4050
4051 Changed in version 3.11: ".pdbrc" is now read with "'utf-8'" encoding.
4052 Previously, it was read with the system locale encoding.
4053
4054 h(elp) [command]
4055
4056 Without argument, print the list of available commands. With a
4057 *command* as argument, print help about that command. "help pdb"
4058 displays the full documentation (the docstring of the "pdb"
4059 module). Since the *command* argument must be an identifier, "help
4060 exec" must be entered to get help on the "!" command.
4061
4062 w(here)
4063
4064 Print a stack trace, with the most recent frame at the bottom. An
4065 arrow (">") indicates the current frame, which determines the
4066 context of most commands.
4067
4068 d(own) [count]
4069
4070 Move the current frame *count* (default one) levels down in the
4071 stack trace (to a newer frame).
4072
4073 u(p) [count]
4074
4075 Move the current frame *count* (default one) levels up in the stack
4076 trace (to an older frame).
4077
4078 b(reak) [([filename:]lineno | function) [, condition]]
4079
4080 With a *lineno* argument, set a break at line *lineno* in the
4081 current file. The line number may be prefixed with a *filename* and
4082 a colon, to specify a breakpoint in another file (possibly one that
4083 hasn’t been loaded yet). The file is searched on "sys.path".
4084 Accepatable forms of *filename* are "/abspath/to/file.py",
4085 "relpath/file.py", "module" and "package.module".
4086
4087 With a *function* argument, set a break at the first executable
4088 statement within that function. *function* can be any expression
4089 that evaluates to a function in the current namespace.
4090
4091 If a second argument is present, it is an expression which must
4092 evaluate to true before the breakpoint is honored.
4093
4094 Without argument, list all breaks, including for each breakpoint,
4095 the number of times that breakpoint has been hit, the current
4096 ignore count, and the associated condition if any.
4097
4098 Each breakpoint is assigned a number to which all the other
4099 breakpoint commands refer.
4100
4101 tbreak [([filename:]lineno | function) [, condition]]
4102
4103 Temporary breakpoint, which is removed automatically when it is
4104 first hit. The arguments are the same as for "break".
4105
4106 cl(ear) [filename:lineno | bpnumber ...]
4107
4108 With a *filename:lineno* argument, clear all the breakpoints at
4109 this line. With a space separated list of breakpoint numbers, clear
4110 those breakpoints. Without argument, clear all breaks (but first
4111 ask confirmation).
4112
4113 disable bpnumber [bpnumber ...]
4114
4115 Disable the breakpoints given as a space separated list of
4116 breakpoint numbers. Disabling a breakpoint means it cannot cause
4117 the program to stop execution, but unlike clearing a breakpoint, it
4118 remains in the list of breakpoints and can be (re-)enabled.
4119
4120 enable bpnumber [bpnumber ...]
4121
4122 Enable the breakpoints specified.
4123
4124 ignore bpnumber [count]
4125
4126 Set the ignore count for the given breakpoint number. If *count*
4127 is omitted, the ignore count is set to 0. A breakpoint becomes
4128 active when the ignore count is zero. When non-zero, the *count*
4129 is decremented each time the breakpoint is reached and the
4130 breakpoint is not disabled and any associated condition evaluates
4131 to true.
4132
4133 condition bpnumber [condition]
4134
4135 Set a new *condition* for the breakpoint, an expression which must
4136 evaluate to true before the breakpoint is honored. If *condition*
4137 is absent, any existing condition is removed; i.e., the breakpoint
4138 is made unconditional.
4139
4140 commands [bpnumber]
4141
4142 Specify a list of commands for breakpoint number *bpnumber*. The
4143 commands themselves appear on the following lines. Type a line
4144 containing just "end" to terminate the commands. An example:
4145
4146 (Pdb) commands 1
4147 (com) p some_variable
4148 (com) end
4149 (Pdb)
4150
4151 To remove all commands from a breakpoint, type "commands" and
4152 follow it immediately with "end"; that is, give no commands.
4153
4154 With no *bpnumber* argument, "commands" refers to the last
4155 breakpoint set.
4156
4157 You can use breakpoint commands to start your program up again.
4158 Simply use the "continue" command, or "step", or any other command
4159 that resumes execution.
4160
4161 Specifying any command resuming execution (currently "continue",
4162 "step", "next", "return", "jump", "quit" and their abbreviations)
4163 terminates the command list (as if that command was immediately
4164 followed by end). This is because any time you resume execution
4165 (even with a simple next or step), you may encounter another
4166 breakpoint—which could have its own command list, leading to
4167 ambiguities about which list to execute.
4168
4169 If you use the "silent" command in the command list, the usual
4170 message about stopping at a breakpoint is not printed. This may be
4171 desirable for breakpoints that are to print a specific message and
4172 then continue. If none of the other commands print anything, you
4173 see no sign that the breakpoint was reached.
4174
4175 s(tep)
4176
4177 Execute the current line, stop at the first possible occasion
4178 (either in a function that is called or on the next line in the
4179 current function).
4180
4181 n(ext)
4182
4183 Continue execution until the next line in the current function is
4184 reached or it returns. (The difference between "next" and "step"
4185 is that "step" stops inside a called function, while "next"
4186 executes called functions at (nearly) full speed, only stopping at
4187 the next line in the current function.)
4188
4189 unt(il) [lineno]
4190
4191 Without argument, continue execution until the line with a number
4192 greater than the current one is reached.
4193
4194 With *lineno*, continue execution until a line with a number
4195 greater or equal to *lineno* is reached. In both cases, also stop
4196 when the current frame returns.
4197
4198 Changed in version 3.2: Allow giving an explicit line number.
4199
4200 r(eturn)
4201
4202 Continue execution until the current function returns.
4203
4204 c(ont(inue))
4205
4206 Continue execution, only stop when a breakpoint is encountered.
4207
4208 j(ump) lineno
4209
4210 Set the next line that will be executed. Only available in the
4211 bottom-most frame. This lets you jump back and execute code again,
4212 or jump forward to skip code that you don’t want to run.
4213
4214 It should be noted that not all jumps are allowed – for instance it
4215 is not possible to jump into the middle of a "for" loop or out of a
4216 "finally" clause.
4217
4218 l(ist) [first[, last]]
4219
4220 List source code for the current file. Without arguments, list 11
4221 lines around the current line or continue the previous listing.
4222 With "." as argument, list 11 lines around the current line. With
4223 one argument, list 11 lines around at that line. With two
4224 arguments, list the given range; if the second argument is less
4225 than the first, it is interpreted as a count.
4226
4227 The current line in the current frame is indicated by "->". If an
4228 exception is being debugged, the line where the exception was
4229 originally raised or propagated is indicated by ">>", if it differs
4230 from the current line.
4231
4232 Changed in version 3.2: Added the ">>" marker.
4233
4234 ll | longlist
4235
4236 List all source code for the current function or frame.
4237 Interesting lines are marked as for "list".
4238
4239 Added in version 3.2.
4240
4241 a(rgs)
4242
4243 Print the arguments of the current function and their current
4244 values.
4245
4246 p expression
4247
4248 Evaluate *expression* in the current context and print its value.
4249
4250 Note:
4251
4252 "print()" can also be used, but is not a debugger command — this
4253 executes the Python "print()" function.
4254
4255 pp expression
4256
4257 Like the "p" command, except the value of *expression* is pretty-
4258 printed using the "pprint" module.
4259
4260 whatis expression
4261
4262 Print the type of *expression*.
4263
4264 source expression
4265
4266 Try to get source code of *expression* and display it.
4267
4268 Added in version 3.2.
4269
4270 display [expression]
4271
4272 Display the value of *expression* if it changed, each time
4273 execution stops in the current frame.
4274
4275 Without *expression*, list all display expressions for the current
4276 frame.
4277
4278 Note:
4279
4280 Display evaluates *expression* and compares to the result of the
4281 previous evaluation of *expression*, so when the result is
4282 mutable, display may not be able to pick up the changes.
4283
4284 Example:
4285
4286 lst = []
4287 breakpoint()
4288 pass
4289 lst.append(1)
4290 print(lst)
4291
4292 Display won’t realize "lst" has been changed because the result of
4293 evaluation is modified in place by "lst.append(1)" before being
4294 compared:
4295
4296 > example.py(3)<module>()
4297 -> pass
4298 (Pdb) display lst
4299 display lst: []
4300 (Pdb) n
4301 > example.py(4)<module>()
4302 -> lst.append(1)
4303 (Pdb) n
4304 > example.py(5)<module>()
4305 -> print(lst)
4306 (Pdb)
4307
4308 You can do some tricks with copy mechanism to make it work:
4309
4310 > example.py(3)<module>()
4311 -> pass
4312 (Pdb) display lst[:]
4313 display lst[:]: []
4314 (Pdb) n
4315 > example.py(4)<module>()
4316 -> lst.append(1)
4317 (Pdb) n
4318 > example.py(5)<module>()
4319 -> print(lst)
4320 display lst[:]: [1] [old: []]
4321 (Pdb)
4322
4323 Added in version 3.2.
4324
4325 undisplay [expression]
4326
4327 Do not display *expression* anymore in the current frame. Without
4328 *expression*, clear all display expressions for the current frame.
4329
4330 Added in version 3.2.
4331
4332 interact
4333
4334 Start an interactive interpreter (using the "code" module) in a new
4335 global namespace initialised from the local and global namespaces
4336 for the current scope. Use "exit()" or "quit()" to exit the
4337 interpreter and return to the debugger.
4338
4339 Note:
4340
4341 As "interact" creates a new dedicated namespace for code
4342 execution, assignments to variables will not affect the original
4343 namespaces. However, modifications to any referenced mutable
4344 objects will be reflected in the original namespaces as usual.
4345
4346 Added in version 3.2.
4347
4348 Changed in version 3.13: "exit()" and "quit()" can be used to exit
4349 the "interact" command.
4350
4351 Changed in version 3.13: "interact" directs its output to the
4352 debugger’s output channel rather than "sys.stderr".
4353
4354 alias [name [command]]
4355
4356 Create an alias called *name* that executes *command*. The
4357 *command* must *not* be enclosed in quotes. Replaceable parameters
4358 can be indicated by "%1", "%2", … and "%9", while "%*" is replaced
4359 by all the parameters. If *command* is omitted, the current alias
4360 for *name* is shown. If no arguments are given, all aliases are
4361 listed.
4362
4363 Aliases may be nested and can contain anything that can be legally
4364 typed at the pdb prompt. Note that internal pdb commands *can* be
4365 overridden by aliases. Such a command is then hidden until the
4366 alias is removed. Aliasing is recursively applied to the first
4367 word of the command line; all other words in the line are left
4368 alone.
4369
4370 As an example, here are two useful aliases (especially when placed
4371 in the ".pdbrc" file):
4372
4373 # Print instance variables (usage "pi classInst")
4374 alias pi for k in %1.__dict__.keys(): print(f"%1.{k} = {%1.__dict__[k]}")
4375 # Print instance variables in self
4376 alias ps pi self
4377
4378 unalias name
4379
4380 Delete the specified alias *name*.
4381
4382 ! statement
4383
4384 Execute the (one-line) *statement* in the context of the current
4385 stack frame. The exclamation point can be omitted unless the first
4386 word of the statement resembles a debugger command, e.g.:
4387
4388 (Pdb) ! n=42
4389 (Pdb)
4390
4391 To set a global variable, you can prefix the assignment command
4392 with a "global" statement on the same line, e.g.:
4393
4394 (Pdb) global list_options; list_options = ['-l']
4395 (Pdb)
4396
4397 run [args ...]
4398 restart [args ...]
4399
4400 Restart the debugged Python program. If *args* is supplied, it is
4401 split with "shlex" and the result is used as the new "sys.argv".
4402 History, breakpoints, actions and debugger options are preserved.
4403 "restart" is an alias for "run".
4404
4405 q(uit)
4406
4407 Quit from the debugger. The program being executed is aborted.
4408
4409 debug code
4410
4411 Enter a recursive debugger that steps through *code* (which is an
4412 arbitrary expression or statement to be executed in the current
4413 environment).
4414
4415 retval
4416
4417 Print the return value for the last return of the current function.
4418
4419 exceptions [excnumber]
4420
4421 List or jump between chained exceptions.
4422
4423 When using "pdb.pm()" or "Pdb.post_mortem(...)" with a chained
4424 exception instead of a traceback, it allows the user to move
4425 between the chained exceptions using "exceptions" command to list
4426 exceptions, and "exceptions <number>" to switch to that exception.
4427
4428 Example:
4429
4430 def out():
4431 try:
4432 middle()
4433 except Exception as e:
4434 raise ValueError("reraise middle() error") from e
4435
4436 def middle():
4437 try:
4438 return inner(0)
4439 except Exception as e:
4440 raise ValueError("Middle fail")
4441
4442 def inner(x):
4443 1 / x
4444
4445 out()
4446
4447 calling "pdb.pm()" will allow to move between exceptions:
4448
4449 > example.py(5)out()
4450 -> raise ValueError("reraise middle() error") from e
4451
4452 (Pdb) exceptions
4453 0 ZeroDivisionError('division by zero')
4454 1 ValueError('Middle fail')
4455 > 2 ValueError('reraise middle() error')
4456
4457 (Pdb) exceptions 0
4458 > example.py(16)inner()
4459 -> 1 / x
4460
4461 (Pdb) up
4462 > example.py(10)middle()
4463 -> return inner(0)
4464
4465 Added in version 3.13.
4466
4467 -[ Footnotes ]-
4468
4469 [1] Whether a frame is considered to originate in a certain module is
4470 determined by the "__name__" in the frame globals.
4471 ''',
4472 'del': r'''The "del" statement
4473 *******************
4474
4475 del_stmt ::= "del" target_list
4476
4477 Deletion is recursively defined very similar to the way assignment is
4478 defined. Rather than spelling it out in full details, here are some
4479 hints.
4480
4481 Deletion of a target list recursively deletes each target, from left
4482 to right.
4483
4484 Deletion of a name removes the binding of that name from the local or
4485 global namespace, depending on whether the name occurs in a "global"
4486 statement in the same code block. Trying to delete an unbound name
4487 raises a "NameError" exception.
4488
4489 Deletion of attribute references, subscriptions and slicings is passed
4490 to the primary object involved; deletion of a slicing is in general
4491 equivalent to assignment of an empty slice of the right type (but even
4492 this is determined by the sliced object).
4493
4494 Changed in version 3.2: Previously it was illegal to delete a name
4495 from the local namespace if it occurs as a free variable in a nested
4496 block.
4497 ''',
4498 'dict': r'''Dictionary displays
4499 *******************
4500
4501 A dictionary display is a possibly empty series of dict items
4502 (key/value pairs) enclosed in curly braces:
4503
4504 dict_display ::= "{" [dict_item_list | dict_comprehension] "}"
4505 dict_item_list ::= dict_item ("," dict_item)* [","]
4506 dict_item ::= expression ":" expression | "**" or_expr
4507 dict_comprehension ::= expression ":" expression comp_for
4508
4509 A dictionary display yields a new dictionary object.
4510
4511 If a comma-separated sequence of dict items is given, they are
4512 evaluated from left to right to define the entries of the dictionary:
4513 each key object is used as a key into the dictionary to store the
4514 corresponding value. This means that you can specify the same key
4515 multiple times in the dict item list, and the final dictionary’s value
4516 for that key will be the last one given.
4517
4518 A double asterisk "**" denotes *dictionary unpacking*. Its operand
4519 must be a *mapping*. Each mapping item is added to the new
4520 dictionary. Later values replace values already set by earlier dict
4521 items and earlier dictionary unpackings.
4522
4523 Added in version 3.5: Unpacking into dictionary displays, originally
4524 proposed by **PEP 448**.
4525
4526 A dict comprehension, in contrast to list and set comprehensions,
4527 needs two expressions separated with a colon followed by the usual
4528 “for” and “if” clauses. When the comprehension is run, the resulting
4529 key and value elements are inserted in the new dictionary in the order
4530 they are produced.
4531
4532 Restrictions on the types of the key values are listed earlier in
4533 section The standard type hierarchy. (To summarize, the key type
4534 should be *hashable*, which excludes all mutable objects.) Clashes
4535 between duplicate keys are not detected; the last value (textually
4536 rightmost in the display) stored for a given key value prevails.
4537
4538 Changed in version 3.8: Prior to Python 3.8, in dict comprehensions,
4539 the evaluation order of key and value was not well-defined. In
4540 CPython, the value was evaluated before the key. Starting with 3.8,
4541 the key is evaluated before the value, as proposed by **PEP 572**.
4542 ''',
4543 'dynamic-features': r'''Interaction with dynamic features
4544 *********************************
4545
4546 Name resolution of free variables occurs at runtime, not at compile
4547 time. This means that the following code will print 42:
4548
4549 i = 10
4550 def f():
4551 print(i)
4552 i = 42
4553 f()
4554
4555 The "eval()" and "exec()" functions do not have access to the full
4556 environment for resolving names. Names may be resolved in the local
4557 and global namespaces of the caller. Free variables are not resolved
4558 in the nearest enclosing namespace, but in the global namespace. [1]
4559 The "exec()" and "eval()" functions have optional arguments to
4560 override the global and local namespace. If only one namespace is
4561 specified, it is used for both.
4562 ''',
4563 'else': r'''The "if" statement
4564 ******************
4565
4566 The "if" statement is used for conditional execution:
4567
4568 if_stmt ::= "if" assignment_expression ":" suite
4569 ("elif" assignment_expression ":" suite)*
4570 ["else" ":" suite]
4571
4572 It selects exactly one of the suites by evaluating the expressions one
4573 by one until one is found to be true (see section Boolean operations
4574 for the definition of true and false); then that suite is executed
4575 (and no other part of the "if" statement is executed or evaluated).
4576 If all expressions are false, the suite of the "else" clause, if
4577 present, is executed.
4578 ''',
4579 'exceptions': r'''Exceptions
4580 **********
4581
4582 Exceptions are a means of breaking out of the normal flow of control
4583 of a code block in order to handle errors or other exceptional
4584 conditions. An exception is *raised* at the point where the error is
4585 detected; it may be *handled* by the surrounding code block or by any
4586 code block that directly or indirectly invoked the code block where
4587 the error occurred.
4588
4589 The Python interpreter raises an exception when it detects a run-time
4590 error (such as division by zero). A Python program can also
4591 explicitly raise an exception with the "raise" statement. Exception
4592 handlers are specified with the "try" … "except" statement. The
4593 "finally" clause of such a statement can be used to specify cleanup
4594 code which does not handle the exception, but is executed whether an
4595 exception occurred or not in the preceding code.
4596
4597 Python uses the “termination” model of error handling: an exception
4598 handler can find out what happened and continue execution at an outer
4599 level, but it cannot repair the cause of the error and retry the
4600 failing operation (except by re-entering the offending piece of code
4601 from the top).
4602
4603 When an exception is not handled at all, the interpreter terminates
4604 execution of the program, or returns to its interactive main loop. In
4605 either case, it prints a stack traceback, except when the exception is
4606 "SystemExit".
4607
4608 Exceptions are identified by class instances. The "except" clause is
4609 selected depending on the class of the instance: it must reference the
4610 class of the instance or a *non-virtual base class* thereof. The
4611 instance can be received by the handler and can carry additional
4612 information about the exceptional condition.
4613
4614 Note:
4615
4616 Exception messages are not part of the Python API. Their contents
4617 may change from one version of Python to the next without warning
4618 and should not be relied on by code which will run under multiple
4619 versions of the interpreter.
4620
4621 See also the description of the "try" statement in section The try
4622 statement and "raise" statement in section The raise statement.
4623
4624 -[ Footnotes ]-
4625
4626 [1] This limitation occurs because the code that is executed by these
4627 operations is not available at the time the module is compiled.
4628 ''',
4629 'execmodel': r'''Execution model
4630 ***************
4631
4632
4633 Structure of a program
4634 ======================
4635
4636 A Python program is constructed from code blocks. A *block* is a piece
4637 of Python program text that is executed as a unit. The following are
4638 blocks: a module, a function body, and a class definition. Each
4639 command typed interactively is a block. A script file (a file given
4640 as standard input to the interpreter or specified as a command line
4641 argument to the interpreter) is a code block. A script command (a
4642 command specified on the interpreter command line with the "-c"
4643 option) is a code block. A module run as a top level script (as module
4644 "__main__") from the command line using a "-m" argument is also a code
4645 block. The string argument passed to the built-in functions "eval()"
4646 and "exec()" is a code block.
4647
4648 A code block is executed in an *execution frame*. A frame contains
4649 some administrative information (used for debugging) and determines
4650 where and how execution continues after the code block’s execution has
4651 completed.
4652
4653
4654 Naming and binding
4655 ==================
4656
4657
4658 Binding of names
4659 ----------------
4660
4661 *Names* refer to objects. Names are introduced by name binding
4662 operations.
4663
4664 The following constructs bind names:
4665
4666 * formal parameters to functions,
4667
4668 * class definitions,
4669
4670 * function definitions,
4671
4672 * assignment expressions,
4673
4674 * targets that are identifiers if occurring in an assignment:
4675
4676 * "for" loop header,
4677
4678 * after "as" in a "with" statement, "except" clause, "except*"
4679 clause, or in the as-pattern in structural pattern matching,
4680
4681 * in a capture pattern in structural pattern matching
4682
4683 * "import" statements.
4684
4685 * "type" statements.
4686
4687 * type parameter lists.
4688
4689 The "import" statement of the form "from ... import *" binds all names
4690 defined in the imported module, except those beginning with an
4691 underscore. This form may only be used at the module level.
4692
4693 A target occurring in a "del" statement is also considered bound for
4694 this purpose (though the actual semantics are to unbind the name).
4695
4696 Each assignment or import statement occurs within a block defined by a
4697 class or function definition or at the module level (the top-level
4698 code block).
4699
4700 If a name is bound in a block, it is a local variable of that block,
4701 unless declared as "nonlocal" or "global". If a name is bound at the
4702 module level, it is a global variable. (The variables of the module
4703 code block are local and global.) If a variable is used in a code
4704 block but not defined there, it is a *free variable*.
4705
4706 Each occurrence of a name in the program text refers to the *binding*
4707 of that name established by the following name resolution rules.
4708
4709
4710 Resolution of names
4711 -------------------
4712
4713 A *scope* defines the visibility of a name within a block. If a local
4714 variable is defined in a block, its scope includes that block. If the
4715 definition occurs in a function block, the scope extends to any blocks
4716 contained within the defining one, unless a contained block introduces
4717 a different binding for the name.
4718
4719 When a name is used in a code block, it is resolved using the nearest
4720 enclosing scope. The set of all such scopes visible to a code block
4721 is called the block’s *environment*.
4722
4723 When a name is not found at all, a "NameError" exception is raised. If
4724 the current scope is a function scope, and the name refers to a local
4725 variable that has not yet been bound to a value at the point where the
4726 name is used, an "UnboundLocalError" exception is raised.
4727 "UnboundLocalError" is a subclass of "NameError".
4728
4729 If a name binding operation occurs anywhere within a code block, all
4730 uses of the name within the block are treated as references to the
4731 current block. This can lead to errors when a name is used within a
4732 block before it is bound. This rule is subtle. Python lacks
4733 declarations and allows name binding operations to occur anywhere
4734 within a code block. The local variables of a code block can be
4735 determined by scanning the entire text of the block for name binding
4736 operations. See the FAQ entry on UnboundLocalError for examples.
4737
4738 If the "global" statement occurs within a block, all uses of the names
4739 specified in the statement refer to the bindings of those names in the
4740 top-level namespace. Names are resolved in the top-level namespace by
4741 searching the global namespace, i.e. the namespace of the module
4742 containing the code block, and the builtins namespace, the namespace
4743 of the module "builtins". The global namespace is searched first. If
4744 the names are not found there, the builtins namespace is searched
4745 next. If the names are also not found in the builtins namespace, new
4746 variables are created in the global namespace. The global statement
4747 must precede all uses of the listed names.
4748
4749 The "global" statement has the same scope as a name binding operation
4750 in the same block. If the nearest enclosing scope for a free variable
4751 contains a global statement, the free variable is treated as a global.
4752
4753 The "nonlocal" statement causes corresponding names to refer to
4754 previously bound variables in the nearest enclosing function scope.
4755 "SyntaxError" is raised at compile time if the given name does not
4756 exist in any enclosing function scope. Type parameters cannot be
4757 rebound with the "nonlocal" statement.
4758
4759 The namespace for a module is automatically created the first time a
4760 module is imported. The main module for a script is always called
4761 "__main__".
4762
4763 Class definition blocks and arguments to "exec()" and "eval()" are
4764 special in the context of name resolution. A class definition is an
4765 executable statement that may use and define names. These references
4766 follow the normal rules for name resolution with an exception that
4767 unbound local variables are looked up in the global namespace. The
4768 namespace of the class definition becomes the attribute dictionary of
4769 the class. The scope of names defined in a class block is limited to
4770 the class block; it does not extend to the code blocks of methods.
4771 This includes comprehensions and generator expressions, but it does
4772 not include annotation scopes, which have access to their enclosing
4773 class scopes. This means that the following will fail:
4774
4775 class A:
4776 a = 42
4777 b = list(a + i for i in range(10))
4778
4779 However, the following will succeed:
4780
4781 class A:
4782 type Alias = Nested
4783 class Nested: pass
4784
4785 print(A.Alias.__value__) # <type 'A.Nested'>
4786
4787
4788 Annotation scopes
4789 -----------------
4790
4791 Type parameter lists and "type" statements introduce *annotation
4792 scopes*, which behave mostly like function scopes, but with some
4793 exceptions discussed below. *Annotations* currently do not use
4794 annotation scopes, but they are expected to use annotation scopes in
4795 Python 3.13 when **PEP 649** is implemented.
4796
4797 Annotation scopes are used in the following contexts:
4798
4799 * Type parameter lists for generic type aliases.
4800
4801 * Type parameter lists for generic functions. A generic function’s
4802 annotations are executed within the annotation scope, but its
4803 defaults and decorators are not.
4804
4805 * Type parameter lists for generic classes. A generic class’s base
4806 classes and keyword arguments are executed within the annotation
4807 scope, but its decorators are not.
4808
4809 * The bounds, constraints, and default values for type parameters
4810 (lazily evaluated).
4811
4812 * The value of type aliases (lazily evaluated).
4813
4814 Annotation scopes differ from function scopes in the following ways:
4815
4816 * Annotation scopes have access to their enclosing class namespace. If
4817 an annotation scope is immediately within a class scope, or within
4818 another annotation scope that is immediately within a class scope,
4819 the code in the annotation scope can use names defined in the class
4820 scope as if it were executed directly within the class body. This
4821 contrasts with regular functions defined within classes, which
4822 cannot access names defined in the class scope.
4823
4824 * Expressions in annotation scopes cannot contain "yield", "yield
4825 from", "await", or ":=" expressions. (These expressions are allowed
4826 in other scopes contained within the annotation scope.)
4827
4828 * Names defined in annotation scopes cannot be rebound with "nonlocal"
4829 statements in inner scopes. This includes only type parameters, as
4830 no other syntactic elements that can appear within annotation scopes
4831 can introduce new names.
4832
4833 * While annotation scopes have an internal name, that name is not
4834 reflected in the *qualified name* of objects defined within the
4835 scope. Instead, the "__qualname__" of such objects is as if the
4836 object were defined in the enclosing scope.
4837
4838 Added in version 3.12: Annotation scopes were introduced in Python
4839 3.12 as part of **PEP 695**.
4840
4841 Changed in version 3.13: Annotation scopes are also used for type
4842 parameter defaults, as introduced by **PEP 696**.
4843
4844
4845 Lazy evaluation
4846 ---------------
4847
4848 The values of type aliases created through the "type" statement are
4849 *lazily evaluated*. The same applies to the bounds, constraints, and
4850 default values of type variables created through the type parameter
4851 syntax. This means that they are not evaluated when the type alias or
4852 type variable is created. Instead, they are only evaluated when doing
4853 so is necessary to resolve an attribute access.
4854
4855 Example:
4856
4857 >>> type Alias = 1/0
4858 >>> Alias.__value__
4859 Traceback (most recent call last):
4860 ...
4861 ZeroDivisionError: division by zero
4862 >>> def func[T: 1/0](): pass
4863 >>> T = func.__type_params__[0]
4864 >>> T.__bound__
4865 Traceback (most recent call last):
4866 ...
4867 ZeroDivisionError: division by zero
4868
4869 Here the exception is raised only when the "__value__" attribute of
4870 the type alias or the "__bound__" attribute of the type variable is
4871 accessed.
4872
4873 This behavior is primarily useful for references to types that have
4874 not yet been defined when the type alias or type variable is created.
4875 For example, lazy evaluation enables creation of mutually recursive
4876 type aliases:
4877
4878 from typing import Literal
4879
4880 type SimpleExpr = int | Parenthesized
4881 type Parenthesized = tuple[Literal["("], Expr, Literal[")"]]
4882 type Expr = SimpleExpr | tuple[SimpleExpr, Literal["+", "-"], Expr]
4883
4884 Lazily evaluated values are evaluated in annotation scope, which means
4885 that names that appear inside the lazily evaluated value are looked up
4886 as if they were used in the immediately enclosing scope.
4887
4888 Added in version 3.12.
4889
4890
4891 Builtins and restricted execution
4892 ---------------------------------
4893
4894 **CPython implementation detail:** Users should not touch
4895 "__builtins__"; it is strictly an implementation detail. Users
4896 wanting to override values in the builtins namespace should "import"
4897 the "builtins" module and modify its attributes appropriately.
4898
4899 The builtins namespace associated with the execution of a code block
4900 is actually found by looking up the name "__builtins__" in its global
4901 namespace; this should be a dictionary or a module (in the latter case
4902 the module’s dictionary is used). By default, when in the "__main__"
4903 module, "__builtins__" is the built-in module "builtins"; when in any
4904 other module, "__builtins__" is an alias for the dictionary of the
4905 "builtins" module itself.
4906
4907
4908 Interaction with dynamic features
4909 ---------------------------------
4910
4911 Name resolution of free variables occurs at runtime, not at compile
4912 time. This means that the following code will print 42:
4913
4914 i = 10
4915 def f():
4916 print(i)
4917 i = 42
4918 f()
4919
4920 The "eval()" and "exec()" functions do not have access to the full
4921 environment for resolving names. Names may be resolved in the local
4922 and global namespaces of the caller. Free variables are not resolved
4923 in the nearest enclosing namespace, but in the global namespace. [1]
4924 The "exec()" and "eval()" functions have optional arguments to
4925 override the global and local namespace. If only one namespace is
4926 specified, it is used for both.
4927
4928
4929 Exceptions
4930 ==========
4931
4932 Exceptions are a means of breaking out of the normal flow of control
4933 of a code block in order to handle errors or other exceptional
4934 conditions. An exception is *raised* at the point where the error is
4935 detected; it may be *handled* by the surrounding code block or by any
4936 code block that directly or indirectly invoked the code block where
4937 the error occurred.
4938
4939 The Python interpreter raises an exception when it detects a run-time
4940 error (such as division by zero). A Python program can also
4941 explicitly raise an exception with the "raise" statement. Exception
4942 handlers are specified with the "try" … "except" statement. The
4943 "finally" clause of such a statement can be used to specify cleanup
4944 code which does not handle the exception, but is executed whether an
4945 exception occurred or not in the preceding code.
4946
4947 Python uses the “termination” model of error handling: an exception
4948 handler can find out what happened and continue execution at an outer
4949 level, but it cannot repair the cause of the error and retry the
4950 failing operation (except by re-entering the offending piece of code
4951 from the top).
4952
4953 When an exception is not handled at all, the interpreter terminates
4954 execution of the program, or returns to its interactive main loop. In
4955 either case, it prints a stack traceback, except when the exception is
4956 "SystemExit".
4957
4958 Exceptions are identified by class instances. The "except" clause is
4959 selected depending on the class of the instance: it must reference the
4960 class of the instance or a *non-virtual base class* thereof. The
4961 instance can be received by the handler and can carry additional
4962 information about the exceptional condition.
4963
4964 Note:
4965
4966 Exception messages are not part of the Python API. Their contents
4967 may change from one version of Python to the next without warning
4968 and should not be relied on by code which will run under multiple
4969 versions of the interpreter.
4970
4971 See also the description of the "try" statement in section The try
4972 statement and "raise" statement in section The raise statement.
4973
4974 -[ Footnotes ]-
4975
4976 [1] This limitation occurs because the code that is executed by these
4977 operations is not available at the time the module is compiled.
4978 ''',
4979 'exprlists': r'''Expression lists
4980 ****************
4981
4982 starred_expression ::= ["*"] or_expr
4983 flexible_expression ::= assignment_expression | starred_expression
4984 flexible_expression_list ::= flexible_expression ("," flexible_expression)* [","]
4985 starred_expression_list ::= starred_expression ("," starred_expression)* [","]
4986 expression_list ::= expression ("," expression)* [","]
4987 yield_list ::= expression_list | starred_expression "," [starred_expression_list]
4988
4989 Except when part of a list or set display, an expression list
4990 containing at least one comma yields a tuple. The length of the tuple
4991 is the number of expressions in the list. The expressions are
4992 evaluated from left to right.
4993
4994 An asterisk "*" denotes *iterable unpacking*. Its operand must be an
4995 *iterable*. The iterable is expanded into a sequence of items, which
4996 are included in the new tuple, list, or set, at the site of the
4997 unpacking.
4998
4999 Added in version 3.5: Iterable unpacking in expression lists,
5000 originally proposed by **PEP 448**.
5001
5002 Added in version 3.11: Any item in an expression list may be starred.
5003 See **PEP 646**.
5004
5005 A trailing comma is required only to create a one-item tuple, such as
5006 "1,"; it is optional in all other cases. A single expression without a
5007 trailing comma doesn’t create a tuple, but rather yields the value of
5008 that expression. (To create an empty tuple, use an empty pair of
5009 parentheses: "()".)
5010 ''',
5011 'floating': r'''Floating-point literals
5012 ***********************
5013
5014 Floating-point literals are described by the following lexical
5015 definitions:
5016
5017 floatnumber ::= pointfloat | exponentfloat
5018 pointfloat ::= [digitpart] fraction | digitpart "."
5019 exponentfloat ::= (digitpart | pointfloat) exponent
5020 digitpart ::= digit (["_"] digit)*
5021 fraction ::= "." digitpart
5022 exponent ::= ("e" | "E") ["+" | "-"] digitpart
5023
5024 Note that the integer and exponent parts are always interpreted using
5025 radix 10. For example, "077e010" is legal, and denotes the same number
5026 as "77e10". The allowed range of floating-point literals is
5027 implementation-dependent. As in integer literals, underscores are
5028 supported for digit grouping.
5029
5030 Some examples of floating-point literals:
5031
5032 3.14 10. .001 1e100 3.14e-10 0e0 3.14_15_93
5033
5034 Changed in version 3.6: Underscores are now allowed for grouping
5035 purposes in literals.
5036 ''',
5037 'for': r'''The "for" statement
5038 *******************
5039
5040 The "for" statement is used to iterate over the elements of a sequence
5041 (such as a string, tuple or list) or other iterable object:
5042
5043 for_stmt ::= "for" target_list "in" starred_list ":" suite
5044 ["else" ":" suite]
5045
5046 The "starred_list" expression is evaluated once; it should yield an
5047 *iterable* object. An *iterator* is created for that iterable. The
5048 first item provided by the iterator is then assigned to the target
5049 list using the standard rules for assignments (see Assignment
5050 statements), and the suite is executed. This repeats for each item
5051 provided by the iterator. When the iterator is exhausted, the suite
5052 in the "else" clause, if present, is executed, and the loop
5053 terminates.
5054
5055 A "break" statement executed in the first suite terminates the loop
5056 without executing the "else" clause’s suite. A "continue" statement
5057 executed in the first suite skips the rest of the suite and continues
5058 with the next item, or with the "else" clause if there is no next
5059 item.
5060
5061 The for-loop makes assignments to the variables in the target list.
5062 This overwrites all previous assignments to those variables including
5063 those made in the suite of the for-loop:
5064
5065 for i in range(10):
5066 print(i)
5067 i = 5 # this will not affect the for-loop
5068 # because i will be overwritten with the next
5069 # index in the range
5070
5071 Names in the target list are not deleted when the loop is finished,
5072 but if the sequence is empty, they will not have been assigned to at
5073 all by the loop. Hint: the built-in type "range()" represents
5074 immutable arithmetic sequences of integers. For instance, iterating
5075 "range(3)" successively yields 0, 1, and then 2.
5076
5077 Changed in version 3.11: Starred elements are now allowed in the
5078 expression list.
5079 ''',
5080 'formatstrings': r'''Format String Syntax
5081 ********************
5082
5083 The "str.format()" method and the "Formatter" class share the same
5084 syntax for format strings (although in the case of "Formatter",
5085 subclasses can define their own format string syntax). The syntax is
5086 related to that of formatted string literals, but it is less
5087 sophisticated and, in particular, does not support arbitrary
5088 expressions.
5089
5090 Format strings contain “replacement fields” surrounded by curly braces
5091 "{}". Anything that is not contained in braces is considered literal
5092 text, which is copied unchanged to the output. If you need to include
5093 a brace character in the literal text, it can be escaped by doubling:
5094 "{{" and "}}".
5095
5096 The grammar for a replacement field is as follows:
5097
5098 replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
5099 field_name ::= arg_name ("." attribute_name | "[" element_index "]")*
5100 arg_name ::= [identifier | digit+]
5101 attribute_name ::= identifier
5102 element_index ::= digit+ | index_string
5103 index_string ::= <any source character except "]"> +
5104 conversion ::= "r" | "s" | "a"
5105 format_spec ::= format-spec:format_spec
5106
5107 In less formal terms, the replacement field can start with a
5108 *field_name* that specifies the object whose value is to be formatted
5109 and inserted into the output instead of the replacement field. The
5110 *field_name* is optionally followed by a *conversion* field, which is
5111 preceded by an exclamation point "'!'", and a *format_spec*, which is
5112 preceded by a colon "':'". These specify a non-default format for the
5113 replacement value.
5114
5115 See also the Format Specification Mini-Language section.
5116
5117 The *field_name* itself begins with an *arg_name* that is either a
5118 number or a keyword. If it’s a number, it refers to a positional
5119 argument, and if it’s a keyword, it refers to a named keyword
5120 argument. An *arg_name* is treated as a number if a call to
5121 "str.isdecimal()" on the string would return true. If the numerical
5122 arg_names in a format string are 0, 1, 2, … in sequence, they can all
5123 be omitted (not just some) and the numbers 0, 1, 2, … will be
5124 automatically inserted in that order. Because *arg_name* is not quote-
5125 delimited, it is not possible to specify arbitrary dictionary keys
5126 (e.g., the strings "'10'" or "':-]'") within a format string. The
5127 *arg_name* can be followed by any number of index or attribute
5128 expressions. An expression of the form "'.name'" selects the named
5129 attribute using "getattr()", while an expression of the form
5130 "'[index]'" does an index lookup using "__getitem__()".
5131
5132 Changed in version 3.1: The positional argument specifiers can be
5133 omitted for "str.format()", so "'{} {}'.format(a, b)" is equivalent to
5134 "'{0} {1}'.format(a, b)".
5135
5136 Changed in version 3.4: The positional argument specifiers can be
5137 omitted for "Formatter".
5138
5139 Some simple format string examples:
5140
5141 "First, thou shalt count to {0}" # References first positional argument
5142 "Bring me a {}" # Implicitly references the first positional argument
5143 "From {} to {}" # Same as "From {0} to {1}"
5144 "My quest is {name}" # References keyword argument 'name'
5145 "Weight in tons {0.weight}" # 'weight' attribute of first positional arg
5146 "Units destroyed: {players[0]}" # First element of keyword argument 'players'.
5147
5148 The *conversion* field causes a type coercion before formatting.
5149 Normally, the job of formatting a value is done by the "__format__()"
5150 method of the value itself. However, in some cases it is desirable to
5151 force a type to be formatted as a string, overriding its own
5152 definition of formatting. By converting the value to a string before
5153 calling "__format__()", the normal formatting logic is bypassed.
5154
5155 Three conversion flags are currently supported: "'!s'" which calls
5156 "str()" on the value, "'!r'" which calls "repr()" and "'!a'" which
5157 calls "ascii()".
5158
5159 Some examples:
5160
5161 "Harold's a clever {0!s}" # Calls str() on the argument first
5162 "Bring out the holy {name!r}" # Calls repr() on the argument first
5163 "More {!a}" # Calls ascii() on the argument first
5164
5165 The *format_spec* field contains a specification of how the value
5166 should be presented, including such details as field width, alignment,
5167 padding, decimal precision and so on. Each value type can define its
5168 own “formatting mini-language” or interpretation of the *format_spec*.
5169
5170 Most built-in types support a common formatting mini-language, which
5171 is described in the next section.
5172
5173 A *format_spec* field can also include nested replacement fields
5174 within it. These nested replacement fields may contain a field name,
5175 conversion flag and format specification, but deeper nesting is not
5176 allowed. The replacement fields within the format_spec are
5177 substituted before the *format_spec* string is interpreted. This
5178 allows the formatting of a value to be dynamically specified.
5179
5180 See the Format examples section for some examples.
5181
5182
5183 Format Specification Mini-Language
5184 ==================================
5185
5186 “Format specifications” are used within replacement fields contained
5187 within a format string to define how individual values are presented
5188 (see Format String Syntax and f-strings). They can also be passed
5189 directly to the built-in "format()" function. Each formattable type
5190 may define how the format specification is to be interpreted.
5191
5192 Most built-in types implement the following options for format
5193 specifications, although some of the formatting options are only
5194 supported by the numeric types.
5195
5196 A general convention is that an empty format specification produces
5197 the same result as if you had called "str()" on the value. A non-empty
5198 format specification typically modifies the result.
5199
5200 The general form of a *standard format specifier* is:
5201
5202 format_spec ::= [options][width][grouping]["." precision][type]
5203 options ::= [[fill]align][sign]["z"]["#"]["0"]
5204 fill ::= <any character>
5205 align ::= "<" | ">" | "=" | "^"
5206 sign ::= "+" | "-" | " "
5207 width ::= digit+
5208 grouping ::= "," | "_"
5209 precision ::= digit+
5210 type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g"
5211 | "G" | "n" | "o" | "s" | "x" | "X" | "%"
5212
5213 If a valid *align* value is specified, it can be preceded by a *fill*
5214 character that can be any character and defaults to a space if
5215 omitted. It is not possible to use a literal curly brace (”"{"” or
5216 “"}"”) as the *fill* character in a formatted string literal or when
5217 using the "str.format()" method. However, it is possible to insert a
5218 curly brace with a nested replacement field. This limitation doesn’t
5219 affect the "format()" function.
5220
5221 The meaning of the various alignment options is as follows:
5222
5223 +-----------+------------------------------------------------------------+
5224 | Option | Meaning |
5225 |===========|============================================================|
5226 | "'<'" | Forces the field to be left-aligned within the available |
5227 | | space (this is the default for most objects). |
5228 +-----------+------------------------------------------------------------+
5229 | "'>'" | Forces the field to be right-aligned within the available |
5230 | | space (this is the default for numbers). |
5231 +-----------+------------------------------------------------------------+
5232 | "'='" | Forces the padding to be placed after the sign (if any) |
5233 | | but before the digits. This is used for printing fields |
5234 | | in the form ‘+000000120’. This alignment option is only |
5235 | | valid for numeric types, excluding "complex". It becomes |
5236 | | the default for numbers when ‘0’ immediately precedes the |
5237 | | field width. |
5238 +-----------+------------------------------------------------------------+
5239 | "'^'" | Forces the field to be centered within the available |
5240 | | space. |
5241 +-----------+------------------------------------------------------------+
5242
5243 Note that unless a minimum field width is defined, the field width
5244 will always be the same size as the data to fill it, so that the
5245 alignment option has no meaning in this case.
5246
5247 The *sign* option is only valid for number types, and can be one of
5248 the following:
5249
5250 +-----------+------------------------------------------------------------+
5251 | Option | Meaning |
5252 |===========|============================================================|
5253 | "'+'" | Indicates that a sign should be used for both positive as |
5254 | | well as negative numbers. |
5255 +-----------+------------------------------------------------------------+
5256 | "'-'" | Indicates that a sign should be used only for negative |
5257 | | numbers (this is the default behavior). |
5258 +-----------+------------------------------------------------------------+
5259 | space | Indicates that a leading space should be used on positive |
5260 | | numbers, and a minus sign on negative numbers. |
5261 +-----------+------------------------------------------------------------+
5262
5263 The "'z'" option coerces negative zero floating-point values to
5264 positive zero after rounding to the format precision. This option is
5265 only valid for floating-point presentation types.
5266
5267 Changed in version 3.11: Added the "'z'" option (see also **PEP
5268 682**).
5269
5270 The "'#'" option causes the “alternate form” to be used for the
5271 conversion. The alternate form is defined differently for different
5272 types. This option is only valid for integer, float and complex
5273 types. For integers, when binary, octal, or hexadecimal output is
5274 used, this option adds the respective prefix "'0b'", "'0o'", "'0x'",
5275 or "'0X'" to the output value. For float and complex the alternate
5276 form causes the result of the conversion to always contain a decimal-
5277 point character, even if no digits follow it. Normally, a decimal-
5278 point character appears in the result of these conversions only if a
5279 digit follows it. In addition, for "'g'" and "'G'" conversions,
5280 trailing zeros are not removed from the result.
5281
5282 The *width* is a decimal integer defining the minimum total field
5283 width, including any prefixes, separators, and other formatting
5284 characters. If not specified, then the field width will be determined
5285 by the content.
5286
5287 When no explicit alignment is given, preceding the *width* field by a
5288 zero ("'0'") character enables sign-aware zero-padding for numeric
5289 types, excluding "complex". This is equivalent to a *fill* character
5290 of "'0'" with an *alignment* type of "'='".
5291
5292 Changed in version 3.10: Preceding the *width* field by "'0'" no
5293 longer affects the default alignment for strings.
5294
5295 The *grouping* option after the *width* field specifies a digit group
5296 separator for the integral part of a number. It can be one of the
5297 following:
5298
5299 +-----------+------------------------------------------------------------+
5300 | Option | Meaning |
5301 |===========|============================================================|
5302 | "','" | Inserts a comma every 3 digits for integer presentation |
5303 | | type "'d'" and floating-point presentation types, |
5304 | | excluding "'n'". For other presentation types, this option |
5305 | | is not supported. |
5306 +-----------+------------------------------------------------------------+
5307 | "'_'" | Inserts an underscore every 3 digits for integer |
5308 | | presentation type "'d'" and floating-point presentation |
5309 | | types, excluding "'n'". For integer presentation types |
5310 | | "'b'", "'o'", "'x'", and "'X'", underscores are inserted |
5311 | | every 4 digits. For other presentation types, this option |
5312 | | is not supported. |
5313 +-----------+------------------------------------------------------------+
5314
5315 For a locale aware separator, use the "'n'" presentation type instead.
5316
5317 Changed in version 3.1: Added the "','" option (see also **PEP 378**).
5318
5319 Changed in version 3.6: Added the "'_'" option (see also **PEP 515**).
5320
5321 The *precision* is a decimal integer indicating how many digits should
5322 be displayed after the decimal point for presentation types "'f'" and
5323 "'F'", or before and after the decimal point for presentation types
5324 "'g'" or "'G'". For string presentation types the field indicates the
5325 maximum field size - in other words, how many characters will be used
5326 from the field content. The *precision* is not allowed for integer
5327 presentation types.
5328
5329 Finally, the *type* determines how the data should be presented.
5330
5331 The available string presentation types are:
5332
5333 +-----------+------------------------------------------------------------+
5334 | Type | Meaning |
5335 |===========|============================================================|
5336 | "'s'" | String format. This is the default type for strings and |
5337 | | may be omitted. |
5338 +-----------+------------------------------------------------------------+
5339 | None | The same as "'s'". |
5340 +-----------+------------------------------------------------------------+
5341
5342 The available integer presentation types are:
5343
5344 +-----------+------------------------------------------------------------+
5345 | Type | Meaning |
5346 |===========|============================================================|
5347 | "'b'" | Binary format. Outputs the number in base 2. |
5348 +-----------+------------------------------------------------------------+
5349 | "'c'" | Character. Converts the integer to the corresponding |
5350 | | unicode character before printing. |
5351 +-----------+------------------------------------------------------------+
5352 | "'d'" | Decimal Integer. Outputs the number in base 10. |
5353 +-----------+------------------------------------------------------------+
5354 | "'o'" | Octal format. Outputs the number in base 8. |
5355 +-----------+------------------------------------------------------------+
5356 | "'x'" | Hex format. Outputs the number in base 16, using lower- |
5357 | | case letters for the digits above 9. |
5358 +-----------+------------------------------------------------------------+
5359 | "'X'" | Hex format. Outputs the number in base 16, using upper- |
5360 | | case letters for the digits above 9. In case "'#'" is |
5361 | | specified, the prefix "'0x'" will be upper-cased to "'0X'" |
5362 | | as well. |
5363 +-----------+------------------------------------------------------------+
5364 | "'n'" | Number. This is the same as "'d'", except that it uses the |
5365 | | current locale setting to insert the appropriate digit |
5366 | | group separators. |
5367 +-----------+------------------------------------------------------------+
5368 | None | The same as "'d'". |
5369 +-----------+------------------------------------------------------------+
5370
5371 In addition to the above presentation types, integers can be formatted
5372 with the floating-point presentation types listed below (except "'n'"
5373 and "None"). When doing so, "float()" is used to convert the integer
5374 to a floating-point number before formatting.
5375
5376 The available presentation types for "float" and "Decimal" values are:
5377
5378 +-----------+------------------------------------------------------------+
5379 | Type | Meaning |
5380 |===========|============================================================|
5381 | "'e'" | Scientific notation. For a given precision "p", formats |
5382 | | the number in scientific notation with the letter ‘e’ |
5383 | | separating the coefficient from the exponent. The |
5384 | | coefficient has one digit before and "p" digits after the |
5385 | | decimal point, for a total of "p + 1" significant digits. |
5386 | | With no precision given, uses a precision of "6" digits |
5387 | | after the decimal point for "float", and shows all |
5388 | | coefficient digits for "Decimal". If "p=0", the decimal |
5389 | | point is omitted unless the "#" option is used. For |
5390 | | "float", the exponent always contains at least two digits, |
5391 | | and is zero if the value is zero. |
5392 +-----------+------------------------------------------------------------+
5393 | "'E'" | Scientific notation. Same as "'e'" except it uses an upper |
5394 | | case ‘E’ as the separator character. |
5395 +-----------+------------------------------------------------------------+
5396 | "'f'" | Fixed-point notation. For a given precision "p", formats |
5397 | | the number as a decimal number with exactly "p" digits |
5398 | | following the decimal point. With no precision given, uses |
5399 | | a precision of "6" digits after the decimal point for |
5400 | | "float", and uses a precision large enough to show all |
5401 | | coefficient digits for "Decimal". If "p=0", the decimal |
5402 | | point is omitted unless the "#" option is used. |
5403 +-----------+------------------------------------------------------------+
5404 | "'F'" | Fixed-point notation. Same as "'f'", but converts "nan" to |
5405 | | "NAN" and "inf" to "INF". |
5406 +-----------+------------------------------------------------------------+
5407 | "'g'" | General format. For a given precision "p >= 1", this |
5408 | | rounds the number to "p" significant digits and then |
5409 | | formats the result in either fixed-point format or in |
5410 | | scientific notation, depending on its magnitude. A |
5411 | | precision of "0" is treated as equivalent to a precision |
5412 | | of "1". The precise rules are as follows: suppose that |
5413 | | the result formatted with presentation type "'e'" and |
5414 | | precision "p-1" would have exponent "exp". Then, if "m <= |
5415 | | exp < p", where "m" is -4 for floats and -6 for |
5416 | | "Decimals", the number is formatted with presentation type |
5417 | | "'f'" and precision "p-1-exp". Otherwise, the number is |
5418 | | formatted with presentation type "'e'" and precision |
5419 | | "p-1". In both cases insignificant trailing zeros are |
5420 | | removed from the significand, and the decimal point is |
5421 | | also removed if there are no remaining digits following |
5422 | | it, unless the "'#'" option is used. With no precision |
5423 | | given, uses a precision of "6" significant digits for |
5424 | | "float". For "Decimal", the coefficient of the result is |
5425 | | formed from the coefficient digits of the value; |
5426 | | scientific notation is used for values smaller than "1e-6" |
5427 | | in absolute value and values where the place value of the |
5428 | | least significant digit is larger than 1, and fixed-point |
5429 | | notation is used otherwise. Positive and negative |
5430 | | infinity, positive and negative zero, and nans, are |
5431 | | formatted as "inf", "-inf", "0", "-0" and "nan" |
5432 | | respectively, regardless of the precision. |
5433 +-----------+------------------------------------------------------------+
5434 | "'G'" | General format. Same as "'g'" except switches to "'E'" if |
5435 | | the number gets too large. The representations of infinity |
5436 | | and NaN are uppercased, too. |
5437 +-----------+------------------------------------------------------------+
5438 | "'n'" | Number. This is the same as "'g'", except that it uses the |
5439 | | current locale setting to insert the appropriate digit |
5440 | | group separators for the integral part of a number. |
5441 +-----------+------------------------------------------------------------+
5442 | "'%'" | Percentage. Multiplies the number by 100 and displays in |
5443 | | fixed ("'f'") format, followed by a percent sign. |
5444 +-----------+------------------------------------------------------------+
5445 | None | For "float" this is like the "'g'" type, except that when |
5446 | | fixed- point notation is used to format the result, it |
5447 | | always includes at least one digit past the decimal point, |
5448 | | and switches to the scientific notation when "exp >= p - |
5449 | | 1". When the precision is not specified, the latter will |
5450 | | be as large as needed to represent the given value |
5451 | | faithfully. For "Decimal", this is the same as either |
5452 | | "'g'" or "'G'" depending on the value of |
5453 | | "context.capitals" for the current decimal context. The |
5454 | | overall effect is to match the output of "str()" as |
5455 | | altered by the other format modifiers. |
5456 +-----------+------------------------------------------------------------+
5457
5458 The result should be correctly rounded to a given precision "p" of
5459 digits after the decimal point. The rounding mode for "float" matches
5460 that of the "round()" builtin. For "Decimal", the rounding mode of
5461 the current context will be used.
5462
5463 The available presentation types for "complex" are the same as those
5464 for "float" ("'%'" is not allowed). Both the real and imaginary
5465 components of a complex number are formatted as floating-point
5466 numbers, according to the specified presentation type. They are
5467 separated by the mandatory sign of the imaginary part, the latter
5468 being terminated by a "j" suffix. If the presentation type is
5469 missing, the result will match the output of "str()" (complex numbers
5470 with a non-zero real part are also surrounded by parentheses),
5471 possibly altered by other format modifiers.
5472
5473
5474 Format examples
5475 ===============
5476
5477 This section contains examples of the "str.format()" syntax and
5478 comparison with the old "%"-formatting.
5479
5480 In most of the cases the syntax is similar to the old "%"-formatting,
5481 with the addition of the "{}" and with ":" used instead of "%". For
5482 example, "'%03.2f'" can be translated to "'{:03.2f}'".
5483
5484 The new format syntax also supports new and different options, shown
5485 in the following examples.
5486
5487 Accessing arguments by position:
5488
5489 >>> '{0}, {1}, {2}'.format('a', 'b', 'c')
5490 'a, b, c'
5491 >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only
5492 'a, b, c'
5493 >>> '{2}, {1}, {0}'.format('a', 'b', 'c')
5494 'c, b, a'
5495 >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence
5496 'c, b, a'
5497 >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated
5498 'abracadabra'
5499
5500 Accessing arguments by name:
5501
5502 >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
5503 'Coordinates: 37.24N, -115.81W'
5504 >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
5505 >>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
5506 'Coordinates: 37.24N, -115.81W'
5507
5508 Accessing arguments’ attributes:
5509
5510 >>> c = 3-5j
5511 >>> ('The complex number {0} is formed from the real part {0.real} '
5512 ... 'and the imaginary part {0.imag}.').format(c)
5513 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
5514 >>> class Point:
5515 ... def __init__(self, x, y):
5516 ... self.x, self.y = x, y
5517 ... def __str__(self):
5518 ... return 'Point({self.x}, {self.y})'.format(self=self)
5519 ...
5520 >>> str(Point(4, 2))
5521 'Point(4, 2)'
5522
5523 Accessing arguments’ items:
5524
5525 >>> coord = (3, 5)
5526 >>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
5527 'X: 3; Y: 5'
5528
5529 Replacing "%s" and "%r":
5530
5531 >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
5532 "repr() shows quotes: 'test1'; str() doesn't: test2"
5533
5534 Aligning the text and specifying a width:
5535
5536 >>> '{:<30}'.format('left aligned')
5537 'left aligned '
5538 >>> '{:>30}'.format('right aligned')
5539 ' right aligned'
5540 >>> '{:^30}'.format('centered')
5541 ' centered '
5542 >>> '{:*^30}'.format('centered') # use '*' as a fill char
5543 '***********centered***********'
5544
5545 Replacing "%+f", "%-f", and "% f" and specifying a sign:
5546
5547 >>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it always
5548 '+3.140000; -3.140000'
5549 >>> '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
5550 ' 3.140000; -3.140000'
5551 >>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}'
5552 '3.140000; -3.140000'
5553
5554 Replacing "%x" and "%o" and converting the value to different bases:
5555
5556 >>> # format also supports binary numbers
5557 >>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
5558 'int: 42; hex: 2a; oct: 52; bin: 101010'
5559 >>> # with 0x, 0o, or 0b as prefix:
5560 >>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
5561 'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
5562
5563 Using the comma or the underscore as a digit group separator:
5564
5565 >>> '{:,}'.format(1234567890)
5566 '1,234,567,890'
5567 >>> '{:_}'.format(1234567890)
5568 '1_234_567_890'
5569 >>> '{:_b}'.format(1234567890)
5570 '100_1001_1001_0110_0000_0010_1101_0010'
5571 >>> '{:_x}'.format(1234567890)
5572 '4996_02d2'
5573
5574 Expressing a percentage:
5575
5576 >>> points = 19
5577 >>> total = 22
5578 >>> 'Correct answers: {:.2%}'.format(points/total)
5579 'Correct answers: 86.36%'
5580
5581 Using type-specific formatting:
5582
5583 >>> import datetime
5584 >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
5585 >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
5586 '2010-07-04 12:15:58'
5587
5588 Nesting arguments and more complex examples:
5589
5590 >>> for align, text in zip('<^>', ['left', 'center', 'right']):
5591 ... '{0:{fill}{align}16}'.format(text, fill=align, align=align)
5592 ...
5593 'left<<<<<<<<<<<<'
5594 '^^^^^center^^^^^'
5595 '>>>>>>>>>>>right'
5596 >>>
5597 >>> octets = [192, 168, 0, 1]
5598 >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
5599 'C0A80001'
5600 >>> int(_, 16)
5601 3232235521
5602 >>>
5603 >>> width = 5
5604 >>> for num in range(5,12):
5605 ... for base in 'dXob':
5606 ... print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
5607 ... print()
5608 ...
5609 5 5 5 101
5610 6 6 6 110
5611 7 7 7 111
5612 8 8 10 1000
5613 9 9 11 1001
5614 10 A 12 1010
5615 11 B 13 1011
5616 ''',
5617 'function': r'''Function definitions
5618 ********************
5619
5620 A function definition defines a user-defined function object (see
5621 section The standard type hierarchy):
5622
5623 funcdef ::= [decorators] "def" funcname [type_params] "(" [parameter_list] ")"
5624 ["->" expression] ":" suite
5625 decorators ::= decorator+
5626 decorator ::= "@" assignment_expression NEWLINE
5627 parameter_list ::= defparameter ("," defparameter)* "," "/" ["," [parameter_list_no_posonly]]
5628 | parameter_list_no_posonly
5629 parameter_list_no_posonly ::= defparameter ("," defparameter)* ["," [parameter_list_starargs]]
5630 | parameter_list_starargs
5631 parameter_list_starargs ::= "*" [star_parameter] ("," defparameter)* ["," [parameter_star_kwargs]]
5632 | "*" ("," defparameter)+ ["," [parameter_star_kwargs]]
5633 | parameter_star_kwargs
5634 parameter_star_kwargs ::= "**" parameter [","]
5635 parameter ::= identifier [":" expression]
5636 star_parameter ::= identifier [":" ["*"] expression]
5637 defparameter ::= parameter ["=" expression]
5638 funcname ::= identifier
5639
5640 A function definition is an executable statement. Its execution binds
5641 the function name in the current local namespace to a function object
5642 (a wrapper around the executable code for the function). This
5643 function object contains a reference to the current global namespace
5644 as the global namespace to be used when the function is called.
5645
5646 The function definition does not execute the function body; this gets
5647 executed only when the function is called. [4]
5648
5649 A function definition may be wrapped by one or more *decorator*
5650 expressions. Decorator expressions are evaluated when the function is
5651 defined, in the scope that contains the function definition. The
5652 result must be a callable, which is invoked with the function object
5653 as the only argument. The returned value is bound to the function name
5654 instead of the function object. Multiple decorators are applied in
5655 nested fashion. For example, the following code
5656
5657 @f1(arg)
5658 @f2
5659 def func(): pass
5660
5661 is roughly equivalent to
5662
5663 def func(): pass
5664 func = f1(arg)(f2(func))
5665
5666 except that the original function is not temporarily bound to the name
5667 "func".
5668
5669 Changed in version 3.9: Functions may be decorated with any valid
5670 "assignment_expression". Previously, the grammar was much more
5671 restrictive; see **PEP 614** for details.
5672
5673 A list of type parameters may be given in square brackets between the
5674 function’s name and the opening parenthesis for its parameter list.
5675 This indicates to static type checkers that the function is generic.
5676 At runtime, the type parameters can be retrieved from the function’s
5677 "__type_params__" attribute. See Generic functions for more.
5678
5679 Changed in version 3.12: Type parameter lists are new in Python 3.12.
5680
5681 When one or more *parameters* have the form *parameter* "="
5682 *expression*, the function is said to have “default parameter values.”
5683 For a parameter with a default value, the corresponding *argument* may
5684 be omitted from a call, in which case the parameter’s default value is
5685 substituted. If a parameter has a default value, all following
5686 parameters up until the “"*"” must also have a default value — this is
5687 a syntactic restriction that is not expressed by the grammar.
5688
5689 **Default parameter values are evaluated from left to right when the
5690 function definition is executed.** This means that the expression is
5691 evaluated once, when the function is defined, and that the same “pre-
5692 computed” value is used for each call. This is especially important
5693 to understand when a default parameter value is a mutable object, such
5694 as a list or a dictionary: if the function modifies the object (e.g.
5695 by appending an item to a list), the default parameter value is in
5696 effect modified. This is generally not what was intended. A way
5697 around this is to use "None" as the default, and explicitly test for
5698 it in the body of the function, e.g.:
5699
5700 def whats_on_the_telly(penguin=None):
5701 if penguin is None:
5702 penguin = []
5703 penguin.append("property of the zoo")
5704 return penguin
5705
5706 Function call semantics are described in more detail in section Calls.
5707 A function call always assigns values to all parameters mentioned in
5708 the parameter list, either from positional arguments, from keyword
5709 arguments, or from default values. If the form “"*identifier"” is
5710 present, it is initialized to a tuple receiving any excess positional
5711 parameters, defaulting to the empty tuple. If the form
5712 “"**identifier"” is present, it is initialized to a new ordered
5713 mapping receiving any excess keyword arguments, defaulting to a new
5714 empty mapping of the same type. Parameters after “"*"” or
5715 “"*identifier"” are keyword-only parameters and may only be passed by
5716 keyword arguments. Parameters before “"/"” are positional-only
5717 parameters and may only be passed by positional arguments.
5718
5719 Changed in version 3.8: The "/" function parameter syntax may be used
5720 to indicate positional-only parameters. See **PEP 570** for details.
5721
5722 Parameters may have an *annotation* of the form “": expression"”
5723 following the parameter name. Any parameter may have an annotation,
5724 even those of the form "*identifier" or "**identifier". (As a special
5725 case, parameters of the form "*identifier" may have an annotation “":
5726 *expression"”.) Functions may have “return” annotation of the form
5727 “"-> expression"” after the parameter list. These annotations can be
5728 any valid Python expression. The presence of annotations does not
5729 change the semantics of a function. The annotation values are
5730 available as values of a dictionary keyed by the parameters’ names in
5731 the "__annotations__" attribute of the function object. If the
5732 "annotations" import from "__future__" is used, annotations are
5733 preserved as strings at runtime which enables postponed evaluation.
5734 Otherwise, they are evaluated when the function definition is
5735 executed. In this case annotations may be evaluated in a different
5736 order than they appear in the source code.
5737
5738 Changed in version 3.11: Parameters of the form “"*identifier"” may
5739 have an annotation “": *expression"”. See **PEP 646**.
5740
5741 It is also possible to create anonymous functions (functions not bound
5742 to a name), for immediate use in expressions. This uses lambda
5743 expressions, described in section Lambdas. Note that the lambda
5744 expression is merely a shorthand for a simplified function definition;
5745 a function defined in a “"def"” statement can be passed around or
5746 assigned to another name just like a function defined by a lambda
5747 expression. The “"def"” form is actually more powerful since it
5748 allows the execution of multiple statements and annotations.
5749
5750 **Programmer’s note:** Functions are first-class objects. A “"def"”
5751 statement executed inside a function definition defines a local
5752 function that can be returned or passed around. Free variables used
5753 in the nested function can access the local variables of the function
5754 containing the def. See section Naming and binding for details.
5755
5756 See also:
5757
5758 **PEP 3107** - Function Annotations
5759 The original specification for function annotations.
5760
5761 **PEP 484** - Type Hints
5762 Definition of a standard meaning for annotations: type hints.
5763
5764 **PEP 526** - Syntax for Variable Annotations
5765 Ability to type hint variable declarations, including class
5766 variables and instance variables.
5767
5768 **PEP 563** - Postponed Evaluation of Annotations
5769 Support for forward references within annotations by preserving
5770 annotations in a string form at runtime instead of eager
5771 evaluation.
5772
5773 **PEP 318** - Decorators for Functions and Methods
5774 Function and method decorators were introduced. Class decorators
5775 were introduced in **PEP 3129**.
5776 ''',
5777 'global': r'''The "global" statement
5778 **********************
5779
5780 global_stmt ::= "global" identifier ("," identifier)*
5781
5782 The "global" statement causes the listed identifiers to be interpreted
5783 as globals. It would be impossible to assign to a global variable
5784 without "global", although free variables may refer to globals without
5785 being declared global.
5786
5787 The "global" statement applies to the entire current scope (module,
5788 function body or class definition). A "SyntaxError" is raised if a
5789 variable is used or assigned to prior to its global declaration in the
5790 scope.
5791
5792 At the module level, all variables are global, so a "global" statement
5793 has no effect. However, variables must still not be used or assigned
5794 to prior to their "global" declaration. This requirement is relaxed in
5795 the interactive prompt (*REPL*).
5796
5797 **Programmer’s note:** "global" is a directive to the parser. It
5798 applies only to code parsed at the same time as the "global"
5799 statement. In particular, a "global" statement contained in a string
5800 or code object supplied to the built-in "exec()" function does not
5801 affect the code block *containing* the function call, and code
5802 contained in such a string is unaffected by "global" statements in the
5803 code containing the function call. The same applies to the "eval()"
5804 and "compile()" functions.
5805 ''',
5806 'id-classes': r'''Reserved classes of identifiers
5807 *******************************
5808
5809 Certain classes of identifiers (besides keywords) have special
5810 meanings. These classes are identified by the patterns of leading and
5811 trailing underscore characters:
5812
5813 "_*"
5814 Not imported by "from module import *".
5815
5816 "_"
5817 In a "case" pattern within a "match" statement, "_" is a soft
5818 keyword that denotes a wildcard.
5819
5820 Separately, the interactive interpreter makes the result of the
5821 last evaluation available in the variable "_". (It is stored in the
5822 "builtins" module, alongside built-in functions like "print".)
5823
5824 Elsewhere, "_" is a regular identifier. It is often used to name
5825 “special” items, but it is not special to Python itself.
5826
5827 Note:
5828
5829 The name "_" is often used in conjunction with
5830 internationalization; refer to the documentation for the
5831 "gettext" module for more information on this convention.It is
5832 also commonly used for unused variables.
5833
5834 "__*__"
5835 System-defined names, informally known as “dunder” names. These
5836 names are defined by the interpreter and its implementation
5837 (including the standard library). Current system names are
5838 discussed in the Special method names section and elsewhere. More
5839 will likely be defined in future versions of Python. *Any* use of
5840 "__*__" names, in any context, that does not follow explicitly
5841 documented use, is subject to breakage without warning.
5842
5843 "__*"
5844 Class-private names. Names in this category, when used within the
5845 context of a class definition, are re-written to use a mangled form
5846 to help avoid name clashes between “private” attributes of base and
5847 derived classes. See section Identifiers (Names).
5848 ''',
5849 'identifiers': r'''Identifiers and keywords
5850 ************************
5851
5852 Identifiers (also referred to as *names*) are described by the
5853 following lexical definitions.
5854
5855 The syntax of identifiers in Python is based on the Unicode standard
5856 annex UAX-31, with elaboration and changes as defined below; see also
5857 **PEP 3131** for further details.
5858
5859 Within the ASCII range (U+0001..U+007F), the valid characters for
5860 identifiers include the uppercase and lowercase letters "A" through
5861 "Z", the underscore "_" and, except for the first character, the
5862 digits "0" through "9". Python 3.0 introduced additional characters
5863 from outside the ASCII range (see **PEP 3131**). For these
5864 characters, the classification uses the version of the Unicode
5865 Character Database as included in the "unicodedata" module.
5866
5867 Identifiers are unlimited in length. Case is significant.
5868
5869 identifier ::= xid_start xid_continue*
5870 id_start ::= <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property>
5871 id_continue ::= <all characters in id_start, plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property>
5872 xid_start ::= <all characters in id_start whose NFKC normalization is in "id_start xid_continue*">
5873 xid_continue ::= <all characters in id_continue whose NFKC normalization is in "id_continue*">
5874
5875 The Unicode category codes mentioned above stand for:
5876
5877 * *Lu* - uppercase letters
5878
5879 * *Ll* - lowercase letters
5880
5881 * *Lt* - titlecase letters
5882
5883 * *Lm* - modifier letters
5884
5885 * *Lo* - other letters
5886
5887 * *Nl* - letter numbers
5888
5889 * *Mn* - nonspacing marks
5890
5891 * *Mc* - spacing combining marks
5892
5893 * *Nd* - decimal numbers
5894
5895 * *Pc* - connector punctuations
5896
5897 * *Other_ID_Start* - explicit list of characters in PropList.txt to
5898 support backwards compatibility
5899
5900 * *Other_ID_Continue* - likewise
5901
5902 All identifiers are converted into the normal form NFKC while parsing;
5903 comparison of identifiers is based on NFKC.
5904
5905 A non-normative HTML file listing all valid identifier characters for
5906 Unicode 15.1.0 can be found at
5907 https://www.unicode.org/Public/15.1.0/ucd/DerivedCoreProperties.txt
5908
5909
5910 Keywords
5911 ========
5912
5913 The following identifiers are used as reserved words, or *keywords* of
5914 the language, and cannot be used as ordinary identifiers. They must
5915 be spelled exactly as written here:
5916
5917 False await else import pass
5918 None break except in raise
5919 True class finally is return
5920 and continue for lambda try
5921 as def from nonlocal while
5922 assert del global not with
5923 async elif if or yield
5924
5925
5926 Soft Keywords
5927 =============
5928
5929 Added in version 3.10.
5930
5931 Some identifiers are only reserved under specific contexts. These are
5932 known as *soft keywords*. The identifiers "match", "case", "type" and
5933 "_" can syntactically act as keywords in certain contexts, but this
5934 distinction is done at the parser level, not when tokenizing.
5935
5936 As soft keywords, their use in the grammar is possible while still
5937 preserving compatibility with existing code that uses these names as
5938 identifier names.
5939
5940 "match", "case", and "_" are used in the "match" statement. "type" is
5941 used in the "type" statement.
5942
5943 Changed in version 3.12: "type" is now a soft keyword.
5944
5945
5946 Reserved classes of identifiers
5947 ===============================
5948
5949 Certain classes of identifiers (besides keywords) have special
5950 meanings. These classes are identified by the patterns of leading and
5951 trailing underscore characters:
5952
5953 "_*"
5954 Not imported by "from module import *".
5955
5956 "_"
5957 In a "case" pattern within a "match" statement, "_" is a soft
5958 keyword that denotes a wildcard.
5959
5960 Separately, the interactive interpreter makes the result of the
5961 last evaluation available in the variable "_". (It is stored in the
5962 "builtins" module, alongside built-in functions like "print".)
5963
5964 Elsewhere, "_" is a regular identifier. It is often used to name
5965 “special” items, but it is not special to Python itself.
5966
5967 Note:
5968
5969 The name "_" is often used in conjunction with
5970 internationalization; refer to the documentation for the
5971 "gettext" module for more information on this convention.It is
5972 also commonly used for unused variables.
5973
5974 "__*__"
5975 System-defined names, informally known as “dunder” names. These
5976 names are defined by the interpreter and its implementation
5977 (including the standard library). Current system names are
5978 discussed in the Special method names section and elsewhere. More
5979 will likely be defined in future versions of Python. *Any* use of
5980 "__*__" names, in any context, that does not follow explicitly
5981 documented use, is subject to breakage without warning.
5982
5983 "__*"
5984 Class-private names. Names in this category, when used within the
5985 context of a class definition, are re-written to use a mangled form
5986 to help avoid name clashes between “private” attributes of base and
5987 derived classes. See section Identifiers (Names).
5988 ''',
5989 'if': r'''The "if" statement
5990 ******************
5991
5992 The "if" statement is used for conditional execution:
5993
5994 if_stmt ::= "if" assignment_expression ":" suite
5995 ("elif" assignment_expression ":" suite)*
5996 ["else" ":" suite]
5997
5998 It selects exactly one of the suites by evaluating the expressions one
5999 by one until one is found to be true (see section Boolean operations
6000 for the definition of true and false); then that suite is executed
6001 (and no other part of the "if" statement is executed or evaluated).
6002 If all expressions are false, the suite of the "else" clause, if
6003 present, is executed.
6004 ''',
6005 'imaginary': r'''Imaginary literals
6006 ******************
6007
6008 Imaginary literals are described by the following lexical definitions:
6009
6010 imagnumber ::= (floatnumber | digitpart) ("j" | "J")
6011
6012 An imaginary literal yields a complex number with a real part of 0.0.
6013 Complex numbers are represented as a pair of floating-point numbers
6014 and have the same restrictions on their range. To create a complex
6015 number with a nonzero real part, add a floating-point number to it,
6016 e.g., "(3+4j)". Some examples of imaginary literals:
6017
6018 3.14j 10.j 10j .001j 1e100j 3.14e-10j 3.14_15_93j
6019 ''',
6020 'import': r'''The "import" statement
6021 **********************
6022
6023 import_stmt ::= "import" module ["as" identifier] ("," module ["as" identifier])*
6024 | "from" relative_module "import" identifier ["as" identifier]
6025 ("," identifier ["as" identifier])*
6026 | "from" relative_module "import" "(" identifier ["as" identifier]
6027 ("," identifier ["as" identifier])* [","] ")"
6028 | "from" relative_module "import" "*"
6029 module ::= (identifier ".")* identifier
6030 relative_module ::= "."* module | "."+
6031
6032 The basic import statement (no "from" clause) is executed in two
6033 steps:
6034
6035 1. find a module, loading and initializing it if necessary
6036
6037 2. define a name or names in the local namespace for the scope where
6038 the "import" statement occurs.
6039
6040 When the statement contains multiple clauses (separated by commas) the
6041 two steps are carried out separately for each clause, just as though
6042 the clauses had been separated out into individual import statements.
6043
6044 The details of the first step, finding and loading modules, are
6045 described in greater detail in the section on the import system, which
6046 also describes the various types of packages and modules that can be
6047 imported, as well as all the hooks that can be used to customize the
6048 import system. Note that failures in this step may indicate either
6049 that the module could not be located, *or* that an error occurred
6050 while initializing the module, which includes execution of the
6051 module’s code.
6052
6053 If the requested module is retrieved successfully, it will be made
6054 available in the local namespace in one of three ways:
6055
6056 * If the module name is followed by "as", then the name following "as"
6057 is bound directly to the imported module.
6058
6059 * If no other name is specified, and the module being imported is a
6060 top level module, the module’s name is bound in the local namespace
6061 as a reference to the imported module
6062
6063 * If the module being imported is *not* a top level module, then the
6064 name of the top level package that contains the module is bound in
6065 the local namespace as a reference to the top level package. The
6066 imported module must be accessed using its full qualified name
6067 rather than directly
6068
6069 The "from" form uses a slightly more complex process:
6070
6071 1. find the module specified in the "from" clause, loading and
6072 initializing it if necessary;
6073
6074 2. for each of the identifiers specified in the "import" clauses:
6075
6076 1. check if the imported module has an attribute by that name
6077
6078 2. if not, attempt to import a submodule with that name and then
6079 check the imported module again for that attribute
6080
6081 3. if the attribute is not found, "ImportError" is raised.
6082
6083 4. otherwise, a reference to that value is stored in the local
6084 namespace, using the name in the "as" clause if it is present,
6085 otherwise using the attribute name
6086
6087 Examples:
6088
6089 import foo # foo imported and bound locally
6090 import foo.bar.baz # foo, foo.bar, and foo.bar.baz imported, foo bound locally
6091 import foo.bar.baz as fbb # foo, foo.bar, and foo.bar.baz imported, foo.bar.baz bound as fbb
6092 from foo.bar import baz # foo, foo.bar, and foo.bar.baz imported, foo.bar.baz bound as baz
6093 from foo import attr # foo imported and foo.attr bound as attr
6094
6095 If the list of identifiers is replaced by a star ("'*'"), all public
6096 names defined in the module are bound in the local namespace for the
6097 scope where the "import" statement occurs.
6098
6099 The *public names* defined by a module are determined by checking the
6100 module’s namespace for a variable named "__all__"; if defined, it must
6101 be a sequence of strings which are names defined or imported by that
6102 module. The names given in "__all__" are all considered public and
6103 are required to exist. If "__all__" is not defined, the set of public
6104 names includes all names found in the module’s namespace which do not
6105 begin with an underscore character ("'_'"). "__all__" should contain
6106 the entire public API. It is intended to avoid accidentally exporting
6107 items that are not part of the API (such as library modules which were
6108 imported and used within the module).
6109
6110 The wild card form of import — "from module import *" — is only
6111 allowed at the module level. Attempting to use it in class or
6112 function definitions will raise a "SyntaxError".
6113
6114 When specifying what module to import you do not have to specify the
6115 absolute name of the module. When a module or package is contained
6116 within another package it is possible to make a relative import within
6117 the same top package without having to mention the package name. By
6118 using leading dots in the specified module or package after "from" you
6119 can specify how high to traverse up the current package hierarchy
6120 without specifying exact names. One leading dot means the current
6121 package where the module making the import exists. Two dots means up
6122 one package level. Three dots is up two levels, etc. So if you execute
6123 "from . import mod" from a module in the "pkg" package then you will
6124 end up importing "pkg.mod". If you execute "from ..subpkg2 import mod"
6125 from within "pkg.subpkg1" you will import "pkg.subpkg2.mod". The
6126 specification for relative imports is contained in the Package
6127 Relative Imports section.
6128
6129 "importlib.import_module()" is provided to support applications that
6130 determine dynamically the modules to be loaded.
6131
6132 Raises an auditing event "import" with arguments "module", "filename",
6133 "sys.path", "sys.meta_path", "sys.path_hooks".
6134
6135
6136 Future statements
6137 =================
6138
6139 A *future statement* is a directive to the compiler that a particular
6140 module should be compiled using syntax or semantics that will be
6141 available in a specified future release of Python where the feature
6142 becomes standard.
6143
6144 The future statement is intended to ease migration to future versions
6145 of Python that introduce incompatible changes to the language. It
6146 allows use of the new features on a per-module basis before the
6147 release in which the feature becomes standard.
6148
6149 future_stmt ::= "from" "__future__" "import" feature ["as" identifier]
6150 ("," feature ["as" identifier])*
6151 | "from" "__future__" "import" "(" feature ["as" identifier]
6152 ("," feature ["as" identifier])* [","] ")"
6153 feature ::= identifier
6154
6155 A future statement must appear near the top of the module. The only
6156 lines that can appear before a future statement are:
6157
6158 * the module docstring (if any),
6159
6160 * comments,
6161
6162 * blank lines, and
6163
6164 * other future statements.
6165
6166 The only feature that requires using the future statement is
6167 "annotations" (see **PEP 563**).
6168
6169 All historical features enabled by the future statement are still
6170 recognized by Python 3. The list includes "absolute_import",
6171 "division", "generators", "generator_stop", "unicode_literals",
6172 "print_function", "nested_scopes" and "with_statement". They are all
6173 redundant because they are always enabled, and only kept for backwards
6174 compatibility.
6175
6176 A future statement is recognized and treated specially at compile
6177 time: Changes to the semantics of core constructs are often
6178 implemented by generating different code. It may even be the case
6179 that a new feature introduces new incompatible syntax (such as a new
6180 reserved word), in which case the compiler may need to parse the
6181 module differently. Such decisions cannot be pushed off until
6182 runtime.
6183
6184 For any given release, the compiler knows which feature names have
6185 been defined, and raises a compile-time error if a future statement
6186 contains a feature not known to it.
6187
6188 The direct runtime semantics are the same as for any import statement:
6189 there is a standard module "__future__", described later, and it will
6190 be imported in the usual way at the time the future statement is
6191 executed.
6192
6193 The interesting runtime semantics depend on the specific feature
6194 enabled by the future statement.
6195
6196 Note that there is nothing special about the statement:
6197
6198 import __future__ [as name]
6199
6200 That is not a future statement; it’s an ordinary import statement with
6201 no special semantics or syntax restrictions.
6202
6203 Code compiled by calls to the built-in functions "exec()" and
6204 "compile()" that occur in a module "M" containing a future statement
6205 will, by default, use the new syntax or semantics associated with the
6206 future statement. This can be controlled by optional arguments to
6207 "compile()" — see the documentation of that function for details.
6208
6209 A future statement typed at an interactive interpreter prompt will
6210 take effect for the rest of the interpreter session. If an
6211 interpreter is started with the "-i" option, is passed a script name
6212 to execute, and the script includes a future statement, it will be in
6213 effect in the interactive session started after the script is
6214 executed.
6215
6216 See also:
6217
6218 **PEP 236** - Back to the __future__
6219 The original proposal for the __future__ mechanism.
6220 ''',
6221 'in': r'''Membership test operations
6222 **************************
6223
6224 The operators "in" and "not in" test for membership. "x in s"
6225 evaluates to "True" if *x* is a member of *s*, and "False" otherwise.
6226 "x not in s" returns the negation of "x in s". All built-in sequences
6227 and set types support this as well as dictionary, for which "in" tests
6228 whether the dictionary has a given key. For container types such as
6229 list, tuple, set, frozenset, dict, or collections.deque, the
6230 expression "x in y" is equivalent to "any(x is e or x == e for e in
6231 y)".
6232
6233 For the string and bytes types, "x in y" is "True" if and only if *x*
6234 is a substring of *y*. An equivalent test is "y.find(x) != -1".
6235 Empty strings are always considered to be a substring of any other
6236 string, so """ in "abc"" will return "True".
6237
6238 For user-defined classes which define the "__contains__()" method, "x
6239 in y" returns "True" if "y.__contains__(x)" returns a true value, and
6240 "False" otherwise.
6241
6242 For user-defined classes which do not define "__contains__()" but do
6243 define "__iter__()", "x in y" is "True" if some value "z", for which
6244 the expression "x is z or x == z" is true, is produced while iterating
6245 over "y". If an exception is raised during the iteration, it is as if
6246 "in" raised that exception.
6247
6248 Lastly, the old-style iteration protocol is tried: if a class defines
6249 "__getitem__()", "x in y" is "True" if and only if there is a non-
6250 negative integer index *i* such that "x is y[i] or x == y[i]", and no
6251 lower integer index raises the "IndexError" exception. (If any other
6252 exception is raised, it is as if "in" raised that exception).
6253
6254 The operator "not in" is defined to have the inverse truth value of
6255 "in".
6256 ''',
6257 'integers': r'''Integer literals
6258 ****************
6259
6260 Integer literals are described by the following lexical definitions:
6261
6262 integer ::= decinteger | bininteger | octinteger | hexinteger
6263 decinteger ::= nonzerodigit (["_"] digit)* | "0"+ (["_"] "0")*
6264 bininteger ::= "0" ("b" | "B") (["_"] bindigit)+
6265 octinteger ::= "0" ("o" | "O") (["_"] octdigit)+
6266 hexinteger ::= "0" ("x" | "X") (["_"] hexdigit)+
6267 nonzerodigit ::= "1"..."9"
6268 digit ::= "0"..."9"
6269 bindigit ::= "0" | "1"
6270 octdigit ::= "0"..."7"
6271 hexdigit ::= digit | "a"..."f" | "A"..."F"
6272
6273 There is no limit for the length of integer literals apart from what
6274 can be stored in available memory.
6275
6276 Underscores are ignored for determining the numeric value of the
6277 literal. They can be used to group digits for enhanced readability.
6278 One underscore can occur between digits, and after base specifiers
6279 like "0x".
6280
6281 Note that leading zeros in a non-zero decimal number are not allowed.
6282 This is for disambiguation with C-style octal literals, which Python
6283 used before version 3.0.
6284
6285 Some examples of integer literals:
6286
6287 7 2147483647 0o177 0b100110111
6288 3 79228162514264337593543950336 0o377 0xdeadbeef
6289 100_000_000_000 0b_1110_0101
6290
6291 Changed in version 3.6: Underscores are now allowed for grouping
6292 purposes in literals.
6293 ''',
6294 'lambda': r'''Lambdas
6295 *******
6296
6297 lambda_expr ::= "lambda" [parameter_list] ":" expression
6298
6299 Lambda expressions (sometimes called lambda forms) are used to create
6300 anonymous functions. The expression "lambda parameters: expression"
6301 yields a function object. The unnamed object behaves like a function
6302 object defined with:
6303
6304 def <lambda>(parameters):
6305 return expression
6306
6307 See section Function definitions for the syntax of parameter lists.
6308 Note that functions created with lambda expressions cannot contain
6309 statements or annotations.
6310 ''',
6311 'lists': r'''List displays
6312 *************
6313
6314 A list display is a possibly empty series of expressions enclosed in
6315 square brackets:
6316
6317 list_display ::= "[" [flexible_expression_list | comprehension] "]"
6318
6319 A list display yields a new list object, the contents being specified
6320 by either a list of expressions or a comprehension. When a comma-
6321 separated list of expressions is supplied, its elements are evaluated
6322 from left to right and placed into the list object in that order.
6323 When a comprehension is supplied, the list is constructed from the
6324 elements resulting from the comprehension.
6325 ''',
6326 'naming': r'''Naming and binding
6327 ******************
6328
6329
6330 Binding of names
6331 ================
6332
6333 *Names* refer to objects. Names are introduced by name binding
6334 operations.
6335
6336 The following constructs bind names:
6337
6338 * formal parameters to functions,
6339
6340 * class definitions,
6341
6342 * function definitions,
6343
6344 * assignment expressions,
6345
6346 * targets that are identifiers if occurring in an assignment:
6347
6348 * "for" loop header,
6349
6350 * after "as" in a "with" statement, "except" clause, "except*"
6351 clause, or in the as-pattern in structural pattern matching,
6352
6353 * in a capture pattern in structural pattern matching
6354
6355 * "import" statements.
6356
6357 * "type" statements.
6358
6359 * type parameter lists.
6360
6361 The "import" statement of the form "from ... import *" binds all names
6362 defined in the imported module, except those beginning with an
6363 underscore. This form may only be used at the module level.
6364
6365 A target occurring in a "del" statement is also considered bound for
6366 this purpose (though the actual semantics are to unbind the name).
6367
6368 Each assignment or import statement occurs within a block defined by a
6369 class or function definition or at the module level (the top-level
6370 code block).
6371
6372 If a name is bound in a block, it is a local variable of that block,
6373 unless declared as "nonlocal" or "global". If a name is bound at the
6374 module level, it is a global variable. (The variables of the module
6375 code block are local and global.) If a variable is used in a code
6376 block but not defined there, it is a *free variable*.
6377
6378 Each occurrence of a name in the program text refers to the *binding*
6379 of that name established by the following name resolution rules.
6380
6381
6382 Resolution of names
6383 ===================
6384
6385 A *scope* defines the visibility of a name within a block. If a local
6386 variable is defined in a block, its scope includes that block. If the
6387 definition occurs in a function block, the scope extends to any blocks
6388 contained within the defining one, unless a contained block introduces
6389 a different binding for the name.
6390
6391 When a name is used in a code block, it is resolved using the nearest
6392 enclosing scope. The set of all such scopes visible to a code block
6393 is called the block’s *environment*.
6394
6395 When a name is not found at all, a "NameError" exception is raised. If
6396 the current scope is a function scope, and the name refers to a local
6397 variable that has not yet been bound to a value at the point where the
6398 name is used, an "UnboundLocalError" exception is raised.
6399 "UnboundLocalError" is a subclass of "NameError".
6400
6401 If a name binding operation occurs anywhere within a code block, all
6402 uses of the name within the block are treated as references to the
6403 current block. This can lead to errors when a name is used within a
6404 block before it is bound. This rule is subtle. Python lacks
6405 declarations and allows name binding operations to occur anywhere
6406 within a code block. The local variables of a code block can be
6407 determined by scanning the entire text of the block for name binding
6408 operations. See the FAQ entry on UnboundLocalError for examples.
6409
6410 If the "global" statement occurs within a block, all uses of the names
6411 specified in the statement refer to the bindings of those names in the
6412 top-level namespace. Names are resolved in the top-level namespace by
6413 searching the global namespace, i.e. the namespace of the module
6414 containing the code block, and the builtins namespace, the namespace
6415 of the module "builtins". The global namespace is searched first. If
6416 the names are not found there, the builtins namespace is searched
6417 next. If the names are also not found in the builtins namespace, new
6418 variables are created in the global namespace. The global statement
6419 must precede all uses of the listed names.
6420
6421 The "global" statement has the same scope as a name binding operation
6422 in the same block. If the nearest enclosing scope for a free variable
6423 contains a global statement, the free variable is treated as a global.
6424
6425 The "nonlocal" statement causes corresponding names to refer to
6426 previously bound variables in the nearest enclosing function scope.
6427 "SyntaxError" is raised at compile time if the given name does not
6428 exist in any enclosing function scope. Type parameters cannot be
6429 rebound with the "nonlocal" statement.
6430
6431 The namespace for a module is automatically created the first time a
6432 module is imported. The main module for a script is always called
6433 "__main__".
6434
6435 Class definition blocks and arguments to "exec()" and "eval()" are
6436 special in the context of name resolution. A class definition is an
6437 executable statement that may use and define names. These references
6438 follow the normal rules for name resolution with an exception that
6439 unbound local variables are looked up in the global namespace. The
6440 namespace of the class definition becomes the attribute dictionary of
6441 the class. The scope of names defined in a class block is limited to
6442 the class block; it does not extend to the code blocks of methods.
6443 This includes comprehensions and generator expressions, but it does
6444 not include annotation scopes, which have access to their enclosing
6445 class scopes. This means that the following will fail:
6446
6447 class A:
6448 a = 42
6449 b = list(a + i for i in range(10))
6450
6451 However, the following will succeed:
6452
6453 class A:
6454 type Alias = Nested
6455 class Nested: pass
6456
6457 print(A.Alias.__value__) # <type 'A.Nested'>
6458
6459
6460 Annotation scopes
6461 =================
6462
6463 Type parameter lists and "type" statements introduce *annotation
6464 scopes*, which behave mostly like function scopes, but with some
6465 exceptions discussed below. *Annotations* currently do not use
6466 annotation scopes, but they are expected to use annotation scopes in
6467 Python 3.13 when **PEP 649** is implemented.
6468
6469 Annotation scopes are used in the following contexts:
6470
6471 * Type parameter lists for generic type aliases.
6472
6473 * Type parameter lists for generic functions. A generic function’s
6474 annotations are executed within the annotation scope, but its
6475 defaults and decorators are not.
6476
6477 * Type parameter lists for generic classes. A generic class’s base
6478 classes and keyword arguments are executed within the annotation
6479 scope, but its decorators are not.
6480
6481 * The bounds, constraints, and default values for type parameters
6482 (lazily evaluated).
6483
6484 * The value of type aliases (lazily evaluated).
6485
6486 Annotation scopes differ from function scopes in the following ways:
6487
6488 * Annotation scopes have access to their enclosing class namespace. If
6489 an annotation scope is immediately within a class scope, or within
6490 another annotation scope that is immediately within a class scope,
6491 the code in the annotation scope can use names defined in the class
6492 scope as if it were executed directly within the class body. This
6493 contrasts with regular functions defined within classes, which
6494 cannot access names defined in the class scope.
6495
6496 * Expressions in annotation scopes cannot contain "yield", "yield
6497 from", "await", or ":=" expressions. (These expressions are allowed
6498 in other scopes contained within the annotation scope.)
6499
6500 * Names defined in annotation scopes cannot be rebound with "nonlocal"
6501 statements in inner scopes. This includes only type parameters, as
6502 no other syntactic elements that can appear within annotation scopes
6503 can introduce new names.
6504
6505 * While annotation scopes have an internal name, that name is not
6506 reflected in the *qualified name* of objects defined within the
6507 scope. Instead, the "__qualname__" of such objects is as if the
6508 object were defined in the enclosing scope.
6509
6510 Added in version 3.12: Annotation scopes were introduced in Python
6511 3.12 as part of **PEP 695**.
6512
6513 Changed in version 3.13: Annotation scopes are also used for type
6514 parameter defaults, as introduced by **PEP 696**.
6515
6516
6517 Lazy evaluation
6518 ===============
6519
6520 The values of type aliases created through the "type" statement are
6521 *lazily evaluated*. The same applies to the bounds, constraints, and
6522 default values of type variables created through the type parameter
6523 syntax. This means that they are not evaluated when the type alias or
6524 type variable is created. Instead, they are only evaluated when doing
6525 so is necessary to resolve an attribute access.
6526
6527 Example:
6528
6529 >>> type Alias = 1/0
6530 >>> Alias.__value__
6531 Traceback (most recent call last):
6532 ...
6533 ZeroDivisionError: division by zero
6534 >>> def func[T: 1/0](): pass
6535 >>> T = func.__type_params__[0]
6536 >>> T.__bound__
6537 Traceback (most recent call last):
6538 ...
6539 ZeroDivisionError: division by zero
6540
6541 Here the exception is raised only when the "__value__" attribute of
6542 the type alias or the "__bound__" attribute of the type variable is
6543 accessed.
6544
6545 This behavior is primarily useful for references to types that have
6546 not yet been defined when the type alias or type variable is created.
6547 For example, lazy evaluation enables creation of mutually recursive
6548 type aliases:
6549
6550 from typing import Literal
6551
6552 type SimpleExpr = int | Parenthesized
6553 type Parenthesized = tuple[Literal["("], Expr, Literal[")"]]
6554 type Expr = SimpleExpr | tuple[SimpleExpr, Literal["+", "-"], Expr]
6555
6556 Lazily evaluated values are evaluated in annotation scope, which means
6557 that names that appear inside the lazily evaluated value are looked up
6558 as if they were used in the immediately enclosing scope.
6559
6560 Added in version 3.12.
6561
6562
6563 Builtins and restricted execution
6564 =================================
6565
6566 **CPython implementation detail:** Users should not touch
6567 "__builtins__"; it is strictly an implementation detail. Users
6568 wanting to override values in the builtins namespace should "import"
6569 the "builtins" module and modify its attributes appropriately.
6570
6571 The builtins namespace associated with the execution of a code block
6572 is actually found by looking up the name "__builtins__" in its global
6573 namespace; this should be a dictionary or a module (in the latter case
6574 the module’s dictionary is used). By default, when in the "__main__"
6575 module, "__builtins__" is the built-in module "builtins"; when in any
6576 other module, "__builtins__" is an alias for the dictionary of the
6577 "builtins" module itself.
6578
6579
6580 Interaction with dynamic features
6581 =================================
6582
6583 Name resolution of free variables occurs at runtime, not at compile
6584 time. This means that the following code will print 42:
6585
6586 i = 10
6587 def f():
6588 print(i)
6589 i = 42
6590 f()
6591
6592 The "eval()" and "exec()" functions do not have access to the full
6593 environment for resolving names. Names may be resolved in the local
6594 and global namespaces of the caller. Free variables are not resolved
6595 in the nearest enclosing namespace, but in the global namespace. [1]
6596 The "exec()" and "eval()" functions have optional arguments to
6597 override the global and local namespace. If only one namespace is
6598 specified, it is used for both.
6599 ''',
6600 'nonlocal': r'''The "nonlocal" statement
6601 ************************
6602
6603 nonlocal_stmt ::= "nonlocal" identifier ("," identifier)*
6604
6605 When the definition of a function or class is nested (enclosed) within
6606 the definitions of other functions, its nonlocal scopes are the local
6607 scopes of the enclosing functions. The "nonlocal" statement causes the
6608 listed identifiers to refer to names previously bound in nonlocal
6609 scopes. It allows encapsulated code to rebind such nonlocal
6610 identifiers. If a name is bound in more than one nonlocal scope, the
6611 nearest binding is used. If a name is not bound in any nonlocal scope,
6612 or if there is no nonlocal scope, a "SyntaxError" is raised.
6613
6614 The "nonlocal" statement applies to the entire scope of a function or
6615 class body. A "SyntaxError" is raised if a variable is used or
6616 assigned to prior to its nonlocal declaration in the scope.
6617
6618 See also:
6619
6620 **PEP 3104** - Access to Names in Outer Scopes
6621 The specification for the "nonlocal" statement.
6622
6623 **Programmer’s note:** "nonlocal" is a directive to the parser and
6624 applies only to code parsed along with it. See the note for the
6625 "global" statement.
6626 ''',
6627 'numbers': r'''Numeric literals
6628 ****************
6629
6630 There are three types of numeric literals: integers, floating-point
6631 numbers, and imaginary numbers. There are no complex literals
6632 (complex numbers can be formed by adding a real number and an
6633 imaginary number).
6634
6635 Note that numeric literals do not include a sign; a phrase like "-1"
6636 is actually an expression composed of the unary operator ‘"-"’ and the
6637 literal "1".
6638 ''',
6639 'numeric-types': r'''Emulating numeric types
6640 ***********************
6641
6642 The following methods can be defined to emulate numeric objects.
6643 Methods corresponding to operations that are not supported by the
6644 particular kind of number implemented (e.g., bitwise operations for
6645 non-integral numbers) should be left undefined.
6646
6647 object.__add__(self, other)
6648 object.__sub__(self, other)
6649 object.__mul__(self, other)
6650 object.__matmul__(self, other)
6651 object.__truediv__(self, other)
6652 object.__floordiv__(self, other)
6653 object.__mod__(self, other)
6654 object.__divmod__(self, other)
6655 object.__pow__(self, other[, modulo])
6656 object.__lshift__(self, other)
6657 object.__rshift__(self, other)
6658 object.__and__(self, other)
6659 object.__xor__(self, other)
6660 object.__or__(self, other)
6661
6662 These methods are called to implement the binary arithmetic
6663 operations ("+", "-", "*", "@", "/", "//", "%", "divmod()",
6664 "pow()", "**", "<<", ">>", "&", "^", "|"). For instance, to
6665 evaluate the expression "x + y", where *x* is an instance of a
6666 class that has an "__add__()" method, "type(x).__add__(x, y)" is
6667 called. The "__divmod__()" method should be the equivalent to
6668 using "__floordiv__()" and "__mod__()"; it should not be related to
6669 "__truediv__()". Note that "__pow__()" should be defined to accept
6670 an optional third argument if the ternary version of the built-in
6671 "pow()" function is to be supported.
6672
6673 If one of those methods does not support the operation with the
6674 supplied arguments, it should return "NotImplemented".
6675
6676 object.__radd__(self, other)
6677 object.__rsub__(self, other)
6678 object.__rmul__(self, other)
6679 object.__rmatmul__(self, other)
6680 object.__rtruediv__(self, other)
6681 object.__rfloordiv__(self, other)
6682 object.__rmod__(self, other)
6683 object.__rdivmod__(self, other)
6684 object.__rpow__(self, other[, modulo])
6685 object.__rlshift__(self, other)
6686 object.__rrshift__(self, other)
6687 object.__rand__(self, other)
6688 object.__rxor__(self, other)
6689 object.__ror__(self, other)
6690
6691 These methods are called to implement the binary arithmetic
6692 operations ("+", "-", "*", "@", "/", "//", "%", "divmod()",
6693 "pow()", "**", "<<", ">>", "&", "^", "|") with reflected (swapped)
6694 operands. These functions are only called if the left operand does
6695 not support the corresponding operation [3] and the operands are of
6696 different types. [4] For instance, to evaluate the expression "x -
6697 y", where *y* is an instance of a class that has an "__rsub__()"
6698 method, "type(y).__rsub__(y, x)" is called if "type(x).__sub__(x,
6699 y)" returns "NotImplemented".
6700
6701 Note that ternary "pow()" will not try calling "__rpow__()" (the
6702 coercion rules would become too complicated).
6703
6704 Note:
6705
6706 If the right operand’s type is a subclass of the left operand’s
6707 type and that subclass provides a different implementation of the
6708 reflected method for the operation, this method will be called
6709 before the left operand’s non-reflected method. This behavior
6710 allows subclasses to override their ancestors’ operations.
6711
6712 object.__iadd__(self, other)
6713 object.__isub__(self, other)
6714 object.__imul__(self, other)
6715 object.__imatmul__(self, other)
6716 object.__itruediv__(self, other)
6717 object.__ifloordiv__(self, other)
6718 object.__imod__(self, other)
6719 object.__ipow__(self, other[, modulo])
6720 object.__ilshift__(self, other)
6721 object.__irshift__(self, other)
6722 object.__iand__(self, other)
6723 object.__ixor__(self, other)
6724 object.__ior__(self, other)
6725
6726 These methods are called to implement the augmented arithmetic
6727 assignments ("+=", "-=", "*=", "@=", "/=", "//=", "%=", "**=",
6728 "<<=", ">>=", "&=", "^=", "|="). These methods should attempt to
6729 do the operation in-place (modifying *self*) and return the result
6730 (which could be, but does not have to be, *self*). If a specific
6731 method is not defined, or if that method returns "NotImplemented",
6732 the augmented assignment falls back to the normal methods. For
6733 instance, if *x* is an instance of a class with an "__iadd__()"
6734 method, "x += y" is equivalent to "x = x.__iadd__(y)" . If
6735 "__iadd__()" does not exist, or if "x.__iadd__(y)" returns
6736 "NotImplemented", "x.__add__(y)" and "y.__radd__(x)" are
6737 considered, as with the evaluation of "x + y". In certain
6738 situations, augmented assignment can result in unexpected errors
6739 (see Why does a_tuple[i] += [‘item’] raise an exception when the
6740 addition works?), but this behavior is in fact part of the data
6741 model.
6742
6743 object.__neg__(self)
6744 object.__pos__(self)
6745 object.__abs__(self)
6746 object.__invert__(self)
6747
6748 Called to implement the unary arithmetic operations ("-", "+",
6749 "abs()" and "~").
6750
6751 object.__complex__(self)
6752 object.__int__(self)
6753 object.__float__(self)
6754
6755 Called to implement the built-in functions "complex()", "int()" and
6756 "float()". Should return a value of the appropriate type.
6757
6758 object.__index__(self)
6759
6760 Called to implement "operator.index()", and whenever Python needs
6761 to losslessly convert the numeric object to an integer object (such
6762 as in slicing, or in the built-in "bin()", "hex()" and "oct()"
6763 functions). Presence of this method indicates that the numeric
6764 object is an integer type. Must return an integer.
6765
6766 If "__int__()", "__float__()" and "__complex__()" are not defined
6767 then corresponding built-in functions "int()", "float()" and
6768 "complex()" fall back to "__index__()".
6769
6770 object.__round__(self[, ndigits])
6771 object.__trunc__(self)
6772 object.__floor__(self)
6773 object.__ceil__(self)
6774
6775 Called to implement the built-in function "round()" and "math"
6776 functions "trunc()", "floor()" and "ceil()". Unless *ndigits* is
6777 passed to "__round__()" all these methods should return the value
6778 of the object truncated to an "Integral" (typically an "int").
6779
6780 The built-in function "int()" falls back to "__trunc__()" if
6781 neither "__int__()" nor "__index__()" is defined.
6782
6783 Changed in version 3.11: The delegation of "int()" to "__trunc__()"
6784 is deprecated.
6785 ''',
6786 'objects': r'''Objects, values and types
6787 *************************
6788
6789 *Objects* are Python’s abstraction for data. All data in a Python
6790 program is represented by objects or by relations between objects.
6791 Even code is represented by objects.
6792
6793 Every object has an identity, a type and a value. An object’s
6794 *identity* never changes once it has been created; you may think of it
6795 as the object’s address in memory. The "is" operator compares the
6796 identity of two objects; the "id()" function returns an integer
6797 representing its identity.
6798
6799 **CPython implementation detail:** For CPython, "id(x)" is the memory
6800 address where "x" is stored.
6801
6802 An object’s type determines the operations that the object supports
6803 (e.g., “does it have a length?”) and also defines the possible values
6804 for objects of that type. The "type()" function returns an object’s
6805 type (which is an object itself). Like its identity, an object’s
6806 *type* is also unchangeable. [1]
6807
6808 The *value* of some objects can change. Objects whose value can
6809 change are said to be *mutable*; objects whose value is unchangeable
6810 once they are created are called *immutable*. (The value of an
6811 immutable container object that contains a reference to a mutable
6812 object can change when the latter’s value is changed; however the
6813 container is still considered immutable, because the collection of
6814 objects it contains cannot be changed. So, immutability is not
6815 strictly the same as having an unchangeable value, it is more subtle.)
6816 An object’s mutability is determined by its type; for instance,
6817 numbers, strings and tuples are immutable, while dictionaries and
6818 lists are mutable.
6819
6820 Objects are never explicitly destroyed; however, when they become
6821 unreachable they may be garbage-collected. An implementation is
6822 allowed to postpone garbage collection or omit it altogether — it is a
6823 matter of implementation quality how garbage collection is
6824 implemented, as long as no objects are collected that are still
6825 reachable.
6826
6827 **CPython implementation detail:** CPython currently uses a reference-
6828 counting scheme with (optional) delayed detection of cyclically linked
6829 garbage, which collects most objects as soon as they become
6830 unreachable, but is not guaranteed to collect garbage containing
6831 circular references. See the documentation of the "gc" module for
6832 information on controlling the collection of cyclic garbage. Other
6833 implementations act differently and CPython may change. Do not depend
6834 on immediate finalization of objects when they become unreachable (so
6835 you should always close files explicitly).
6836
6837 Note that the use of the implementation’s tracing or debugging
6838 facilities may keep objects alive that would normally be collectable.
6839 Also note that catching an exception with a "try"…"except" statement
6840 may keep objects alive.
6841
6842 Some objects contain references to “external” resources such as open
6843 files or windows. It is understood that these resources are freed
6844 when the object is garbage-collected, but since garbage collection is
6845 not guaranteed to happen, such objects also provide an explicit way to
6846 release the external resource, usually a "close()" method. Programs
6847 are strongly recommended to explicitly close such objects. The
6848 "try"…"finally" statement and the "with" statement provide convenient
6849 ways to do this.
6850
6851 Some objects contain references to other objects; these are called
6852 *containers*. Examples of containers are tuples, lists and
6853 dictionaries. The references are part of a container’s value. In
6854 most cases, when we talk about the value of a container, we imply the
6855 values, not the identities of the contained objects; however, when we
6856 talk about the mutability of a container, only the identities of the
6857 immediately contained objects are implied. So, if an immutable
6858 container (like a tuple) contains a reference to a mutable object, its
6859 value changes if that mutable object is changed.
6860
6861 Types affect almost all aspects of object behavior. Even the
6862 importance of object identity is affected in some sense: for immutable
6863 types, operations that compute new values may actually return a
6864 reference to any existing object with the same type and value, while
6865 for mutable objects this is not allowed. For example, after "a = 1; b
6866 = 1", *a* and *b* may or may not refer to the same object with the
6867 value one, depending on the implementation. This is because "int" is
6868 an immutable type, so the reference to "1" can be reused. This
6869 behaviour depends on the implementation used, so should not be relied
6870 upon, but is something to be aware of when making use of object
6871 identity tests. However, after "c = []; d = []", *c* and *d* are
6872 guaranteed to refer to two different, unique, newly created empty
6873 lists. (Note that "e = f = []" assigns the *same* object to both *e*
6874 and *f*.)
6875 ''',
6876 'operator-summary': r'''Operator precedence
6877 *******************
6878
6879 The following table summarizes the operator precedence in Python, from
6880 highest precedence (most binding) to lowest precedence (least
6881 binding). Operators in the same box have the same precedence. Unless
6882 the syntax is explicitly given, operators are binary. Operators in
6883 the same box group left to right (except for exponentiation and
6884 conditional expressions, which group from right to left).
6885
6886 Note that comparisons, membership tests, and identity tests, all have
6887 the same precedence and have a left-to-right chaining feature as
6888 described in the Comparisons section.
6889
6890 +-------------------------------------------------+---------------------------------------+
6891 | Operator | Description |
6892 |=================================================|=======================================|
6893 | "(expressions...)", "[expressions...]", "{key: | Binding or parenthesized expression, |
6894 | value...}", "{expressions...}" | list display, dictionary display, set |
6895 | | display |
6896 +-------------------------------------------------+---------------------------------------+
6897 | "x[index]", "x[index:index]", | Subscription, slicing, call, |
6898 | "x(arguments...)", "x.attribute" | attribute reference |
6899 +-------------------------------------------------+---------------------------------------+
6900 | "await x" | Await expression |
6901 +-------------------------------------------------+---------------------------------------+
6902 | "**" | Exponentiation [5] |
6903 +-------------------------------------------------+---------------------------------------+
6904 | "+x", "-x", "~x" | Positive, negative, bitwise NOT |
6905 +-------------------------------------------------+---------------------------------------+
6906 | "*", "@", "/", "//", "%" | Multiplication, matrix |
6907 | | multiplication, division, floor |
6908 | | division, remainder [6] |
6909 +-------------------------------------------------+---------------------------------------+
6910 | "+", "-" | Addition and subtraction |
6911 +-------------------------------------------------+---------------------------------------+
6912 | "<<", ">>" | Shifts |
6913 +-------------------------------------------------+---------------------------------------+
6914 | "&" | Bitwise AND |
6915 +-------------------------------------------------+---------------------------------------+
6916 | "^" | Bitwise XOR |
6917 +-------------------------------------------------+---------------------------------------+
6918 | "|" | Bitwise OR |
6919 +-------------------------------------------------+---------------------------------------+
6920 | "in", "not in", "is", "is not", "<", "<=", ">", | Comparisons, including membership |
6921 | ">=", "!=", "==" | tests and identity tests |
6922 +-------------------------------------------------+---------------------------------------+
6923 | "not x" | Boolean NOT |
6924 +-------------------------------------------------+---------------------------------------+
6925 | "and" | Boolean AND |
6926 +-------------------------------------------------+---------------------------------------+
6927 | "or" | Boolean OR |
6928 +-------------------------------------------------+---------------------------------------+
6929 | "if" – "else" | Conditional expression |
6930 +-------------------------------------------------+---------------------------------------+
6931 | "lambda" | Lambda expression |
6932 +-------------------------------------------------+---------------------------------------+
6933 | ":=" | Assignment expression |
6934 +-------------------------------------------------+---------------------------------------+
6935
6936 -[ Footnotes ]-
6937
6938 [1] While "abs(x%y) < abs(y)" is true mathematically, for floats it
6939 may not be true numerically due to roundoff. For example, and
6940 assuming a platform on which a Python float is an IEEE 754 double-
6941 precision number, in order that "-1e-100 % 1e100" have the same
6942 sign as "1e100", the computed result is "-1e-100 + 1e100", which
6943 is numerically exactly equal to "1e100". The function
6944 "math.fmod()" returns a result whose sign matches the sign of the
6945 first argument instead, and so returns "-1e-100" in this case.
6946 Which approach is more appropriate depends on the application.
6947
6948 [2] If x is very close to an exact integer multiple of y, it’s
6949 possible for "x//y" to be one larger than "(x-x%y)//y" due to
6950 rounding. In such cases, Python returns the latter result, in
6951 order to preserve that "divmod(x,y)[0] * y + x % y" be very close
6952 to "x".
6953
6954 [3] The Unicode standard distinguishes between *code points* (e.g.
6955 U+0041) and *abstract characters* (e.g. “LATIN CAPITAL LETTER A”).
6956 While most abstract characters in Unicode are only represented
6957 using one code point, there is a number of abstract characters
6958 that can in addition be represented using a sequence of more than
6959 one code point. For example, the abstract character “LATIN
6960 CAPITAL LETTER C WITH CEDILLA” can be represented as a single
6961 *precomposed character* at code position U+00C7, or as a sequence
6962 of a *base character* at code position U+0043 (LATIN CAPITAL
6963 LETTER C), followed by a *combining character* at code position
6964 U+0327 (COMBINING CEDILLA).
6965
6966 The comparison operators on strings compare at the level of
6967 Unicode code points. This may be counter-intuitive to humans. For
6968 example, ""\u00C7" == "\u0043\u0327"" is "False", even though both
6969 strings represent the same abstract character “LATIN CAPITAL
6970 LETTER C WITH CEDILLA”.
6971
6972 To compare strings at the level of abstract characters (that is,
6973 in a way intuitive to humans), use "unicodedata.normalize()".
6974
6975 [4] Due to automatic garbage-collection, free lists, and the dynamic
6976 nature of descriptors, you may notice seemingly unusual behaviour
6977 in certain uses of the "is" operator, like those involving
6978 comparisons between instance methods, or constants. Check their
6979 documentation for more info.
6980
6981 [5] The power operator "**" binds less tightly than an arithmetic or
6982 bitwise unary operator on its right, that is, "2**-1" is "0.5".
6983
6984 [6] The "%" operator is also used for string formatting; the same
6985 precedence applies.
6986 ''',
6987 'pass': r'''The "pass" statement
6988 ********************
6989
6990 pass_stmt ::= "pass"
6991
6992 "pass" is a null operation — when it is executed, nothing happens. It
6993 is useful as a placeholder when a statement is required syntactically,
6994 but no code needs to be executed, for example:
6995
6996 def f(arg): pass # a function that does nothing (yet)
6997
6998 class C: pass # a class with no methods (yet)
6999 ''',
7000 'power': r'''The power operator
7001 ******************
7002
7003 The power operator binds more tightly than unary operators on its
7004 left; it binds less tightly than unary operators on its right. The
7005 syntax is:
7006
7007 power ::= (await_expr | primary) ["**" u_expr]
7008
7009 Thus, in an unparenthesized sequence of power and unary operators, the
7010 operators are evaluated from right to left (this does not constrain
7011 the evaluation order for the operands): "-1**2" results in "-1".
7012
7013 The power operator has the same semantics as the built-in "pow()"
7014 function, when called with two arguments: it yields its left argument
7015 raised to the power of its right argument. The numeric arguments are
7016 first converted to a common type, and the result is of that type.
7017
7018 For int operands, the result has the same type as the operands unless
7019 the second argument is negative; in that case, all arguments are
7020 converted to float and a float result is delivered. For example,
7021 "10**2" returns "100", but "10**-2" returns "0.01".
7022
7023 Raising "0.0" to a negative power results in a "ZeroDivisionError".
7024 Raising a negative number to a fractional power results in a "complex"
7025 number. (In earlier versions it raised a "ValueError".)
7026
7027 This operation can be customized using the special "__pow__()" and
7028 "__rpow__()" methods.
7029 ''',
7030 'raise': r'''The "raise" statement
7031 *********************
7032
7033 raise_stmt ::= "raise" [expression ["from" expression]]
7034
7035 If no expressions are present, "raise" re-raises the exception that is
7036 currently being handled, which is also known as the *active
7037 exception*. If there isn’t currently an active exception, a
7038 "RuntimeError" exception is raised indicating that this is an error.
7039
7040 Otherwise, "raise" evaluates the first expression as the exception
7041 object. It must be either a subclass or an instance of
7042 "BaseException". If it is a class, the exception instance will be
7043 obtained when needed by instantiating the class with no arguments.
7044
7045 The *type* of the exception is the exception instance’s class, the
7046 *value* is the instance itself.
7047
7048 A traceback object is normally created automatically when an exception
7049 is raised and attached to it as the "__traceback__" attribute. You can
7050 create an exception and set your own traceback in one step using the
7051 "with_traceback()" exception method (which returns the same exception
7052 instance, with its traceback set to its argument), like so:
7053
7054 raise Exception("foo occurred").with_traceback(tracebackobj)
7055
7056 The "from" clause is used for exception chaining: if given, the second
7057 *expression* must be another exception class or instance. If the
7058 second expression is an exception instance, it will be attached to the
7059 raised exception as the "__cause__" attribute (which is writable). If
7060 the expression is an exception class, the class will be instantiated
7061 and the resulting exception instance will be attached to the raised
7062 exception as the "__cause__" attribute. If the raised exception is not
7063 handled, both exceptions will be printed:
7064
7065 >>> try:
7066 ... print(1 / 0)
7067 ... except Exception as exc:
7068 ... raise RuntimeError("Something bad happened") from exc
7069 ...
7070 Traceback (most recent call last):
7071 File "<stdin>", line 2, in <module>
7072 print(1 / 0)
7073 ~~^~~
7074 ZeroDivisionError: division by zero
7075
7076 The above exception was the direct cause of the following exception:
7077
7078 Traceback (most recent call last):
7079 File "<stdin>", line 4, in <module>
7080 raise RuntimeError("Something bad happened") from exc
7081 RuntimeError: Something bad happened
7082
7083 A similar mechanism works implicitly if a new exception is raised when
7084 an exception is already being handled. An exception may be handled
7085 when an "except" or "finally" clause, or a "with" statement, is used.
7086 The previous exception is then attached as the new exception’s
7087 "__context__" attribute:
7088
7089 >>> try:
7090 ... print(1 / 0)
7091 ... except:
7092 ... raise RuntimeError("Something bad happened")
7093 ...
7094 Traceback (most recent call last):
7095 File "<stdin>", line 2, in <module>
7096 print(1 / 0)
7097 ~~^~~
7098 ZeroDivisionError: division by zero
7099
7100 During handling of the above exception, another exception occurred:
7101
7102 Traceback (most recent call last):
7103 File "<stdin>", line 4, in <module>
7104 raise RuntimeError("Something bad happened")
7105 RuntimeError: Something bad happened
7106
7107 Exception chaining can be explicitly suppressed by specifying "None"
7108 in the "from" clause:
7109
7110 >>> try:
7111 ... print(1 / 0)
7112 ... except:
7113 ... raise RuntimeError("Something bad happened") from None
7114 ...
7115 Traceback (most recent call last):
7116 File "<stdin>", line 4, in <module>
7117 RuntimeError: Something bad happened
7118
7119 Additional information on exceptions can be found in section
7120 Exceptions, and information about handling exceptions is in section
7121 The try statement.
7122
7123 Changed in version 3.3: "None" is now permitted as "Y" in "raise X
7124 from Y".Added the "__suppress_context__" attribute to suppress
7125 automatic display of the exception context.
7126
7127 Changed in version 3.11: If the traceback of the active exception is
7128 modified in an "except" clause, a subsequent "raise" statement re-
7129 raises the exception with the modified traceback. Previously, the
7130 exception was re-raised with the traceback it had when it was caught.
7131 ''',
7132 'return': r'''The "return" statement
7133 **********************
7134
7135 return_stmt ::= "return" [expression_list]
7136
7137 "return" may only occur syntactically nested in a function definition,
7138 not within a nested class definition.
7139
7140 If an expression list is present, it is evaluated, else "None" is
7141 substituted.
7142
7143 "return" leaves the current function call with the expression list (or
7144 "None") as return value.
7145
7146 When "return" passes control out of a "try" statement with a "finally"
7147 clause, that "finally" clause is executed before really leaving the
7148 function.
7149
7150 In a generator function, the "return" statement indicates that the
7151 generator is done and will cause "StopIteration" to be raised. The
7152 returned value (if any) is used as an argument to construct
7153 "StopIteration" and becomes the "StopIteration.value" attribute.
7154
7155 In an asynchronous generator function, an empty "return" statement
7156 indicates that the asynchronous generator is done and will cause
7157 "StopAsyncIteration" to be raised. A non-empty "return" statement is
7158 a syntax error in an asynchronous generator function.
7159 ''',
7160 'sequence-types': r'''Emulating container types
7161 *************************
7162
7163 The following methods can be defined to implement container objects.
7164 None of them are provided by the "object" class itself. Containers
7165 usually are *sequences* (such as "lists" or "tuples") or *mappings*
7166 (like *dictionaries*), but can represent other containers as well.
7167 The first set of methods is used either to emulate a sequence or to
7168 emulate a mapping; the difference is that for a sequence, the
7169 allowable keys should be the integers *k* for which "0 <= k < N" where
7170 *N* is the length of the sequence, or "slice" objects, which define a
7171 range of items. It is also recommended that mappings provide the
7172 methods "keys()", "values()", "items()", "get()", "clear()",
7173 "setdefault()", "pop()", "popitem()", "copy()", and "update()"
7174 behaving similar to those for Python’s standard "dictionary" objects.
7175 The "collections.abc" module provides a "MutableMapping" *abstract
7176 base class* to help create those methods from a base set of
7177 "__getitem__()", "__setitem__()", "__delitem__()", and "keys()".
7178
7179 Mutable sequences should provide methods "append()", "clear()",
7180 "count()", "extend()", "index()", "insert()", "pop()", "remove()", and
7181 "reverse()", like Python standard "list" objects. Finally, sequence
7182 types should implement addition (meaning concatenation) and
7183 multiplication (meaning repetition) by defining the methods
7184 "__add__()", "__radd__()", "__iadd__()", "__mul__()", "__rmul__()" and
7185 "__imul__()" described below; they should not define other numerical
7186 operators.
7187
7188 It is recommended that both mappings and sequences implement the
7189 "__contains__()" method to allow efficient use of the "in" operator;
7190 for mappings, "in" should search the mapping’s keys; for sequences, it
7191 should search through the values. It is further recommended that both
7192 mappings and sequences implement the "__iter__()" method to allow
7193 efficient iteration through the container; for mappings, "__iter__()"
7194 should iterate through the object’s keys; for sequences, it should
7195 iterate through the values.
7196
7197 object.__len__(self)
7198
7199 Called to implement the built-in function "len()". Should return
7200 the length of the object, an integer ">=" 0. Also, an object that
7201 doesn’t define a "__bool__()" method and whose "__len__()" method
7202 returns zero is considered to be false in a Boolean context.
7203
7204 **CPython implementation detail:** In CPython, the length is
7205 required to be at most "sys.maxsize". If the length is larger than
7206 "sys.maxsize" some features (such as "len()") may raise
7207 "OverflowError". To prevent raising "OverflowError" by truth value
7208 testing, an object must define a "__bool__()" method.
7209
7210 object.__length_hint__(self)
7211
7212 Called to implement "operator.length_hint()". Should return an
7213 estimated length for the object (which may be greater or less than
7214 the actual length). The length must be an integer ">=" 0. The
7215 return value may also be "NotImplemented", which is treated the
7216 same as if the "__length_hint__" method didn’t exist at all. This
7217 method is purely an optimization and is never required for
7218 correctness.
7219
7220 Added in version 3.4.
7221
7222 Note:
7223
7224 Slicing is done exclusively with the following three methods. A
7225 call like
7226
7227 a[1:2] = b
7228
7229 is translated to
7230
7231 a[slice(1, 2, None)] = b
7232
7233 and so forth. Missing slice items are always filled in with "None".
7234
7235 object.__getitem__(self, key)
7236
7237 Called to implement evaluation of "self[key]". For *sequence*
7238 types, the accepted keys should be integers. Optionally, they may
7239 support "slice" objects as well. Negative index support is also
7240 optional. If *key* is of an inappropriate type, "TypeError" may be
7241 raised; if *key* is a value outside the set of indexes for the
7242 sequence (after any special interpretation of negative values),
7243 "IndexError" should be raised. For *mapping* types, if *key* is
7244 missing (not in the container), "KeyError" should be raised.
7245
7246 Note:
7247
7248 "for" loops expect that an "IndexError" will be raised for
7249 illegal indexes to allow proper detection of the end of the
7250 sequence.
7251
7252 Note:
7253
7254 When subscripting a *class*, the special class method
7255 "__class_getitem__()" may be called instead of "__getitem__()".
7256 See __class_getitem__ versus __getitem__ for more details.
7257
7258 object.__setitem__(self, key, value)
7259
7260 Called to implement assignment to "self[key]". Same note as for
7261 "__getitem__()". This should only be implemented for mappings if
7262 the objects support changes to the values for keys, or if new keys
7263 can be added, or for sequences if elements can be replaced. The
7264 same exceptions should be raised for improper *key* values as for
7265 the "__getitem__()" method.
7266
7267 object.__delitem__(self, key)
7268
7269 Called to implement deletion of "self[key]". Same note as for
7270 "__getitem__()". This should only be implemented for mappings if
7271 the objects support removal of keys, or for sequences if elements
7272 can be removed from the sequence. The same exceptions should be
7273 raised for improper *key* values as for the "__getitem__()" method.
7274
7275 object.__missing__(self, key)
7276
7277 Called by "dict"."__getitem__()" to implement "self[key]" for dict
7278 subclasses when key is not in the dictionary.
7279
7280 object.__iter__(self)
7281
7282 This method is called when an *iterator* is required for a
7283 container. This method should return a new iterator object that can
7284 iterate over all the objects in the container. For mappings, it
7285 should iterate over the keys of the container.
7286
7287 object.__reversed__(self)
7288
7289 Called (if present) by the "reversed()" built-in to implement
7290 reverse iteration. It should return a new iterator object that
7291 iterates over all the objects in the container in reverse order.
7292
7293 If the "__reversed__()" method is not provided, the "reversed()"
7294 built-in will fall back to using the sequence protocol ("__len__()"
7295 and "__getitem__()"). Objects that support the sequence protocol
7296 should only provide "__reversed__()" if they can provide an
7297 implementation that is more efficient than the one provided by
7298 "reversed()".
7299
7300 The membership test operators ("in" and "not in") are normally
7301 implemented as an iteration through a container. However, container
7302 objects can supply the following special method with a more efficient
7303 implementation, which also does not require the object be iterable.
7304
7305 object.__contains__(self, item)
7306
7307 Called to implement membership test operators. Should return true
7308 if *item* is in *self*, false otherwise. For mapping objects, this
7309 should consider the keys of the mapping rather than the values or
7310 the key-item pairs.
7311
7312 For objects that don’t define "__contains__()", the membership test
7313 first tries iteration via "__iter__()", then the old sequence
7314 iteration protocol via "__getitem__()", see this section in the
7315 language reference.
7316 ''',
7317 'shifting': r'''Shifting operations
7318 *******************
7319
7320 The shifting operations have lower priority than the arithmetic
7321 operations:
7322
7323 shift_expr ::= a_expr | shift_expr ("<<" | ">>") a_expr
7324
7325 These operators accept integers as arguments. They shift the first
7326 argument to the left or right by the number of bits given by the
7327 second argument.
7328
7329 The left shift operation can be customized using the special
7330 "__lshift__()" and "__rlshift__()" methods. The right shift operation
7331 can be customized using the special "__rshift__()" and "__rrshift__()"
7332 methods.
7333
7334 A right shift by *n* bits is defined as floor division by "pow(2,n)".
7335 A left shift by *n* bits is defined as multiplication with "pow(2,n)".
7336 ''',
7337 'slicings': r'''Slicings
7338 ********
7339
7340 A slicing selects a range of items in a sequence object (e.g., a
7341 string, tuple or list). Slicings may be used as expressions or as
7342 targets in assignment or "del" statements. The syntax for a slicing:
7343
7344 slicing ::= primary "[" slice_list "]"
7345 slice_list ::= slice_item ("," slice_item)* [","]
7346 slice_item ::= expression | proper_slice
7347 proper_slice ::= [lower_bound] ":" [upper_bound] [ ":" [stride] ]
7348 lower_bound ::= expression
7349 upper_bound ::= expression
7350 stride ::= expression
7351
7352 There is ambiguity in the formal syntax here: anything that looks like
7353 an expression list also looks like a slice list, so any subscription
7354 can be interpreted as a slicing. Rather than further complicating the
7355 syntax, this is disambiguated by defining that in this case the
7356 interpretation as a subscription takes priority over the
7357 interpretation as a slicing (this is the case if the slice list
7358 contains no proper slice).
7359
7360 The semantics for a slicing are as follows. The primary is indexed
7361 (using the same "__getitem__()" method as normal subscription) with a
7362 key that is constructed from the slice list, as follows. If the slice
7363 list contains at least one comma, the key is a tuple containing the
7364 conversion of the slice items; otherwise, the conversion of the lone
7365 slice item is the key. The conversion of a slice item that is an
7366 expression is that expression. The conversion of a proper slice is a
7367 slice object (see section The standard type hierarchy) whose "start",
7368 "stop" and "step" attributes are the values of the expressions given
7369 as lower bound, upper bound and stride, respectively, substituting
7370 "None" for missing expressions.
7371 ''',
7372 'specialattrs': r'''Special Attributes
7373 ******************
7374
7375 The implementation adds a few special read-only attributes to several
7376 object types, where they are relevant. Some of these are not reported
7377 by the "dir()" built-in function.
7378
7379 definition.__name__
7380
7381 The name of the class, function, method, descriptor, or generator
7382 instance.
7383
7384 definition.__qualname__
7385
7386 The *qualified name* of the class, function, method, descriptor, or
7387 generator instance.
7388
7389 Added in version 3.3.
7390
7391 definition.__module__
7392
7393 The name of the module in which a class or function was defined.
7394
7395 definition.__doc__
7396
7397 The documentation string of a class or function, or "None" if
7398 undefined.
7399
7400 definition.__type_params__
7401
7402 The type parameters of generic classes, functions, and type
7403 aliases. For classes and functions that are not generic, this will
7404 be an empty tuple.
7405
7406 Added in version 3.12.
7407 ''',
7408 'specialnames': r'''Special method names
7409 ********************
7410
7411 A class can implement certain operations that are invoked by special
7412 syntax (such as arithmetic operations or subscripting and slicing) by
7413 defining methods with special names. This is Python’s approach to
7414 *operator overloading*, allowing classes to define their own behavior
7415 with respect to language operators. For instance, if a class defines
7416 a method named "__getitem__()", and "x" is an instance of this class,
7417 then "x[i]" is roughly equivalent to "type(x).__getitem__(x, i)".
7418 Except where mentioned, attempts to execute an operation raise an
7419 exception when no appropriate method is defined (typically
7420 "AttributeError" or "TypeError").
7421
7422 Setting a special method to "None" indicates that the corresponding
7423 operation is not available. For example, if a class sets "__iter__()"
7424 to "None", the class is not iterable, so calling "iter()" on its
7425 instances will raise a "TypeError" (without falling back to
7426 "__getitem__()"). [2]
7427
7428 When implementing a class that emulates any built-in type, it is
7429 important that the emulation only be implemented to the degree that it
7430 makes sense for the object being modelled. For example, some
7431 sequences may work well with retrieval of individual elements, but
7432 extracting a slice may not make sense. (One example of this is the
7433 "NodeList" interface in the W3C’s Document Object Model.)
7434
7435
7436 Basic customization
7437 ===================
7438
7439 object.__new__(cls[, ...])
7440
7441 Called to create a new instance of class *cls*. "__new__()" is a
7442 static method (special-cased so you need not declare it as such)
7443 that takes the class of which an instance was requested as its
7444 first argument. The remaining arguments are those passed to the
7445 object constructor expression (the call to the class). The return
7446 value of "__new__()" should be the new object instance (usually an
7447 instance of *cls*).
7448
7449 Typical implementations create a new instance of the class by
7450 invoking the superclass’s "__new__()" method using
7451 "super().__new__(cls[, ...])" with appropriate arguments and then
7452 modifying the newly created instance as necessary before returning
7453 it.
7454
7455 If "__new__()" is invoked during object construction and it returns
7456 an instance of *cls*, then the new instance’s "__init__()" method
7457 will be invoked like "__init__(self[, ...])", where *self* is the
7458 new instance and the remaining arguments are the same as were
7459 passed to the object constructor.
7460
7461 If "__new__()" does not return an instance of *cls*, then the new
7462 instance’s "__init__()" method will not be invoked.
7463
7464 "__new__()" is intended mainly to allow subclasses of immutable
7465 types (like int, str, or tuple) to customize instance creation. It
7466 is also commonly overridden in custom metaclasses in order to
7467 customize class creation.
7468
7469 object.__init__(self[, ...])
7470
7471 Called after the instance has been created (by "__new__()"), but
7472 before it is returned to the caller. The arguments are those
7473 passed to the class constructor expression. If a base class has an
7474 "__init__()" method, the derived class’s "__init__()" method, if
7475 any, must explicitly call it to ensure proper initialization of the
7476 base class part of the instance; for example:
7477 "super().__init__([args...])".
7478
7479 Because "__new__()" and "__init__()" work together in constructing
7480 objects ("__new__()" to create it, and "__init__()" to customize
7481 it), no non-"None" value may be returned by "__init__()"; doing so
7482 will cause a "TypeError" to be raised at runtime.
7483
7484 object.__del__(self)
7485
7486 Called when the instance is about to be destroyed. This is also
7487 called a finalizer or (improperly) a destructor. If a base class
7488 has a "__del__()" method, the derived class’s "__del__()" method,
7489 if any, must explicitly call it to ensure proper deletion of the
7490 base class part of the instance.
7491
7492 It is possible (though not recommended!) for the "__del__()" method
7493 to postpone destruction of the instance by creating a new reference
7494 to it. This is called object *resurrection*. It is
7495 implementation-dependent whether "__del__()" is called a second
7496 time when a resurrected object is about to be destroyed; the
7497 current *CPython* implementation only calls it once.
7498
7499 It is not guaranteed that "__del__()" methods are called for
7500 objects that still exist when the interpreter exits.
7501 "weakref.finalize" provides a straightforward way to register a
7502 cleanup function to be called when an object is garbage collected.
7503
7504 Note:
7505
7506 "del x" doesn’t directly call "x.__del__()" — the former
7507 decrements the reference count for "x" by one, and the latter is
7508 only called when "x"’s reference count reaches zero.
7509
7510 **CPython implementation detail:** It is possible for a reference
7511 cycle to prevent the reference count of an object from going to
7512 zero. In this case, the cycle will be later detected and deleted
7513 by the *cyclic garbage collector*. A common cause of reference
7514 cycles is when an exception has been caught in a local variable.
7515 The frame’s locals then reference the exception, which references
7516 its own traceback, which references the locals of all frames caught
7517 in the traceback.
7518
7519 See also: Documentation for the "gc" module.
7520
7521 Warning:
7522
7523 Due to the precarious circumstances under which "__del__()"
7524 methods are invoked, exceptions that occur during their execution
7525 are ignored, and a warning is printed to "sys.stderr" instead.
7526 In particular:
7527
7528 * "__del__()" can be invoked when arbitrary code is being
7529 executed, including from any arbitrary thread. If "__del__()"
7530 needs to take a lock or invoke any other blocking resource, it
7531 may deadlock as the resource may already be taken by the code
7532 that gets interrupted to execute "__del__()".
7533
7534 * "__del__()" can be executed during interpreter shutdown. As a
7535 consequence, the global variables it needs to access (including
7536 other modules) may already have been deleted or set to "None".
7537 Python guarantees that globals whose name begins with a single
7538 underscore are deleted from their module before other globals
7539 are deleted; if no other references to such globals exist, this
7540 may help in assuring that imported modules are still available
7541 at the time when the "__del__()" method is called.
7542
7543 object.__repr__(self)
7544
7545 Called by the "repr()" built-in function to compute the “official”
7546 string representation of an object. If at all possible, this
7547 should look like a valid Python expression that could be used to
7548 recreate an object with the same value (given an appropriate
7549 environment). If this is not possible, a string of the form
7550 "<...some useful description...>" should be returned. The return
7551 value must be a string object. If a class defines "__repr__()" but
7552 not "__str__()", then "__repr__()" is also used when an “informal”
7553 string representation of instances of that class is required.
7554
7555 This is typically used for debugging, so it is important that the
7556 representation is information-rich and unambiguous. A default
7557 implementation is provided by the "object" class itself.
7558
7559 object.__str__(self)
7560
7561 Called by "str(object)", the default "__format__()" implementation,
7562 and the built-in function "print()", to compute the “informal” or
7563 nicely printable string representation of an object. The return
7564 value must be a str object.
7565
7566 This method differs from "object.__repr__()" in that there is no
7567 expectation that "__str__()" return a valid Python expression: a
7568 more convenient or concise representation can be used.
7569
7570 The default implementation defined by the built-in type "object"
7571 calls "object.__repr__()".
7572
7573 object.__bytes__(self)
7574
7575 Called by bytes to compute a byte-string representation of an
7576 object. This should return a "bytes" object. The "object" class
7577 itself does not provide this method.
7578
7579 object.__format__(self, format_spec)
7580
7581 Called by the "format()" built-in function, and by extension,
7582 evaluation of formatted string literals and the "str.format()"
7583 method, to produce a “formatted” string representation of an
7584 object. The *format_spec* argument is a string that contains a
7585 description of the formatting options desired. The interpretation
7586 of the *format_spec* argument is up to the type implementing
7587 "__format__()", however most classes will either delegate
7588 formatting to one of the built-in types, or use a similar
7589 formatting option syntax.
7590
7591 See Format Specification Mini-Language for a description of the
7592 standard formatting syntax.
7593
7594 The return value must be a string object.
7595
7596 The default implementation by the "object" class should be given an
7597 empty *format_spec* string. It delegates to "__str__()".
7598
7599 Changed in version 3.4: The __format__ method of "object" itself
7600 raises a "TypeError" if passed any non-empty string.
7601
7602 Changed in version 3.7: "object.__format__(x, '')" is now
7603 equivalent to "str(x)" rather than "format(str(x), '')".
7604
7605 object.__lt__(self, other)
7606 object.__le__(self, other)
7607 object.__eq__(self, other)
7608 object.__ne__(self, other)
7609 object.__gt__(self, other)
7610 object.__ge__(self, other)
7611
7612 These are the so-called “rich comparison” methods. The
7613 correspondence between operator symbols and method names is as
7614 follows: "x<y" calls "x.__lt__(y)", "x<=y" calls "x.__le__(y)",
7615 "x==y" calls "x.__eq__(y)", "x!=y" calls "x.__ne__(y)", "x>y" calls
7616 "x.__gt__(y)", and "x>=y" calls "x.__ge__(y)".
7617
7618 A rich comparison method may return the singleton "NotImplemented"
7619 if it does not implement the operation for a given pair of
7620 arguments. By convention, "False" and "True" are returned for a
7621 successful comparison. However, these methods can return any value,
7622 so if the comparison operator is used in a Boolean context (e.g.,
7623 in the condition of an "if" statement), Python will call "bool()"
7624 on the value to determine if the result is true or false.
7625
7626 By default, "object" implements "__eq__()" by using "is", returning
7627 "NotImplemented" in the case of a false comparison: "True if x is y
7628 else NotImplemented". For "__ne__()", by default it delegates to
7629 "__eq__()" and inverts the result unless it is "NotImplemented".
7630 There are no other implied relationships among the comparison
7631 operators or default implementations; for example, the truth of
7632 "(x<y or x==y)" does not imply "x<=y". To automatically generate
7633 ordering operations from a single root operation, see
7634 "functools.total_ordering()".
7635
7636 By default, the "object" class provides implementations consistent
7637 with Value comparisons: equality compares according to object
7638 identity, and order comparisons raise "TypeError". Each default
7639 method may generate these results directly, but may also return
7640 "NotImplemented".
7641
7642 See the paragraph on "__hash__()" for some important notes on
7643 creating *hashable* objects which support custom comparison
7644 operations and are usable as dictionary keys.
7645
7646 There are no swapped-argument versions of these methods (to be used
7647 when the left argument does not support the operation but the right
7648 argument does); rather, "__lt__()" and "__gt__()" are each other’s
7649 reflection, "__le__()" and "__ge__()" are each other’s reflection,
7650 and "__eq__()" and "__ne__()" are their own reflection. If the
7651 operands are of different types, and the right operand’s type is a
7652 direct or indirect subclass of the left operand’s type, the
7653 reflected method of the right operand has priority, otherwise the
7654 left operand’s method has priority. Virtual subclassing is not
7655 considered.
7656
7657 When no appropriate method returns any value other than
7658 "NotImplemented", the "==" and "!=" operators will fall back to
7659 "is" and "is not", respectively.
7660
7661 object.__hash__(self)
7662
7663 Called by built-in function "hash()" and for operations on members
7664 of hashed collections including "set", "frozenset", and "dict".
7665 The "__hash__()" method should return an integer. The only required
7666 property is that objects which compare equal have the same hash
7667 value; it is advised to mix together the hash values of the
7668 components of the object that also play a part in comparison of
7669 objects by packing them into a tuple and hashing the tuple.
7670 Example:
7671
7672 def __hash__(self):
7673 return hash((self.name, self.nick, self.color))
7674
7675 Note:
7676
7677 "hash()" truncates the value returned from an object’s custom
7678 "__hash__()" method to the size of a "Py_ssize_t". This is
7679 typically 8 bytes on 64-bit builds and 4 bytes on 32-bit builds.
7680 If an object’s "__hash__()" must interoperate on builds of
7681 different bit sizes, be sure to check the width on all supported
7682 builds. An easy way to do this is with "python -c "import sys;
7683 print(sys.hash_info.width)"".
7684
7685 If a class does not define an "__eq__()" method it should not
7686 define a "__hash__()" operation either; if it defines "__eq__()"
7687 but not "__hash__()", its instances will not be usable as items in
7688 hashable collections. If a class defines mutable objects and
7689 implements an "__eq__()" method, it should not implement
7690 "__hash__()", since the implementation of *hashable* collections
7691 requires that a key’s hash value is immutable (if the object’s hash
7692 value changes, it will be in the wrong hash bucket).
7693
7694 User-defined classes have "__eq__()" and "__hash__()" methods by
7695 default (inherited from the "object" class); with them, all objects
7696 compare unequal (except with themselves) and "x.__hash__()" returns
7697 an appropriate value such that "x == y" implies both that "x is y"
7698 and "hash(x) == hash(y)".
7699
7700 A class that overrides "__eq__()" and does not define "__hash__()"
7701 will have its "__hash__()" implicitly set to "None". When the
7702 "__hash__()" method of a class is "None", instances of the class
7703 will raise an appropriate "TypeError" when a program attempts to
7704 retrieve their hash value, and will also be correctly identified as
7705 unhashable when checking "isinstance(obj,
7706 collections.abc.Hashable)".
7707
7708 If a class that overrides "__eq__()" needs to retain the
7709 implementation of "__hash__()" from a parent class, the interpreter
7710 must be told this explicitly by setting "__hash__ =
7711 <ParentClass>.__hash__".
7712
7713 If a class that does not override "__eq__()" wishes to suppress
7714 hash support, it should include "__hash__ = None" in the class
7715 definition. A class which defines its own "__hash__()" that
7716 explicitly raises a "TypeError" would be incorrectly identified as
7717 hashable by an "isinstance(obj, collections.abc.Hashable)" call.
7718
7719 Note:
7720
7721 By default, the "__hash__()" values of str and bytes objects are
7722 “salted” with an unpredictable random value. Although they
7723 remain constant within an individual Python process, they are not
7724 predictable between repeated invocations of Python.This is
7725 intended to provide protection against a denial-of-service caused
7726 by carefully chosen inputs that exploit the worst case
7727 performance of a dict insertion, *O*(*n*^2) complexity. See
7728 http://ocert.org/advisories/ocert-2011-003.html for
7729 details.Changing hash values affects the iteration order of sets.
7730 Python has never made guarantees about this ordering (and it
7731 typically varies between 32-bit and 64-bit builds).See also
7732 "PYTHONHASHSEED".
7733
7734 Changed in version 3.3: Hash randomization is enabled by default.
7735
7736 object.__bool__(self)
7737
7738 Called to implement truth value testing and the built-in operation
7739 "bool()"; should return "False" or "True". When this method is not
7740 defined, "__len__()" is called, if it is defined, and the object is
7741 considered true if its result is nonzero. If a class defines
7742 neither "__len__()" nor "__bool__()" (which is true of the "object"
7743 class itself), all its instances are considered true.
7744
7745
7746 Customizing attribute access
7747 ============================
7748
7749 The following methods can be defined to customize the meaning of
7750 attribute access (use of, assignment to, or deletion of "x.name") for
7751 class instances.
7752
7753 object.__getattr__(self, name)
7754
7755 Called when the default attribute access fails with an
7756 "AttributeError" (either "__getattribute__()" raises an
7757 "AttributeError" because *name* is not an instance attribute or an
7758 attribute in the class tree for "self"; or "__get__()" of a *name*
7759 property raises "AttributeError"). This method should either
7760 return the (computed) attribute value or raise an "AttributeError"
7761 exception. The "object" class itself does not provide this method.
7762
7763 Note that if the attribute is found through the normal mechanism,
7764 "__getattr__()" is not called. (This is an intentional asymmetry
7765 between "__getattr__()" and "__setattr__()".) This is done both for
7766 efficiency reasons and because otherwise "__getattr__()" would have
7767 no way to access other attributes of the instance. Note that at
7768 least for instance variables, you can take total control by not
7769 inserting any values in the instance attribute dictionary (but
7770 instead inserting them in another object). See the
7771 "__getattribute__()" method below for a way to actually get total
7772 control over attribute access.
7773
7774 object.__getattribute__(self, name)
7775
7776 Called unconditionally to implement attribute accesses for
7777 instances of the class. If the class also defines "__getattr__()",
7778 the latter will not be called unless "__getattribute__()" either
7779 calls it explicitly or raises an "AttributeError". This method
7780 should return the (computed) attribute value or raise an
7781 "AttributeError" exception. In order to avoid infinite recursion in
7782 this method, its implementation should always call the base class
7783 method with the same name to access any attributes it needs, for
7784 example, "object.__getattribute__(self, name)".
7785
7786 Note:
7787
7788 This method may still be bypassed when looking up special methods
7789 as the result of implicit invocation via language syntax or
7790 built-in functions. See Special method lookup.
7791
7792 For certain sensitive attribute accesses, raises an auditing event
7793 "object.__getattr__" with arguments "obj" and "name".
7794
7795 object.__setattr__(self, name, value)
7796
7797 Called when an attribute assignment is attempted. This is called
7798 instead of the normal mechanism (i.e. store the value in the
7799 instance dictionary). *name* is the attribute name, *value* is the
7800 value to be assigned to it.
7801
7802 If "__setattr__()" wants to assign to an instance attribute, it
7803 should call the base class method with the same name, for example,
7804 "object.__setattr__(self, name, value)".
7805
7806 For certain sensitive attribute assignments, raises an auditing
7807 event "object.__setattr__" with arguments "obj", "name", "value".
7808
7809 object.__delattr__(self, name)
7810
7811 Like "__setattr__()" but for attribute deletion instead of
7812 assignment. This should only be implemented if "del obj.name" is
7813 meaningful for the object.
7814
7815 For certain sensitive attribute deletions, raises an auditing event
7816 "object.__delattr__" with arguments "obj" and "name".
7817
7818 object.__dir__(self)
7819
7820 Called when "dir()" is called on the object. An iterable must be
7821 returned. "dir()" converts the returned iterable to a list and
7822 sorts it.
7823
7824
7825 Customizing module attribute access
7826 -----------------------------------
7827
7828 module.__getattr__()
7829 module.__dir__()
7830
7831 Special names "__getattr__" and "__dir__" can be also used to
7832 customize access to module attributes. The "__getattr__" function at
7833 the module level should accept one argument which is the name of an
7834 attribute and return the computed value or raise an "AttributeError".
7835 If an attribute is not found on a module object through the normal
7836 lookup, i.e. "object.__getattribute__()", then "__getattr__" is
7837 searched in the module "__dict__" before raising an "AttributeError".
7838 If found, it is called with the attribute name and the result is
7839 returned.
7840
7841 The "__dir__" function should accept no arguments, and return an
7842 iterable of strings that represents the names accessible on module. If
7843 present, this function overrides the standard "dir()" search on a
7844 module.
7845
7846 module.__class__
7847
7848 For a more fine grained customization of the module behavior (setting
7849 attributes, properties, etc.), one can set the "__class__" attribute
7850 of a module object to a subclass of "types.ModuleType". For example:
7851
7852 import sys
7853 from types import ModuleType
7854
7855 class VerboseModule(ModuleType):
7856 def __repr__(self):
7857 return f'Verbose {self.__name__}'
7858
7859 def __setattr__(self, attr, value):
7860 print(f'Setting {attr}...')
7861 super().__setattr__(attr, value)
7862
7863 sys.modules[__name__].__class__ = VerboseModule
7864
7865 Note:
7866
7867 Defining module "__getattr__" and setting module "__class__" only
7868 affect lookups made using the attribute access syntax – directly
7869 accessing the module globals (whether by code within the module, or
7870 via a reference to the module’s globals dictionary) is unaffected.
7871
7872 Changed in version 3.5: "__class__" module attribute is now writable.
7873
7874 Added in version 3.7: "__getattr__" and "__dir__" module attributes.
7875
7876 See also:
7877
7878 **PEP 562** - Module __getattr__ and __dir__
7879 Describes the "__getattr__" and "__dir__" functions on modules.
7880
7881
7882 Implementing Descriptors
7883 ------------------------
7884
7885 The following methods only apply when an instance of the class
7886 containing the method (a so-called *descriptor* class) appears in an
7887 *owner* class (the descriptor must be in either the owner’s class
7888 dictionary or in the class dictionary for one of its parents). In the
7889 examples below, “the attribute” refers to the attribute whose name is
7890 the key of the property in the owner class’ "__dict__". The "object"
7891 class itself does not implement any of these protocols.
7892
7893 object.__get__(self, instance, owner=None)
7894
7895 Called to get the attribute of the owner class (class attribute
7896 access) or of an instance of that class (instance attribute
7897 access). The optional *owner* argument is the owner class, while
7898 *instance* is the instance that the attribute was accessed through,
7899 or "None" when the attribute is accessed through the *owner*.
7900
7901 This method should return the computed attribute value or raise an
7902 "AttributeError" exception.
7903
7904 **PEP 252** specifies that "__get__()" is callable with one or two
7905 arguments. Python’s own built-in descriptors support this
7906 specification; however, it is likely that some third-party tools
7907 have descriptors that require both arguments. Python’s own
7908 "__getattribute__()" implementation always passes in both arguments
7909 whether they are required or not.
7910
7911 object.__set__(self, instance, value)
7912
7913 Called to set the attribute on an instance *instance* of the owner
7914 class to a new value, *value*.
7915
7916 Note, adding "__set__()" or "__delete__()" changes the kind of
7917 descriptor to a “data descriptor”. See Invoking Descriptors for
7918 more details.
7919
7920 object.__delete__(self, instance)
7921
7922 Called to delete the attribute on an instance *instance* of the
7923 owner class.
7924
7925 Instances of descriptors may also have the "__objclass__" attribute
7926 present:
7927
7928 object.__objclass__
7929
7930 The attribute "__objclass__" is interpreted by the "inspect" module
7931 as specifying the class where this object was defined (setting this
7932 appropriately can assist in runtime introspection of dynamic class
7933 attributes). For callables, it may indicate that an instance of the
7934 given type (or a subclass) is expected or required as the first
7935 positional argument (for example, CPython sets this attribute for
7936 unbound methods that are implemented in C).
7937
7938
7939 Invoking Descriptors
7940 --------------------
7941
7942 In general, a descriptor is an object attribute with “binding
7943 behavior”, one whose attribute access has been overridden by methods
7944 in the descriptor protocol: "__get__()", "__set__()", and
7945 "__delete__()". If any of those methods are defined for an object, it
7946 is said to be a descriptor.
7947
7948 The default behavior for attribute access is to get, set, or delete
7949 the attribute from an object’s dictionary. For instance, "a.x" has a
7950 lookup chain starting with "a.__dict__['x']", then
7951 "type(a).__dict__['x']", and continuing through the base classes of
7952 "type(a)" excluding metaclasses.
7953
7954 However, if the looked-up value is an object defining one of the
7955 descriptor methods, then Python may override the default behavior and
7956 invoke the descriptor method instead. Where this occurs in the
7957 precedence chain depends on which descriptor methods were defined and
7958 how they were called.
7959
7960 The starting point for descriptor invocation is a binding, "a.x". How
7961 the arguments are assembled depends on "a":
7962
7963 Direct Call
7964 The simplest and least common call is when user code directly
7965 invokes a descriptor method: "x.__get__(a)".
7966
7967 Instance Binding
7968 If binding to an object instance, "a.x" is transformed into the
7969 call: "type(a).__dict__['x'].__get__(a, type(a))".
7970
7971 Class Binding
7972 If binding to a class, "A.x" is transformed into the call:
7973 "A.__dict__['x'].__get__(None, A)".
7974
7975 Super Binding
7976 A dotted lookup such as "super(A, a).x" searches
7977 "a.__class__.__mro__" for a base class "B" following "A" and then
7978 returns "B.__dict__['x'].__get__(a, A)". If not a descriptor, "x"
7979 is returned unchanged.
7980
7981 For instance bindings, the precedence of descriptor invocation depends
7982 on which descriptor methods are defined. A descriptor can define any
7983 combination of "__get__()", "__set__()" and "__delete__()". If it
7984 does not define "__get__()", then accessing the attribute will return
7985 the descriptor object itself unless there is a value in the object’s
7986 instance dictionary. If the descriptor defines "__set__()" and/or
7987 "__delete__()", it is a data descriptor; if it defines neither, it is
7988 a non-data descriptor. Normally, data descriptors define both
7989 "__get__()" and "__set__()", while non-data descriptors have just the
7990 "__get__()" method. Data descriptors with "__get__()" and "__set__()"
7991 (and/or "__delete__()") defined always override a redefinition in an
7992 instance dictionary. In contrast, non-data descriptors can be
7993 overridden by instances.
7994
7995 Python methods (including those decorated with "@staticmethod" and
7996 "@classmethod") are implemented as non-data descriptors. Accordingly,
7997 instances can redefine and override methods. This allows individual
7998 instances to acquire behaviors that differ from other instances of the
7999 same class.
8000
8001 The "property()" function is implemented as a data descriptor.
8002 Accordingly, instances cannot override the behavior of a property.
8003
8004
8005 __slots__
8006 ---------
8007
8008 *__slots__* allow us to explicitly declare data members (like
8009 properties) and deny the creation of "__dict__" and *__weakref__*
8010 (unless explicitly declared in *__slots__* or available in a parent.)
8011
8012 The space saved over using "__dict__" can be significant. Attribute
8013 lookup speed can be significantly improved as well.
8014
8015 object.__slots__
8016
8017 This class variable can be assigned a string, iterable, or sequence
8018 of strings with variable names used by instances. *__slots__*
8019 reserves space for the declared variables and prevents the
8020 automatic creation of "__dict__" and *__weakref__* for each
8021 instance.
8022
8023 Notes on using *__slots__*:
8024
8025 * When inheriting from a class without *__slots__*, the "__dict__" and
8026 *__weakref__* attribute of the instances will always be accessible.
8027
8028 * Without a "__dict__" variable, instances cannot be assigned new
8029 variables not listed in the *__slots__* definition. Attempts to
8030 assign to an unlisted variable name raises "AttributeError". If
8031 dynamic assignment of new variables is desired, then add
8032 "'__dict__'" to the sequence of strings in the *__slots__*
8033 declaration.
8034
8035 * Without a *__weakref__* variable for each instance, classes defining
8036 *__slots__* do not support "weak references" to its instances. If
8037 weak reference support is needed, then add "'__weakref__'" to the
8038 sequence of strings in the *__slots__* declaration.
8039
8040 * *__slots__* are implemented at the class level by creating
8041 descriptors for each variable name. As a result, class attributes
8042 cannot be used to set default values for instance variables defined
8043 by *__slots__*; otherwise, the class attribute would overwrite the
8044 descriptor assignment.
8045
8046 * The action of a *__slots__* declaration is not limited to the class
8047 where it is defined. *__slots__* declared in parents are available
8048 in child classes. However, instances of a child subclass will get a
8049 "__dict__" and *__weakref__* unless the subclass also defines
8050 *__slots__* (which should only contain names of any *additional*
8051 slots).
8052
8053 * If a class defines a slot also defined in a base class, the instance
8054 variable defined by the base class slot is inaccessible (except by
8055 retrieving its descriptor directly from the base class). This
8056 renders the meaning of the program undefined. In the future, a
8057 check may be added to prevent this.
8058
8059 * "TypeError" will be raised if nonempty *__slots__* are defined for a
8060 class derived from a ""variable-length" built-in type" such as
8061 "int", "bytes", and "tuple".
8062
8063 * Any non-string *iterable* may be assigned to *__slots__*.
8064
8065 * If a "dictionary" is used to assign *__slots__*, the dictionary keys
8066 will be used as the slot names. The values of the dictionary can be
8067 used to provide per-attribute docstrings that will be recognised by
8068 "inspect.getdoc()" and displayed in the output of "help()".
8069
8070 * "__class__" assignment works only if both classes have the same
8071 *__slots__*.
8072
8073 * Multiple inheritance with multiple slotted parent classes can be
8074 used, but only one parent is allowed to have attributes created by
8075 slots (the other bases must have empty slot layouts) - violations
8076 raise "TypeError".
8077
8078 * If an *iterator* is used for *__slots__* then a *descriptor* is
8079 created for each of the iterator’s values. However, the *__slots__*
8080 attribute will be an empty iterator.
8081
8082
8083 Customizing class creation
8084 ==========================
8085
8086 Whenever a class inherits from another class, "__init_subclass__()" is
8087 called on the parent class. This way, it is possible to write classes
8088 which change the behavior of subclasses. This is closely related to
8089 class decorators, but where class decorators only affect the specific
8090 class they’re applied to, "__init_subclass__" solely applies to future
8091 subclasses of the class defining the method.
8092
8093 classmethod object.__init_subclass__(cls)
8094
8095 This method is called whenever the containing class is subclassed.
8096 *cls* is then the new subclass. If defined as a normal instance
8097 method, this method is implicitly converted to a class method.
8098
8099 Keyword arguments which are given to a new class are passed to the
8100 parent class’s "__init_subclass__". For compatibility with other
8101 classes using "__init_subclass__", one should take out the needed
8102 keyword arguments and pass the others over to the base class, as
8103 in:
8104
8105 class Philosopher:
8106 def __init_subclass__(cls, /, default_name, **kwargs):
8107 super().__init_subclass__(**kwargs)
8108 cls.default_name = default_name
8109
8110 class AustralianPhilosopher(Philosopher, default_name="Bruce"):
8111 pass
8112
8113 The default implementation "object.__init_subclass__" does nothing,
8114 but raises an error if it is called with any arguments.
8115
8116 Note:
8117
8118 The metaclass hint "metaclass" is consumed by the rest of the
8119 type machinery, and is never passed to "__init_subclass__"
8120 implementations. The actual metaclass (rather than the explicit
8121 hint) can be accessed as "type(cls)".
8122
8123 Added in version 3.6.
8124
8125 When a class is created, "type.__new__()" scans the class variables
8126 and makes callbacks to those with a "__set_name__()" hook.
8127
8128 object.__set_name__(self, owner, name)
8129
8130 Automatically called at the time the owning class *owner* is
8131 created. The object has been assigned to *name* in that class:
8132
8133 class A:
8134 x = C() # Automatically calls: x.__set_name__(A, 'x')
8135
8136 If the class variable is assigned after the class is created,
8137 "__set_name__()" will not be called automatically. If needed,
8138 "__set_name__()" can be called directly:
8139
8140 class A:
8141 pass
8142
8143 c = C()
8144 A.x = c # The hook is not called
8145 c.__set_name__(A, 'x') # Manually invoke the hook
8146
8147 See Creating the class object for more details.
8148
8149 Added in version 3.6.
8150
8151
8152 Metaclasses
8153 -----------
8154
8155 By default, classes are constructed using "type()". The class body is
8156 executed in a new namespace and the class name is bound locally to the
8157 result of "type(name, bases, namespace)".
8158
8159 The class creation process can be customized by passing the
8160 "metaclass" keyword argument in the class definition line, or by
8161 inheriting from an existing class that included such an argument. In
8162 the following example, both "MyClass" and "MySubclass" are instances
8163 of "Meta":
8164
8165 class Meta(type):
8166 pass
8167
8168 class MyClass(metaclass=Meta):
8169 pass
8170
8171 class MySubclass(MyClass):
8172 pass
8173
8174 Any other keyword arguments that are specified in the class definition
8175 are passed through to all metaclass operations described below.
8176
8177 When a class definition is executed, the following steps occur:
8178
8179 * MRO entries are resolved;
8180
8181 * the appropriate metaclass is determined;
8182
8183 * the class namespace is prepared;
8184
8185 * the class body is executed;
8186
8187 * the class object is created.
8188
8189
8190 Resolving MRO entries
8191 ---------------------
8192
8193 object.__mro_entries__(self, bases)
8194
8195 If a base that appears in a class definition is not an instance of
8196 "type", then an "__mro_entries__()" method is searched on the base.
8197 If an "__mro_entries__()" method is found, the base is substituted
8198 with the result of a call to "__mro_entries__()" when creating the
8199 class. The method is called with the original bases tuple passed to
8200 the *bases* parameter, and must return a tuple of classes that will
8201 be used instead of the base. The returned tuple may be empty: in
8202 these cases, the original base is ignored.
8203
8204 See also:
8205
8206 "types.resolve_bases()"
8207 Dynamically resolve bases that are not instances of "type".
8208
8209 "types.get_original_bases()"
8210 Retrieve a class’s “original bases” prior to modifications by
8211 "__mro_entries__()".
8212
8213 **PEP 560**
8214 Core support for typing module and generic types.
8215
8216
8217 Determining the appropriate metaclass
8218 -------------------------------------
8219
8220 The appropriate metaclass for a class definition is determined as
8221 follows:
8222
8223 * if no bases and no explicit metaclass are given, then "type()" is
8224 used;
8225
8226 * if an explicit metaclass is given and it is *not* an instance of
8227 "type()", then it is used directly as the metaclass;
8228
8229 * if an instance of "type()" is given as the explicit metaclass, or
8230 bases are defined, then the most derived metaclass is used.
8231
8232 The most derived metaclass is selected from the explicitly specified
8233 metaclass (if any) and the metaclasses (i.e. "type(cls)") of all
8234 specified base classes. The most derived metaclass is one which is a
8235 subtype of *all* of these candidate metaclasses. If none of the
8236 candidate metaclasses meets that criterion, then the class definition
8237 will fail with "TypeError".
8238
8239
8240 Preparing the class namespace
8241 -----------------------------
8242
8243 Once the appropriate metaclass has been identified, then the class
8244 namespace is prepared. If the metaclass has a "__prepare__" attribute,
8245 it is called as "namespace = metaclass.__prepare__(name, bases,
8246 **kwds)" (where the additional keyword arguments, if any, come from
8247 the class definition). The "__prepare__" method should be implemented
8248 as a "classmethod". The namespace returned by "__prepare__" is passed
8249 in to "__new__", but when the final class object is created the
8250 namespace is copied into a new "dict".
8251
8252 If the metaclass has no "__prepare__" attribute, then the class
8253 namespace is initialised as an empty ordered mapping.
8254
8255 See also:
8256
8257 **PEP 3115** - Metaclasses in Python 3000
8258 Introduced the "__prepare__" namespace hook
8259
8260
8261 Executing the class body
8262 ------------------------
8263
8264 The class body is executed (approximately) as "exec(body, globals(),
8265 namespace)". The key difference from a normal call to "exec()" is that
8266 lexical scoping allows the class body (including any methods) to
8267 reference names from the current and outer scopes when the class
8268 definition occurs inside a function.
8269
8270 However, even when the class definition occurs inside the function,
8271 methods defined inside the class still cannot see names defined at the
8272 class scope. Class variables must be accessed through the first
8273 parameter of instance or class methods, or through the implicit
8274 lexically scoped "__class__" reference described in the next section.
8275
8276
8277 Creating the class object
8278 -------------------------
8279
8280 Once the class namespace has been populated by executing the class
8281 body, the class object is created by calling "metaclass(name, bases,
8282 namespace, **kwds)" (the additional keywords passed here are the same
8283 as those passed to "__prepare__").
8284
8285 This class object is the one that will be referenced by the zero-
8286 argument form of "super()". "__class__" is an implicit closure
8287 reference created by the compiler if any methods in a class body refer
8288 to either "__class__" or "super". This allows the zero argument form
8289 of "super()" to correctly identify the class being defined based on
8290 lexical scoping, while the class or instance that was used to make the
8291 current call is identified based on the first argument passed to the
8292 method.
8293
8294 **CPython implementation detail:** In CPython 3.6 and later, the
8295 "__class__" cell is passed to the metaclass as a "__classcell__" entry
8296 in the class namespace. If present, this must be propagated up to the
8297 "type.__new__" call in order for the class to be initialised
8298 correctly. Failing to do so will result in a "RuntimeError" in Python
8299 3.8.
8300
8301 When using the default metaclass "type", or any metaclass that
8302 ultimately calls "type.__new__", the following additional
8303 customization steps are invoked after creating the class object:
8304
8305 1. The "type.__new__" method collects all of the attributes in the
8306 class namespace that define a "__set_name__()" method;
8307
8308 2. Those "__set_name__" methods are called with the class being
8309 defined and the assigned name of that particular attribute;
8310
8311 3. The "__init_subclass__()" hook is called on the immediate parent of
8312 the new class in its method resolution order.
8313
8314 After the class object is created, it is passed to the class
8315 decorators included in the class definition (if any) and the resulting
8316 object is bound in the local namespace as the defined class.
8317
8318 When a new class is created by "type.__new__", the object provided as
8319 the namespace parameter is copied to a new ordered mapping and the
8320 original object is discarded. The new copy is wrapped in a read-only
8321 proxy, which becomes the "__dict__" attribute of the class object.
8322
8323 See also:
8324
8325 **PEP 3135** - New super
8326 Describes the implicit "__class__" closure reference
8327
8328
8329 Uses for metaclasses
8330 --------------------
8331
8332 The potential uses for metaclasses are boundless. Some ideas that have
8333 been explored include enum, logging, interface checking, automatic
8334 delegation, automatic property creation, proxies, frameworks, and
8335 automatic resource locking/synchronization.
8336
8337
8338 Customizing instance and subclass checks
8339 ========================================
8340
8341 The following methods are used to override the default behavior of the
8342 "isinstance()" and "issubclass()" built-in functions.
8343
8344 In particular, the metaclass "abc.ABCMeta" implements these methods in
8345 order to allow the addition of Abstract Base Classes (ABCs) as
8346 “virtual base classes” to any class or type (including built-in
8347 types), including other ABCs.
8348
8349 type.__instancecheck__(self, instance)
8350
8351 Return true if *instance* should be considered a (direct or
8352 indirect) instance of *class*. If defined, called to implement
8353 "isinstance(instance, class)".
8354
8355 type.__subclasscheck__(self, subclass)
8356
8357 Return true if *subclass* should be considered a (direct or
8358 indirect) subclass of *class*. If defined, called to implement
8359 "issubclass(subclass, class)".
8360
8361 Note that these methods are looked up on the type (metaclass) of a
8362 class. They cannot be defined as class methods in the actual class.
8363 This is consistent with the lookup of special methods that are called
8364 on instances, only in this case the instance is itself a class.
8365
8366 See also:
8367
8368 **PEP 3119** - Introducing Abstract Base Classes
8369 Includes the specification for customizing "isinstance()" and
8370 "issubclass()" behavior through "__instancecheck__()" and
8371 "__subclasscheck__()", with motivation for this functionality in
8372 the context of adding Abstract Base Classes (see the "abc"
8373 module) to the language.
8374
8375
8376 Emulating generic types
8377 =======================
8378
8379 When using *type annotations*, it is often useful to *parameterize* a
8380 *generic type* using Python’s square-brackets notation. For example,
8381 the annotation "list[int]" might be used to signify a "list" in which
8382 all the elements are of type "int".
8383
8384 See also:
8385
8386 **PEP 484** - Type Hints
8387 Introducing Python’s framework for type annotations
8388
8389 Generic Alias Types
8390 Documentation for objects representing parameterized generic
8391 classes
8392
8393 Generics, user-defined generics and "typing.Generic"
8394 Documentation on how to implement generic classes that can be
8395 parameterized at runtime and understood by static type-checkers.
8396
8397 A class can *generally* only be parameterized if it defines the
8398 special class method "__class_getitem__()".
8399
8400 classmethod object.__class_getitem__(cls, key)
8401
8402 Return an object representing the specialization of a generic class
8403 by type arguments found in *key*.
8404
8405 When defined on a class, "__class_getitem__()" is automatically a
8406 class method. As such, there is no need for it to be decorated with
8407 "@classmethod" when it is defined.
8408
8409
8410 The purpose of *__class_getitem__*
8411 ----------------------------------
8412
8413 The purpose of "__class_getitem__()" is to allow runtime
8414 parameterization of standard-library generic classes in order to more
8415 easily apply *type hints* to these classes.
8416
8417 To implement custom generic classes that can be parameterized at
8418 runtime and understood by static type-checkers, users should either
8419 inherit from a standard library class that already implements
8420 "__class_getitem__()", or inherit from "typing.Generic", which has its
8421 own implementation of "__class_getitem__()".
8422
8423 Custom implementations of "__class_getitem__()" on classes defined
8424 outside of the standard library may not be understood by third-party
8425 type-checkers such as mypy. Using "__class_getitem__()" on any class
8426 for purposes other than type hinting is discouraged.
8427
8428
8429 *__class_getitem__* versus *__getitem__*
8430 ----------------------------------------
8431
8432 Usually, the subscription of an object using square brackets will call
8433 the "__getitem__()" instance method defined on the object’s class.
8434 However, if the object being subscribed is itself a class, the class
8435 method "__class_getitem__()" may be called instead.
8436 "__class_getitem__()" should return a GenericAlias object if it is
8437 properly defined.
8438
8439 Presented with the *expression* "obj[x]", the Python interpreter
8440 follows something like the following process to decide whether
8441 "__getitem__()" or "__class_getitem__()" should be called:
8442
8443 from inspect import isclass
8444
8445 def subscribe(obj, x):
8446 """Return the result of the expression 'obj[x]'"""
8447
8448 class_of_obj = type(obj)
8449
8450 # If the class of obj defines __getitem__,
8451 # call class_of_obj.__getitem__(obj, x)
8452 if hasattr(class_of_obj, '__getitem__'):
8453 return class_of_obj.__getitem__(obj, x)
8454
8455 # Else, if obj is a class and defines __class_getitem__,
8456 # call obj.__class_getitem__(x)
8457 elif isclass(obj) and hasattr(obj, '__class_getitem__'):
8458 return obj.__class_getitem__(x)
8459
8460 # Else, raise an exception
8461 else:
8462 raise TypeError(
8463 f"'{class_of_obj.__name__}' object is not subscriptable"
8464 )
8465
8466 In Python, all classes are themselves instances of other classes. The
8467 class of a class is known as that class’s *metaclass*, and most
8468 classes have the "type" class as their metaclass. "type" does not
8469 define "__getitem__()", meaning that expressions such as "list[int]",
8470 "dict[str, float]" and "tuple[str, bytes]" all result in
8471 "__class_getitem__()" being called:
8472
8473 >>> # list has class "type" as its metaclass, like most classes:
8474 >>> type(list)
8475 <class 'type'>
8476 >>> type(dict) == type(list) == type(tuple) == type(str) == type(bytes)
8477 True
8478 >>> # "list[int]" calls "list.__class_getitem__(int)"
8479 >>> list[int]
8480 list[int]
8481 >>> # list.__class_getitem__ returns a GenericAlias object:
8482 >>> type(list[int])
8483 <class 'types.GenericAlias'>
8484
8485 However, if a class has a custom metaclass that defines
8486 "__getitem__()", subscribing the class may result in different
8487 behaviour. An example of this can be found in the "enum" module:
8488
8489 >>> from enum import Enum
8490 >>> class Menu(Enum):
8491 ... """A breakfast menu"""
8492 ... SPAM = 'spam'
8493 ... BACON = 'bacon'
8494 ...
8495 >>> # Enum classes have a custom metaclass:
8496 >>> type(Menu)
8497 <class 'enum.EnumMeta'>
8498 >>> # EnumMeta defines __getitem__,
8499 >>> # so __class_getitem__ is not called,
8500 >>> # and the result is not a GenericAlias object:
8501 >>> Menu['SPAM']
8502 <Menu.SPAM: 'spam'>
8503 >>> type(Menu['SPAM'])
8504 <enum 'Menu'>
8505
8506 See also:
8507
8508 **PEP 560** - Core Support for typing module and generic types
8509 Introducing "__class_getitem__()", and outlining when a
8510 subscription results in "__class_getitem__()" being called
8511 instead of "__getitem__()"
8512
8513
8514 Emulating callable objects
8515 ==========================
8516
8517 object.__call__(self[, args...])
8518
8519 Called when the instance is “called” as a function; if this method
8520 is defined, "x(arg1, arg2, ...)" roughly translates to
8521 "type(x).__call__(x, arg1, ...)". The "object" class itself does
8522 not provide this method.
8523
8524
8525 Emulating container types
8526 =========================
8527
8528 The following methods can be defined to implement container objects.
8529 None of them are provided by the "object" class itself. Containers
8530 usually are *sequences* (such as "lists" or "tuples") or *mappings*
8531 (like *dictionaries*), but can represent other containers as well.
8532 The first set of methods is used either to emulate a sequence or to
8533 emulate a mapping; the difference is that for a sequence, the
8534 allowable keys should be the integers *k* for which "0 <= k < N" where
8535 *N* is the length of the sequence, or "slice" objects, which define a
8536 range of items. It is also recommended that mappings provide the
8537 methods "keys()", "values()", "items()", "get()", "clear()",
8538 "setdefault()", "pop()", "popitem()", "copy()", and "update()"
8539 behaving similar to those for Python’s standard "dictionary" objects.
8540 The "collections.abc" module provides a "MutableMapping" *abstract
8541 base class* to help create those methods from a base set of
8542 "__getitem__()", "__setitem__()", "__delitem__()", and "keys()".
8543
8544 Mutable sequences should provide methods "append()", "clear()",
8545 "count()", "extend()", "index()", "insert()", "pop()", "remove()", and
8546 "reverse()", like Python standard "list" objects. Finally, sequence
8547 types should implement addition (meaning concatenation) and
8548 multiplication (meaning repetition) by defining the methods
8549 "__add__()", "__radd__()", "__iadd__()", "__mul__()", "__rmul__()" and
8550 "__imul__()" described below; they should not define other numerical
8551 operators.
8552
8553 It is recommended that both mappings and sequences implement the
8554 "__contains__()" method to allow efficient use of the "in" operator;
8555 for mappings, "in" should search the mapping’s keys; for sequences, it
8556 should search through the values. It is further recommended that both
8557 mappings and sequences implement the "__iter__()" method to allow
8558 efficient iteration through the container; for mappings, "__iter__()"
8559 should iterate through the object’s keys; for sequences, it should
8560 iterate through the values.
8561
8562 object.__len__(self)
8563
8564 Called to implement the built-in function "len()". Should return
8565 the length of the object, an integer ">=" 0. Also, an object that
8566 doesn’t define a "__bool__()" method and whose "__len__()" method
8567 returns zero is considered to be false in a Boolean context.
8568
8569 **CPython implementation detail:** In CPython, the length is
8570 required to be at most "sys.maxsize". If the length is larger than
8571 "sys.maxsize" some features (such as "len()") may raise
8572 "OverflowError". To prevent raising "OverflowError" by truth value
8573 testing, an object must define a "__bool__()" method.
8574
8575 object.__length_hint__(self)
8576
8577 Called to implement "operator.length_hint()". Should return an
8578 estimated length for the object (which may be greater or less than
8579 the actual length). The length must be an integer ">=" 0. The
8580 return value may also be "NotImplemented", which is treated the
8581 same as if the "__length_hint__" method didn’t exist at all. This
8582 method is purely an optimization and is never required for
8583 correctness.
8584
8585 Added in version 3.4.
8586
8587 Note:
8588
8589 Slicing is done exclusively with the following three methods. A
8590 call like
8591
8592 a[1:2] = b
8593
8594 is translated to
8595
8596 a[slice(1, 2, None)] = b
8597
8598 and so forth. Missing slice items are always filled in with "None".
8599
8600 object.__getitem__(self, key)
8601
8602 Called to implement evaluation of "self[key]". For *sequence*
8603 types, the accepted keys should be integers. Optionally, they may
8604 support "slice" objects as well. Negative index support is also
8605 optional. If *key* is of an inappropriate type, "TypeError" may be
8606 raised; if *key* is a value outside the set of indexes for the
8607 sequence (after any special interpretation of negative values),
8608 "IndexError" should be raised. For *mapping* types, if *key* is
8609 missing (not in the container), "KeyError" should be raised.
8610
8611 Note:
8612
8613 "for" loops expect that an "IndexError" will be raised for
8614 illegal indexes to allow proper detection of the end of the
8615 sequence.
8616
8617 Note:
8618
8619 When subscripting a *class*, the special class method
8620 "__class_getitem__()" may be called instead of "__getitem__()".
8621 See __class_getitem__ versus __getitem__ for more details.
8622
8623 object.__setitem__(self, key, value)
8624
8625 Called to implement assignment to "self[key]". Same note as for
8626 "__getitem__()". This should only be implemented for mappings if
8627 the objects support changes to the values for keys, or if new keys
8628 can be added, or for sequences if elements can be replaced. The
8629 same exceptions should be raised for improper *key* values as for
8630 the "__getitem__()" method.
8631
8632 object.__delitem__(self, key)
8633
8634 Called to implement deletion of "self[key]". Same note as for
8635 "__getitem__()". This should only be implemented for mappings if
8636 the objects support removal of keys, or for sequences if elements
8637 can be removed from the sequence. The same exceptions should be
8638 raised for improper *key* values as for the "__getitem__()" method.
8639
8640 object.__missing__(self, key)
8641
8642 Called by "dict"."__getitem__()" to implement "self[key]" for dict
8643 subclasses when key is not in the dictionary.
8644
8645 object.__iter__(self)
8646
8647 This method is called when an *iterator* is required for a
8648 container. This method should return a new iterator object that can
8649 iterate over all the objects in the container. For mappings, it
8650 should iterate over the keys of the container.
8651
8652 object.__reversed__(self)
8653
8654 Called (if present) by the "reversed()" built-in to implement
8655 reverse iteration. It should return a new iterator object that
8656 iterates over all the objects in the container in reverse order.
8657
8658 If the "__reversed__()" method is not provided, the "reversed()"
8659 built-in will fall back to using the sequence protocol ("__len__()"
8660 and "__getitem__()"). Objects that support the sequence protocol
8661 should only provide "__reversed__()" if they can provide an
8662 implementation that is more efficient than the one provided by
8663 "reversed()".
8664
8665 The membership test operators ("in" and "not in") are normally
8666 implemented as an iteration through a container. However, container
8667 objects can supply the following special method with a more efficient
8668 implementation, which also does not require the object be iterable.
8669
8670 object.__contains__(self, item)
8671
8672 Called to implement membership test operators. Should return true
8673 if *item* is in *self*, false otherwise. For mapping objects, this
8674 should consider the keys of the mapping rather than the values or
8675 the key-item pairs.
8676
8677 For objects that don’t define "__contains__()", the membership test
8678 first tries iteration via "__iter__()", then the old sequence
8679 iteration protocol via "__getitem__()", see this section in the
8680 language reference.
8681
8682
8683 Emulating numeric types
8684 =======================
8685
8686 The following methods can be defined to emulate numeric objects.
8687 Methods corresponding to operations that are not supported by the
8688 particular kind of number implemented (e.g., bitwise operations for
8689 non-integral numbers) should be left undefined.
8690
8691 object.__add__(self, other)
8692 object.__sub__(self, other)
8693 object.__mul__(self, other)
8694 object.__matmul__(self, other)
8695 object.__truediv__(self, other)
8696 object.__floordiv__(self, other)
8697 object.__mod__(self, other)
8698 object.__divmod__(self, other)
8699 object.__pow__(self, other[, modulo])
8700 object.__lshift__(self, other)
8701 object.__rshift__(self, other)
8702 object.__and__(self, other)
8703 object.__xor__(self, other)
8704 object.__or__(self, other)
8705
8706 These methods are called to implement the binary arithmetic
8707 operations ("+", "-", "*", "@", "/", "//", "%", "divmod()",
8708 "pow()", "**", "<<", ">>", "&", "^", "|"). For instance, to
8709 evaluate the expression "x + y", where *x* is an instance of a
8710 class that has an "__add__()" method, "type(x).__add__(x, y)" is
8711 called. The "__divmod__()" method should be the equivalent to
8712 using "__floordiv__()" and "__mod__()"; it should not be related to
8713 "__truediv__()". Note that "__pow__()" should be defined to accept
8714 an optional third argument if the ternary version of the built-in
8715 "pow()" function is to be supported.
8716
8717 If one of those methods does not support the operation with the
8718 supplied arguments, it should return "NotImplemented".
8719
8720 object.__radd__(self, other)
8721 object.__rsub__(self, other)
8722 object.__rmul__(self, other)
8723 object.__rmatmul__(self, other)
8724 object.__rtruediv__(self, other)
8725 object.__rfloordiv__(self, other)
8726 object.__rmod__(self, other)
8727 object.__rdivmod__(self, other)
8728 object.__rpow__(self, other[, modulo])
8729 object.__rlshift__(self, other)
8730 object.__rrshift__(self, other)
8731 object.__rand__(self, other)
8732 object.__rxor__(self, other)
8733 object.__ror__(self, other)
8734
8735 These methods are called to implement the binary arithmetic
8736 operations ("+", "-", "*", "@", "/", "//", "%", "divmod()",
8737 "pow()", "**", "<<", ">>", "&", "^", "|") with reflected (swapped)
8738 operands. These functions are only called if the left operand does
8739 not support the corresponding operation [3] and the operands are of
8740 different types. [4] For instance, to evaluate the expression "x -
8741 y", where *y* is an instance of a class that has an "__rsub__()"
8742 method, "type(y).__rsub__(y, x)" is called if "type(x).__sub__(x,
8743 y)" returns "NotImplemented".
8744
8745 Note that ternary "pow()" will not try calling "__rpow__()" (the
8746 coercion rules would become too complicated).
8747
8748 Note:
8749
8750 If the right operand’s type is a subclass of the left operand’s
8751 type and that subclass provides a different implementation of the
8752 reflected method for the operation, this method will be called
8753 before the left operand’s non-reflected method. This behavior
8754 allows subclasses to override their ancestors’ operations.
8755
8756 object.__iadd__(self, other)
8757 object.__isub__(self, other)
8758 object.__imul__(self, other)
8759 object.__imatmul__(self, other)
8760 object.__itruediv__(self, other)
8761 object.__ifloordiv__(self, other)
8762 object.__imod__(self, other)
8763 object.__ipow__(self, other[, modulo])
8764 object.__ilshift__(self, other)
8765 object.__irshift__(self, other)
8766 object.__iand__(self, other)
8767 object.__ixor__(self, other)
8768 object.__ior__(self, other)
8769
8770 These methods are called to implement the augmented arithmetic
8771 assignments ("+=", "-=", "*=", "@=", "/=", "//=", "%=", "**=",
8772 "<<=", ">>=", "&=", "^=", "|="). These methods should attempt to
8773 do the operation in-place (modifying *self*) and return the result
8774 (which could be, but does not have to be, *self*). If a specific
8775 method is not defined, or if that method returns "NotImplemented",
8776 the augmented assignment falls back to the normal methods. For
8777 instance, if *x* is an instance of a class with an "__iadd__()"
8778 method, "x += y" is equivalent to "x = x.__iadd__(y)" . If
8779 "__iadd__()" does not exist, or if "x.__iadd__(y)" returns
8780 "NotImplemented", "x.__add__(y)" and "y.__radd__(x)" are
8781 considered, as with the evaluation of "x + y". In certain
8782 situations, augmented assignment can result in unexpected errors
8783 (see Why does a_tuple[i] += [‘item’] raise an exception when the
8784 addition works?), but this behavior is in fact part of the data
8785 model.
8786
8787 object.__neg__(self)
8788 object.__pos__(self)
8789 object.__abs__(self)
8790 object.__invert__(self)
8791
8792 Called to implement the unary arithmetic operations ("-", "+",
8793 "abs()" and "~").
8794
8795 object.__complex__(self)
8796 object.__int__(self)
8797 object.__float__(self)
8798
8799 Called to implement the built-in functions "complex()", "int()" and
8800 "float()". Should return a value of the appropriate type.
8801
8802 object.__index__(self)
8803
8804 Called to implement "operator.index()", and whenever Python needs
8805 to losslessly convert the numeric object to an integer object (such
8806 as in slicing, or in the built-in "bin()", "hex()" and "oct()"
8807 functions). Presence of this method indicates that the numeric
8808 object is an integer type. Must return an integer.
8809
8810 If "__int__()", "__float__()" and "__complex__()" are not defined
8811 then corresponding built-in functions "int()", "float()" and
8812 "complex()" fall back to "__index__()".
8813
8814 object.__round__(self[, ndigits])
8815 object.__trunc__(self)
8816 object.__floor__(self)
8817 object.__ceil__(self)
8818
8819 Called to implement the built-in function "round()" and "math"
8820 functions "trunc()", "floor()" and "ceil()". Unless *ndigits* is
8821 passed to "__round__()" all these methods should return the value
8822 of the object truncated to an "Integral" (typically an "int").
8823
8824 The built-in function "int()" falls back to "__trunc__()" if
8825 neither "__int__()" nor "__index__()" is defined.
8826
8827 Changed in version 3.11: The delegation of "int()" to "__trunc__()"
8828 is deprecated.
8829
8830
8831 With Statement Context Managers
8832 ===============================
8833
8834 A *context manager* is an object that defines the runtime context to
8835 be established when executing a "with" statement. The context manager
8836 handles the entry into, and the exit from, the desired runtime context
8837 for the execution of the block of code. Context managers are normally
8838 invoked using the "with" statement (described in section The with
8839 statement), but can also be used by directly invoking their methods.
8840
8841 Typical uses of context managers include saving and restoring various
8842 kinds of global state, locking and unlocking resources, closing opened
8843 files, etc.
8844
8845 For more information on context managers, see Context Manager Types.
8846 The "object" class itself does not provide the context manager
8847 methods.
8848
8849 object.__enter__(self)
8850
8851 Enter the runtime context related to this object. The "with"
8852 statement will bind this method’s return value to the target(s)
8853 specified in the "as" clause of the statement, if any.
8854
8855 object.__exit__(self, exc_type, exc_value, traceback)
8856
8857 Exit the runtime context related to this object. The parameters
8858 describe the exception that caused the context to be exited. If the
8859 context was exited without an exception, all three arguments will
8860 be "None".
8861
8862 If an exception is supplied, and the method wishes to suppress the
8863 exception (i.e., prevent it from being propagated), it should
8864 return a true value. Otherwise, the exception will be processed
8865 normally upon exit from this method.
8866
8867 Note that "__exit__()" methods should not reraise the passed-in
8868 exception; this is the caller’s responsibility.
8869
8870 See also:
8871
8872 **PEP 343** - The “with” statement
8873 The specification, background, and examples for the Python "with"
8874 statement.
8875
8876
8877 Customizing positional arguments in class pattern matching
8878 ==========================================================
8879
8880 When using a class name in a pattern, positional arguments in the
8881 pattern are not allowed by default, i.e. "case MyClass(x, y)" is
8882 typically invalid without special support in "MyClass". To be able to
8883 use that kind of pattern, the class needs to define a *__match_args__*
8884 attribute.
8885
8886 object.__match_args__
8887
8888 This class variable can be assigned a tuple of strings. When this
8889 class is used in a class pattern with positional arguments, each
8890 positional argument will be converted into a keyword argument,
8891 using the corresponding value in *__match_args__* as the keyword.
8892 The absence of this attribute is equivalent to setting it to "()".
8893
8894 For example, if "MyClass.__match_args__" is "("left", "center",
8895 "right")" that means that "case MyClass(x, y)" is equivalent to "case
8896 MyClass(left=x, center=y)". Note that the number of arguments in the
8897 pattern must be smaller than or equal to the number of elements in
8898 *__match_args__*; if it is larger, the pattern match attempt will
8899 raise a "TypeError".
8900
8901 Added in version 3.10.
8902
8903 See also:
8904
8905 **PEP 634** - Structural Pattern Matching
8906 The specification for the Python "match" statement.
8907
8908
8909 Emulating buffer types
8910 ======================
8911
8912 The buffer protocol provides a way for Python objects to expose
8913 efficient access to a low-level memory array. This protocol is
8914 implemented by builtin types such as "bytes" and "memoryview", and
8915 third-party libraries may define additional buffer types.
8916
8917 While buffer types are usually implemented in C, it is also possible
8918 to implement the protocol in Python.
8919
8920 object.__buffer__(self, flags)
8921
8922 Called when a buffer is requested from *self* (for example, by the
8923 "memoryview" constructor). The *flags* argument is an integer
8924 representing the kind of buffer requested, affecting for example
8925 whether the returned buffer is read-only or writable.
8926 "inspect.BufferFlags" provides a convenient way to interpret the
8927 flags. The method must return a "memoryview" object.
8928
8929 object.__release_buffer__(self, buffer)
8930
8931 Called when a buffer is no longer needed. The *buffer* argument is
8932 a "memoryview" object that was previously returned by
8933 "__buffer__()". The method must release any resources associated
8934 with the buffer. This method should return "None". Buffer objects
8935 that do not need to perform any cleanup are not required to
8936 implement this method.
8937
8938 Added in version 3.12.
8939
8940 See also:
8941
8942 **PEP 688** - Making the buffer protocol accessible in Python
8943 Introduces the Python "__buffer__" and "__release_buffer__"
8944 methods.
8945
8946 "collections.abc.Buffer"
8947 ABC for buffer types.
8948
8949
8950 Special method lookup
8951 =====================
8952
8953 For custom classes, implicit invocations of special methods are only
8954 guaranteed to work correctly if defined on an object’s type, not in
8955 the object’s instance dictionary. That behaviour is the reason why
8956 the following code raises an exception:
8957
8958 >>> class C:
8959 ... pass
8960 ...
8961 >>> c = C()
8962 >>> c.__len__ = lambda: 5
8963 >>> len(c)
8964 Traceback (most recent call last):
8965 File "<stdin>", line 1, in <module>
8966 TypeError: object of type 'C' has no len()
8967
8968 The rationale behind this behaviour lies with a number of special
8969 methods such as "__hash__()" and "__repr__()" that are implemented by
8970 all objects, including type objects. If the implicit lookup of these
8971 methods used the conventional lookup process, they would fail when
8972 invoked on the type object itself:
8973
8974 >>> 1 .__hash__() == hash(1)
8975 True
8976 >>> int.__hash__() == hash(int)
8977 Traceback (most recent call last):
8978 File "<stdin>", line 1, in <module>
8979 TypeError: descriptor '__hash__' of 'int' object needs an argument
8980
8981 Incorrectly attempting to invoke an unbound method of a class in this
8982 way is sometimes referred to as ‘metaclass confusion’, and is avoided
8983 by bypassing the instance when looking up special methods:
8984
8985 >>> type(1).__hash__(1) == hash(1)
8986 True
8987 >>> type(int).__hash__(int) == hash(int)
8988 True
8989
8990 In addition to bypassing any instance attributes in the interest of
8991 correctness, implicit special method lookup generally also bypasses
8992 the "__getattribute__()" method even of the object’s metaclass:
8993
8994 >>> class Meta(type):
8995 ... def __getattribute__(*args):
8996 ... print("Metaclass getattribute invoked")
8997 ... return type.__getattribute__(*args)
8998 ...
8999 >>> class C(object, metaclass=Meta):
9000 ... def __len__(self):
9001 ... return 10
9002 ... def __getattribute__(*args):
9003 ... print("Class getattribute invoked")
9004 ... return object.__getattribute__(*args)
9005 ...
9006 >>> c = C()
9007 >>> c.__len__() # Explicit lookup via instance
9008 Class getattribute invoked
9009 10
9010 >>> type(c).__len__(c) # Explicit lookup via type
9011 Metaclass getattribute invoked
9012 10
9013 >>> len(c) # Implicit lookup
9014 10
9015
9016 Bypassing the "__getattribute__()" machinery in this fashion provides
9017 significant scope for speed optimisations within the interpreter, at
9018 the cost of some flexibility in the handling of special methods (the
9019 special method *must* be set on the class object itself in order to be
9020 consistently invoked by the interpreter).
9021 ''',
9022 'string-methods': r'''String Methods
9023 **************
9024
9025 Strings implement all of the common sequence operations, along with
9026 the additional methods described below.
9027
9028 Strings also support two styles of string formatting, one providing a
9029 large degree of flexibility and customization (see "str.format()",
9030 Format String Syntax and Custom String Formatting) and the other based
9031 on C "printf" style formatting that handles a narrower range of types
9032 and is slightly harder to use correctly, but is often faster for the
9033 cases it can handle (printf-style String Formatting).
9034
9035 The Text Processing Services section of the standard library covers a
9036 number of other modules that provide various text related utilities
9037 (including regular expression support in the "re" module).
9038
9039 str.capitalize()
9040
9041 Return a copy of the string with its first character capitalized
9042 and the rest lowercased.
9043
9044 Changed in version 3.8: The first character is now put into
9045 titlecase rather than uppercase. This means that characters like
9046 digraphs will only have their first letter capitalized, instead of
9047 the full character.
9048
9049 str.casefold()
9050
9051 Return a casefolded copy of the string. Casefolded strings may be
9052 used for caseless matching.
9053
9054 Casefolding is similar to lowercasing but more aggressive because
9055 it is intended to remove all case distinctions in a string. For
9056 example, the German lowercase letter "'ß'" is equivalent to ""ss"".
9057 Since it is already lowercase, "lower()" would do nothing to "'ß'";
9058 "casefold()" converts it to ""ss"". For example:
9059
9060 >>> 'straße'.lower()
9061 'straße'
9062 >>> 'straße'.casefold()
9063 'strasse'
9064
9065 The casefolding algorithm is described in section 3.13 ‘Default
9066 Case Folding’ of the Unicode Standard.
9067
9068 Added in version 3.3.
9069
9070 str.center(width, fillchar=' ', /)
9071
9072 Return centered in a string of length *width*. Padding is done
9073 using the specified *fillchar* (default is an ASCII space). The
9074 original string is returned if *width* is less than or equal to
9075 "len(s)". For example:
9076
9077 >>> 'Python'.center(10)
9078 ' Python '
9079 >>> 'Python'.center(10, '-')
9080 '--Python--'
9081 >>> 'Python'.center(4)
9082 'Python'
9083
9084 str.count(sub[, start[, end]])
9085
9086 Return the number of non-overlapping occurrences of substring *sub*
9087 in the range [*start*, *end*]. Optional arguments *start* and
9088 *end* are interpreted as in slice notation.
9089
9090 If *sub* is empty, returns the number of empty strings between
9091 characters which is the length of the string plus one. For example:
9092
9093 >>> 'spam, spam, spam'.count('spam')
9094 3
9095 >>> 'spam, spam, spam'.count('spam', 5)
9096 2
9097 >>> 'spam, spam, spam'.count('spam', 5, 10)
9098 1
9099 >>> 'spam, spam, spam'.count('eggs')
9100 0
9101 >>> 'spam, spam, spam'.count('')
9102 17
9103
9104 str.encode(encoding='utf-8', errors='strict')
9105
9106 Return the string encoded to "bytes".
9107
9108 *encoding* defaults to "'utf-8'"; see Standard Encodings for
9109 possible values.
9110
9111 *errors* controls how encoding errors are handled. If "'strict'"
9112 (the default), a "UnicodeError" exception is raised. Other possible
9113 values are "'ignore'", "'replace'", "'xmlcharrefreplace'",
9114 "'backslashreplace'" and any other name registered via
9115 "codecs.register_error()". See Error Handlers for details.
9116
9117 For performance reasons, the value of *errors* is not checked for
9118 validity unless an encoding error actually occurs, Python
9119 Development Mode is enabled or a debug build is used. For example:
9120
9121 >>> encoded_str_to_bytes = 'Python'.encode()
9122 >>> type(encoded_str_to_bytes)
9123 <class 'bytes'>
9124 >>> encoded_str_to_bytes
9125 b'Python'
9126
9127 Changed in version 3.1: Added support for keyword arguments.
9128
9129 Changed in version 3.9: The value of the *errors* argument is now
9130 checked in Python Development Mode and in debug mode.
9131
9132 str.endswith(suffix[, start[, end]])
9133
9134 Return "True" if the string ends with the specified *suffix*,
9135 otherwise return "False". *suffix* can also be a tuple of suffixes
9136 to look for. With optional *start*, test beginning at that
9137 position. With optional *end*, stop comparing at that position.
9138 Using *start* and *end* is equivalent to
9139 "str[start:end].endswith(suffix)". For example:
9140
9141 >>> 'Python'.endswith('on')
9142 True
9143 >>> 'a tuple of suffixes'.endswith(('at', 'in'))
9144 False
9145 >>> 'a tuple of suffixes'.endswith(('at', 'es'))
9146 True
9147 >>> 'Python is amazing'.endswith('is', 0, 9)
9148 True
9149
9150 See also "startswith()" and "removesuffix()".
9151
9152 str.expandtabs(tabsize=8)
9153
9154 Return a copy of the string where all tab characters are replaced
9155 by one or more spaces, depending on the current column and the
9156 given tab size. Tab positions occur every *tabsize* characters
9157 (default is 8, giving tab positions at columns 0, 8, 16 and so on).
9158 To expand the string, the current column is set to zero and the
9159 string is examined character by character. If the character is a
9160 tab ("\t"), one or more space characters are inserted in the result
9161 until the current column is equal to the next tab position. (The
9162 tab character itself is not copied.) If the character is a newline
9163 ("\n") or return ("\r"), it is copied and the current column is
9164 reset to zero. Any other character is copied unchanged and the
9165 current column is incremented by one regardless of how the
9166 character is represented when printed. For example:
9167
9168 >>> '01\t012\t0123\t01234'.expandtabs()
9169 '01 012 0123 01234'
9170 >>> '01\t012\t0123\t01234'.expandtabs(4)
9171 '01 012 0123 01234'
9172 >>> print('01\t012\n0123\t01234'.expandtabs(4))
9173 01 012
9174 0123 01234
9175
9176 str.find(sub[, start[, end]])
9177
9178 Return the lowest index in the string where substring *sub* is
9179 found within the slice "s[start:end]". Optional arguments *start*
9180 and *end* are interpreted as in slice notation. Return "-1" if
9181 *sub* is not found. For example:
9182
9183 >>> 'spam, spam, spam'.find('sp')
9184 0
9185 >>> 'spam, spam, spam'.find('sp', 5)
9186 6
9187
9188 See also "rfind()" and "index()".
9189
9190 Note:
9191
9192 The "find()" method should be used only if you need to know the
9193 position of *sub*. To check if *sub* is a substring or not, use
9194 the "in" operator:
9195
9196 >>> 'Py' in 'Python'
9197 True
9198
9199 str.format(*args, **kwargs)
9200
9201 Perform a string formatting operation. The string on which this
9202 method is called can contain literal text or replacement fields
9203 delimited by braces "{}". Each replacement field contains either
9204 the numeric index of a positional argument, or the name of a
9205 keyword argument. Returns a copy of the string where each
9206 replacement field is replaced with the string value of the
9207 corresponding argument. For example:
9208
9209 >>> "The sum of 1 + 2 is {0}".format(1+2)
9210 'The sum of 1 + 2 is 3'
9211 >>> "The sum of {a} + {b} is {answer}".format(answer=1+2, a=1, b=2)
9212 'The sum of 1 + 2 is 3'
9213 >>> "{1} expects the {0} Inquisition!".format("Spanish", "Nobody")
9214 'Nobody expects the Spanish Inquisition!'
9215
9216 See Format String Syntax for a description of the various
9217 formatting options that can be specified in format strings.
9218
9219 Note:
9220
9221 When formatting a number ("int", "float", "complex",
9222 "decimal.Decimal" and subclasses) with the "n" type (ex:
9223 "'{:n}'.format(1234)"), the function temporarily sets the
9224 "LC_CTYPE" locale to the "LC_NUMERIC" locale to decode
9225 "decimal_point" and "thousands_sep" fields of "localeconv()" if
9226 they are non-ASCII or longer than 1 byte, and the "LC_NUMERIC"
9227 locale is different than the "LC_CTYPE" locale. This temporary
9228 change affects other threads.
9229
9230 Changed in version 3.7: When formatting a number with the "n" type,
9231 the function sets temporarily the "LC_CTYPE" locale to the
9232 "LC_NUMERIC" locale in some cases.
9233
9234 str.format_map(mapping, /)
9235
9236 Similar to "str.format(**mapping)", except that "mapping" is used
9237 directly and not copied to a "dict". This is useful if for example
9238 "mapping" is a dict subclass:
9239
9240 >>> class Default(dict):
9241 ... def __missing__(self, key):
9242 ... return key
9243 ...
9244 >>> '{name} was born in {country}'.format_map(Default(name='Guido'))
9245 'Guido was born in country'
9246
9247 Added in version 3.2.
9248
9249 str.index(sub[, start[, end]])
9250
9251 Like "find()", but raise "ValueError" when the substring is not
9252 found. For example:
9253
9254 >>> 'spam, spam, spam'.index('spam')
9255 0
9256 >>> 'spam, spam, spam'.index('eggs')
9257 Traceback (most recent call last):
9258 File "<python-input-0>", line 1, in <module>
9259 'spam, spam, spam'.index('eggs')
9260 ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
9261 ValueError: substring not found
9262
9263 See also "rindex()".
9264
9265 str.isalnum()
9266
9267 Return "True" if all characters in the string are alphanumeric and
9268 there is at least one character, "False" otherwise. A character
9269 "c" is alphanumeric if one of the following returns "True":
9270 "c.isalpha()", "c.isdecimal()", "c.isdigit()", or "c.isnumeric()".
9271
9272 str.isalpha()
9273
9274 Return "True" if all characters in the string are alphabetic and
9275 there is at least one character, "False" otherwise. Alphabetic
9276 characters are those characters defined in the Unicode character
9277 database as “Letter”, i.e., those with general category property
9278 being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is
9279 different from the Alphabetic property defined in the section 4.10
9280 ‘Letters, Alphabetic, and Ideographic’ of the Unicode Standard. For
9281 example:
9282
9283 >>> 'Letters and spaces'.isalpha()
9284 False
9285 >>> 'LettersOnly'.isalpha()
9286 True
9287 >>> 'µ'.isalpha() # non-ASCII characters can be considered alphabetical too
9288 True
9289
9290 See Unicode Properties.
9291
9292 str.isascii()
9293
9294 Return "True" if the string is empty or all characters in the
9295 string are ASCII, "False" otherwise. ASCII characters have code
9296 points in the range U+0000-U+007F. For example:
9297
9298 >>> 'ASCII characters'.isascii()
9299 True
9300 >>> 'µ'.isascii()
9301 False
9302
9303 Added in version 3.7.
9304
9305 str.isdecimal()
9306
9307 Return "True" if all characters in the string are decimal
9308 characters and there is at least one character, "False" otherwise.
9309 Decimal characters are those that can be used to form numbers in
9310 base 10, such as U+0660, ARABIC-INDIC DIGIT ZERO. Formally a
9311 decimal character is a character in the Unicode General Category
9312 “Nd”. For example:
9313
9314 >>> '0123456789'.isdecimal()
9315 True
9316 >>> '٠١٢٣٤٥٦٧٨٩'.isdecimal() # Arabic-Indic digits zero to nine
9317 True
9318 >>> 'alphabetic'.isdecimal()
9319 False
9320
9321 str.isdigit()
9322
9323 Return "True" if all characters in the string are digits and there
9324 is at least one character, "False" otherwise. Digits include
9325 decimal characters and digits that need special handling, such as
9326 the compatibility superscript digits. This covers digits which
9327 cannot be used to form numbers in base 10, like the Kharosthi
9328 numbers. Formally, a digit is a character that has the property
9329 value Numeric_Type=Digit or Numeric_Type=Decimal.
9330
9331 str.isidentifier()
9332
9333 Return "True" if the string is a valid identifier according to the
9334 language definition, section Identifiers and keywords.
9335
9336 "keyword.iskeyword()" can be used to test whether string "s" is a
9337 reserved identifier, such as "def" and "class".
9338
9339 Example:
9340
9341 >>> from keyword import iskeyword
9342
9343 >>> 'hello'.isidentifier(), iskeyword('hello')
9344 (True, False)
9345 >>> 'def'.isidentifier(), iskeyword('def')
9346 (True, True)
9347
9348 str.islower()
9349
9350 Return "True" if all cased characters [4] in the string are
9351 lowercase and there is at least one cased character, "False"
9352 otherwise.
9353
9354 str.isnumeric()
9355
9356 Return "True" if all characters in the string are numeric
9357 characters, and there is at least one character, "False" otherwise.
9358 Numeric characters include digit characters, and all characters
9359 that have the Unicode numeric value property, e.g. U+2155, VULGAR
9360 FRACTION ONE FIFTH. Formally, numeric characters are those with
9361 the property value Numeric_Type=Digit, Numeric_Type=Decimal or
9362 Numeric_Type=Numeric. For example:
9363
9364 >>> '0123456789'.isnumeric()
9365 True
9366 >>> '٠١٢٣٤٥٦٧٨٩'.isnumeric() # Arabic-indic digit zero to nine
9367 True
9368 >>> '⅕'.isnumeric() # Vulgar fraction one fifth
9369 True
9370 >>> '²'.isdecimal(), '²'.isdigit(), '²'.isnumeric()
9371 (False, True, True)
9372
9373 See also "isdecimal()" and "isdigit()". Numeric characters are a
9374 superset of decimal numbers.
9375
9376 str.isprintable()
9377
9378 Return "True" if all characters in the string are printable,
9379 "False" if it contains at least one non-printable character.
9380
9381 Here “printable” means the character is suitable for "repr()" to
9382 use in its output; “non-printable” means that "repr()" on built-in
9383 types will hex-escape the character. It has no bearing on the
9384 handling of strings written to "sys.stdout" or "sys.stderr".
9385
9386 The printable characters are those which in the Unicode character
9387 database (see "unicodedata") have a general category in group
9388 Letter, Mark, Number, Punctuation, or Symbol (L, M, N, P, or S);
9389 plus the ASCII space 0x20. Nonprintable characters are those in
9390 group Separator or Other (Z or C), except the ASCII space.
9391
9392 For example:
9393
9394 >>> ''.isprintable(), ' '.isprintable()
9395 (True, True)
9396 >>> '\t'.isprintable(), '\n'.isprintable()
9397 (False, False)
9398
9399 str.isspace()
9400
9401 Return "True" if there are only whitespace characters in the string
9402 and there is at least one character, "False" otherwise.
9403
9404 A character is *whitespace* if in the Unicode character database
9405 (see "unicodedata"), either its general category is "Zs"
9406 (“Separator, space”), or its bidirectional class is one of "WS",
9407 "B", or "S".
9408
9409 str.istitle()
9410
9411 Return "True" if the string is a titlecased string and there is at
9412 least one character, for example uppercase characters may only
9413 follow uncased characters and lowercase characters only cased ones.
9414 Return "False" otherwise.
9415
9416 For example:
9417
9418 >>> 'Spam, Spam, Spam'.istitle()
9419 True
9420 >>> 'spam, spam, spam'.istitle()
9421 False
9422 >>> 'SPAM, SPAM, SPAM'.istitle()
9423 False
9424
9425 See also "title()".
9426
9427 str.isupper()
9428
9429 Return "True" if all cased characters [4] in the string are
9430 uppercase and there is at least one cased character, "False"
9431 otherwise.
9432
9433 >>> 'BANANA'.isupper()
9434 True
9435 >>> 'banana'.isupper()
9436 False
9437 >>> 'baNana'.isupper()
9438 False
9439 >>> ' '.isupper()
9440 False
9441
9442 str.join(iterable, /)
9443
9444 Return a string which is the concatenation of the strings in
9445 *iterable*. A "TypeError" will be raised if there are any non-
9446 string values in *iterable*, including "bytes" objects. The
9447 separator between elements is the string providing this method. For
9448 example:
9449
9450 >>> ', '.join(['spam', 'spam', 'spam'])
9451 'spam, spam, spam'
9452 >>> '-'.join('Python')
9453 'P-y-t-h-o-n'
9454
9455 See also "split()".
9456
9457 str.ljust(width, fillchar=' ', /)
9458
9459 Return the string left justified in a string of length *width*.
9460 Padding is done using the specified *fillchar* (default is an ASCII
9461 space). The original string is returned if *width* is less than or
9462 equal to "len(s)".
9463
9464 For example:
9465
9466 >>> 'Python'.ljust(10)
9467 'Python '
9468 >>> 'Python'.ljust(10, '.')
9469 'Python....'
9470 >>> 'Monty Python'.ljust(10, '.')
9471 'Monty Python'
9472
9473 See also "rjust()".
9474
9475 str.lower()
9476
9477 Return a copy of the string with all the cased characters [4]
9478 converted to lowercase. For example:
9479
9480 >>> 'Lower Method Example'.lower()
9481 'lower method example'
9482
9483 The lowercasing algorithm used is described in section 3.13
9484 ‘Default Case Folding’ of the Unicode Standard.
9485
9486 str.lstrip(chars=None, /)
9487
9488 Return a copy of the string with leading characters removed. The
9489 *chars* argument is a string specifying the set of characters to be
9490 removed. If omitted or "None", the *chars* argument defaults to
9491 removing whitespace. The *chars* argument is not a prefix; rather,
9492 all combinations of its values are stripped:
9493
9494 >>> ' spacious '.lstrip()
9495 'spacious '
9496 >>> 'www.example.com'.lstrip('cmowz.')
9497 'example.com'
9498
9499 See "str.removeprefix()" for a method that will remove a single
9500 prefix string rather than all of a set of characters. For example:
9501
9502 >>> 'Arthur: three!'.lstrip('Arthur: ')
9503 'ee!'
9504 >>> 'Arthur: three!'.removeprefix('Arthur: ')
9505 'three!'
9506
9507 static str.maketrans(dict, /)
9508 static str.maketrans(from, to, remove='', /)
9509
9510 This static method returns a translation table usable for
9511 "str.translate()".
9512
9513 If there is only one argument, it must be a dictionary mapping
9514 Unicode ordinals (integers) or characters (strings of length 1) to
9515 Unicode ordinals, strings (of arbitrary lengths) or "None".
9516 Character keys will then be converted to ordinals.
9517
9518 If there are two arguments, they must be strings of equal length,
9519 and in the resulting dictionary, each character in *from* will be
9520 mapped to the character at the same position in *to*. If there is
9521 a third argument, it must be a string, whose characters will be
9522 mapped to "None" in the result.
9523
9524 str.partition(sep, /)
9525
9526 Split the string at the first occurrence of *sep*, and return a
9527 3-tuple containing the part before the separator, the separator
9528 itself, and the part after the separator. If the separator is not
9529 found, return a 3-tuple containing the string itself, followed by
9530 two empty strings.
9531
9532 str.removeprefix(prefix, /)
9533
9534 If the string starts with the *prefix* string, return
9535 "string[len(prefix):]". Otherwise, return a copy of the original
9536 string:
9537
9538 >>> 'TestHook'.removeprefix('Test')
9539 'Hook'
9540 >>> 'BaseTestCase'.removeprefix('Test')
9541 'BaseTestCase'
9542
9543 Added in version 3.9.
9544
9545 See also "removesuffix()" and "startswith()".
9546
9547 str.removesuffix(suffix, /)
9548
9549 If the string ends with the *suffix* string and that *suffix* is
9550 not empty, return "string[:-len(suffix)]". Otherwise, return a copy
9551 of the original string:
9552
9553 >>> 'MiscTests'.removesuffix('Tests')
9554 'Misc'
9555 >>> 'TmpDirMixin'.removesuffix('Tests')
9556 'TmpDirMixin'
9557
9558 Added in version 3.9.
9559
9560 See also "removeprefix()" and "endswith()".
9561
9562 str.replace(old, new, /, count=-1)
9563
9564 Return a copy of the string with all occurrences of substring *old*
9565 replaced by *new*. If *count* is given, only the first *count*
9566 occurrences are replaced. If *count* is not specified or "-1", then
9567 all occurrences are replaced. For example:
9568
9569 >>> 'spam, spam, spam'.replace('spam', 'eggs')
9570 'eggs, eggs, eggs'
9571 >>> 'spam, spam, spam'.replace('spam', 'eggs', 1)
9572 'eggs, spam, spam'
9573
9574 Changed in version 3.13: *count* is now supported as a keyword
9575 argument.
9576
9577 str.rfind(sub[, start[, end]])
9578
9579 Return the highest index in the string where substring *sub* is
9580 found, such that *sub* is contained within "s[start:end]".
9581 Optional arguments *start* and *end* are interpreted as in slice
9582 notation. Return "-1" on failure. For example:
9583
9584 >>> 'spam, spam, spam'.rfind('sp')
9585 12
9586 >>> 'spam, spam, spam'.rfind('sp', 0, 10)
9587 6
9588
9589 See also "find()" and "rindex()".
9590
9591 str.rindex(sub[, start[, end]])
9592
9593 Like "rfind()" but raises "ValueError" when the substring *sub* is
9594 not found. For example:
9595
9596 >>> 'spam, spam, spam'.rindex('spam')
9597 12
9598 >>> 'spam, spam, spam'.rindex('eggs')
9599 Traceback (most recent call last):
9600 File "<stdin-0>", line 1, in <module>
9601 'spam, spam, spam'.rindex('eggs')
9602 ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
9603 ValueError: substring not found
9604
9605 See also "index()" and "find()".
9606
9607 str.rjust(width, fillchar=' ', /)
9608
9609 Return the string right justified in a string of length *width*.
9610 Padding is done using the specified *fillchar* (default is an ASCII
9611 space). The original string is returned if *width* is less than or
9612 equal to "len(s)".
9613
9614 str.rpartition(sep, /)
9615
9616 Split the string at the last occurrence of *sep*, and return a
9617 3-tuple containing the part before the separator, the separator
9618 itself, and the part after the separator. If the separator is not
9619 found, return a 3-tuple containing two empty strings, followed by
9620 the string itself.
9621
9622 For example:
9623
9624 >>> 'Monty Python'.rpartition(' ')
9625 ('Monty', ' ', 'Python')
9626 >>> "Monty Python's Flying Circus".rpartition(' ')
9627 ("Monty Python's Flying", ' ', 'Circus')
9628 >>> 'Monty Python'.rpartition('-')
9629 ('', '', 'Monty Python')
9630
9631 See also "partition()".
9632
9633 str.rsplit(sep=None, maxsplit=-1)
9634
9635 Return a list of the words in the string, using *sep* as the
9636 delimiter string. If *maxsplit* is given, at most *maxsplit* splits
9637 are done, the *rightmost* ones. If *sep* is not specified or
9638 "None", any whitespace string is a separator. Except for splitting
9639 from the right, "rsplit()" behaves like "split()" which is
9640 described in detail below.
9641
9642 str.rstrip(chars=None, /)
9643
9644 Return a copy of the string with trailing characters removed. The
9645 *chars* argument is a string specifying the set of characters to be
9646 removed. If omitted or "None", the *chars* argument defaults to
9647 removing whitespace. The *chars* argument is not a suffix; rather,
9648 all combinations of its values are stripped:
9649
9650 >>> ' spacious '.rstrip()
9651 ' spacious'
9652 >>> 'mississippi'.rstrip('ipz')
9653 'mississ'
9654
9655 See "str.removesuffix()" for a method that will remove a single
9656 suffix string rather than all of a set of characters. For example:
9657
9658 >>> 'Monty Python'.rstrip(' Python')
9659 'M'
9660 >>> 'Monty Python'.removesuffix(' Python')
9661 'Monty'
9662
9663 str.split(sep=None, maxsplit=-1)
9664
9665 Return a list of the words in the string, using *sep* as the
9666 delimiter string. If *maxsplit* is given, at most *maxsplit*
9667 splits are done (thus, the list will have at most "maxsplit+1"
9668 elements). If *maxsplit* is not specified or "-1", then there is
9669 no limit on the number of splits (all possible splits are made).
9670
9671 If *sep* is given, consecutive delimiters are not grouped together
9672 and are deemed to delimit empty strings (for example,
9673 "'1,,2'.split(',')" returns "['1', '', '2']"). The *sep* argument
9674 may consist of multiple characters as a single delimiter (to split
9675 with multiple delimiters, use "re.split()"). Splitting an empty
9676 string with a specified separator returns "['']".
9677
9678 For example:
9679
9680 >>> '1,2,3'.split(',')
9681 ['1', '2', '3']
9682 >>> '1,2,3'.split(',', maxsplit=1)
9683 ['1', '2,3']
9684 >>> '1,2,,3,'.split(',')
9685 ['1', '2', '', '3', '']
9686 >>> '1<>2<>3<4'.split('<>')
9687 ['1', '2', '3<4']
9688
9689 If *sep* is not specified or is "None", a different splitting
9690 algorithm is applied: runs of consecutive whitespace are regarded
9691 as a single separator, and the result will contain no empty strings
9692 at the start or end if the string has leading or trailing
9693 whitespace. Consequently, splitting an empty string or a string
9694 consisting of just whitespace with a "None" separator returns "[]".
9695
9696 For example:
9697
9698 >>> '1 2 3'.split()
9699 ['1', '2', '3']
9700 >>> '1 2 3'.split(maxsplit=1)
9701 ['1', '2 3']
9702 >>> ' 1 2 3 '.split()
9703 ['1', '2', '3']
9704
9705 If *sep* is not specified or is "None" and *maxsplit* is "0", only
9706 leading runs of consecutive whitespace are considered.
9707
9708 For example:
9709
9710 >>> "".split(None, 0)
9711 []
9712 >>> " ".split(None, 0)
9713 []
9714 >>> " foo ".split(maxsplit=0)
9715 ['foo ']
9716
9717 See also "join()".
9718
9719 str.splitlines(keepends=False)
9720
9721 Return a list of the lines in the string, breaking at line
9722 boundaries. Line breaks are not included in the resulting list
9723 unless *keepends* is given and true.
9724
9725 This method splits on the following line boundaries. In
9726 particular, the boundaries are a superset of *universal newlines*.
9727
9728 +-------------------------+-------------------------------+
9729 | Representation | Description |
9730 |=========================|===============================|
9731 | "\n" | Line Feed |
9732 +-------------------------+-------------------------------+
9733 | "\r" | Carriage Return |
9734 +-------------------------+-------------------------------+
9735 | "\r\n" | Carriage Return + Line Feed |
9736 +-------------------------+-------------------------------+
9737 | "\v" or "\x0b" | Line Tabulation |
9738 +-------------------------+-------------------------------+
9739 | "\f" or "\x0c" | Form Feed |
9740 +-------------------------+-------------------------------+
9741 | "\x1c" | File Separator |
9742 +-------------------------+-------------------------------+
9743 | "\x1d" | Group Separator |
9744 +-------------------------+-------------------------------+
9745 | "\x1e" | Record Separator |
9746 +-------------------------+-------------------------------+
9747 | "\x85" | Next Line (C1 Control Code) |
9748 +-------------------------+-------------------------------+
9749 | "\u2028" | Line Separator |
9750 +-------------------------+-------------------------------+
9751 | "\u2029" | Paragraph Separator |
9752 +-------------------------+-------------------------------+
9753
9754 Changed in version 3.2: "\v" and "\f" added to list of line
9755 boundaries.
9756
9757 For example:
9758
9759 >>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
9760 ['ab c', '', 'de fg', 'kl']
9761 >>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
9762 ['ab c\n', '\n', 'de fg\r', 'kl\r\n']
9763
9764 Unlike "split()" when a delimiter string *sep* is given, this
9765 method returns an empty list for the empty string, and a terminal
9766 line break does not result in an extra line:
9767
9768 >>> "".splitlines()
9769 []
9770 >>> "One line\n".splitlines()
9771 ['One line']
9772
9773 For comparison, "split('\n')" gives:
9774
9775 >>> ''.split('\n')
9776 ['']
9777 >>> 'Two lines\n'.split('\n')
9778 ['Two lines', '']
9779
9780 str.startswith(prefix[, start[, end]])
9781
9782 Return "True" if string starts with the *prefix*, otherwise return
9783 "False". *prefix* can also be a tuple of prefixes to look for.
9784 With optional *start*, test string beginning at that position.
9785 With optional *end*, stop comparing string at that position.
9786
9787 str.strip(chars=None, /)
9788
9789 Return a copy of the string with the leading and trailing
9790 characters removed. The *chars* argument is a string specifying the
9791 set of characters to be removed. If omitted or "None", the *chars*
9792 argument defaults to removing whitespace. The *chars* argument is
9793 not a prefix or suffix; rather, all combinations of its values are
9794 stripped:
9795
9796 >>> ' spacious '.strip()
9797 'spacious'
9798 >>> 'www.example.com'.strip('cmowz.')
9799 'example'
9800
9801 The outermost leading and trailing *chars* argument values are
9802 stripped from the string. Characters are removed from the leading
9803 end until reaching a string character that is not contained in the
9804 set of characters in *chars*. A similar action takes place on the
9805 trailing end. For example:
9806
9807 >>> comment_string = '#....... Section 3.2.1 Issue #32 .......'
9808 >>> comment_string.strip('.#! ')
9809 'Section 3.2.1 Issue #32'
9810
9811 str.swapcase()
9812
9813 Return a copy of the string with uppercase characters converted to
9814 lowercase and vice versa. Note that it is not necessarily true that
9815 "s.swapcase().swapcase() == s".
9816
9817 str.title()
9818
9819 Return a titlecased version of the string where words start with an
9820 uppercase character and the remaining characters are lowercase.
9821
9822 For example:
9823
9824 >>> 'Hello world'.title()
9825 'Hello World'
9826
9827 The algorithm uses a simple language-independent definition of a
9828 word as groups of consecutive letters. The definition works in
9829 many contexts but it means that apostrophes in contractions and
9830 possessives form word boundaries, which may not be the desired
9831 result:
9832
9833 >>> "they're bill's friends from the UK".title()
9834 "They'Re Bill'S Friends From The Uk"
9835
9836 The "string.capwords()" function does not have this problem, as it
9837 splits words on spaces only.
9838
9839 Alternatively, a workaround for apostrophes can be constructed
9840 using regular expressions:
9841
9842 >>> import re
9843 >>> def titlecase(s):
9844 ... return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
9845 ... lambda mo: mo.group(0).capitalize(),
9846 ... s)
9847 ...
9848 >>> titlecase("they're bill's friends.")
9849 "They're Bill's Friends."
9850
9851 See also "istitle()".
9852
9853 str.translate(table, /)
9854
9855 Return a copy of the string in which each character has been mapped
9856 through the given translation table. The table must be an object
9857 that implements indexing via "__getitem__()", typically a *mapping*
9858 or *sequence*. When indexed by a Unicode ordinal (an integer), the
9859 table object can do any of the following: return a Unicode ordinal
9860 or a string, to map the character to one or more other characters;
9861 return "None", to delete the character from the return string; or
9862 raise a "LookupError" exception, to map the character to itself.
9863
9864 You can use "str.maketrans()" to create a translation map from
9865 character-to-character mappings in different formats.
9866
9867 See also the "codecs" module for a more flexible approach to custom
9868 character mappings.
9869
9870 str.upper()
9871
9872 Return a copy of the string with all the cased characters [4]
9873 converted to uppercase. Note that "s.upper().isupper()" might be
9874 "False" if "s" contains uncased characters or if the Unicode
9875 category of the resulting character(s) is not “Lu” (Letter,
9876 uppercase), but e.g. “Lt” (Letter, titlecase).
9877
9878 The uppercasing algorithm used is described in section 3.13
9879 ‘Default Case Folding’ of the Unicode Standard.
9880
9881 str.zfill(width, /)
9882
9883 Return a copy of the string left filled with ASCII "'0'" digits to
9884 make a string of length *width*. A leading sign prefix
9885 ("'+'"/"'-'") is handled by inserting the padding *after* the sign
9886 character rather than before. The original string is returned if
9887 *width* is less than or equal to "len(s)".
9888
9889 For example:
9890
9891 >>> "42".zfill(5)
9892 '00042'
9893 >>> "-42".zfill(5)
9894 '-0042'
9895 ''',
9896 'strings': '''String and Bytes literals
9897 *************************
9898
9899 String literals are described by the following lexical definitions:
9900
9901 stringliteral ::= [stringprefix](shortstring | longstring)
9902 stringprefix ::= "r" | "u" | "R" | "U" | "f" | "F"
9903 | "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | "Rf" | "RF"
9904 shortstring ::= "'" shortstringitem* "'" | '"' shortstringitem* '"'
9905 longstring ::= "\'\'\'" longstringitem* "\'\'\'" | '"""' longstringitem* '"""'
9906 shortstringitem ::= shortstringchar | stringescapeseq
9907 longstringitem ::= longstringchar | stringescapeseq
9908 shortstringchar ::= <any source character except "\\" or newline or the quote>
9909 longstringchar ::= <any source character except "\\">
9910 stringescapeseq ::= "\\" <any source character>
9911
9912 bytesliteral ::= bytesprefix(shortbytes | longbytes)
9913 bytesprefix ::= "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"
9914 shortbytes ::= "'" shortbytesitem* "'" | '"' shortbytesitem* '"'
9915 longbytes ::= "\'\'\'" longbytesitem* "\'\'\'" | '"""' longbytesitem* '"""'
9916 shortbytesitem ::= shortbyteschar | bytesescapeseq
9917 longbytesitem ::= longbyteschar | bytesescapeseq
9918 shortbyteschar ::= <any ASCII character except "\\" or newline or the quote>
9919 longbyteschar ::= <any ASCII character except "\\">
9920 bytesescapeseq ::= "\\" <any ASCII character>
9921
9922 One syntactic restriction not indicated by these productions is that
9923 whitespace is not allowed between the "stringprefix" or "bytesprefix"
9924 and the rest of the literal. The source character set is defined by
9925 the encoding declaration; it is UTF-8 if no encoding declaration is
9926 given in the source file; see section Encoding declarations.
9927
9928 In plain English: Both types of literals can be enclosed in matching
9929 single quotes ("'") or double quotes ("""). They can also be enclosed
9930 in matching groups of three single or double quotes (these are
9931 generally referred to as *triple-quoted strings*). The backslash ("\\")
9932 character is used to give special meaning to otherwise ordinary
9933 characters like "n", which means ‘newline’ when escaped ("\\n"). It can
9934 also be used to escape characters that otherwise have a special
9935 meaning, such as newline, backslash itself, or the quote character.
9936 See escape sequences below for examples.
9937
9938 Bytes literals are always prefixed with "'b'" or "'B'"; they produce
9939 an instance of the "bytes" type instead of the "str" type. They may
9940 only contain ASCII characters; bytes with a numeric value of 128 or
9941 greater must be expressed with escapes.
9942
9943 Both string and bytes literals may optionally be prefixed with a
9944 letter "'r'" or "'R'"; such constructs are called *raw string
9945 literals* and *raw bytes literals* respectively and treat backslashes
9946 as literal characters. As a result, in raw string literals, "'\\U'"
9947 and "'\\u'" escapes are not treated specially.
9948
9949 Added in version 3.3: The "'rb'" prefix of raw bytes literals has been
9950 added as a synonym of "'br'".Support for the unicode legacy literal
9951 ("u'value'") was reintroduced to simplify the maintenance of dual
9952 Python 2.x and 3.x codebases. See **PEP 414** for more information.
9953
9954 A string literal with "'f'" or "'F'" in its prefix is a *formatted
9955 string literal*; see f-strings. The "'f'" may be combined with "'r'",
9956 but not with "'b'" or "'u'", therefore raw formatted strings are
9957 possible, but formatted bytes literals are not.
9958
9959 In triple-quoted literals, unescaped newlines and quotes are allowed
9960 (and are retained), except that three unescaped quotes in a row
9961 terminate the literal. (A “quote” is the character used to open the
9962 literal, i.e. either "'" or """.)
9963
9964
9965 Escape sequences
9966 ================
9967
9968 Unless an "'r'" or "'R'" prefix is present, escape sequences in string
9969 and bytes literals are interpreted according to rules similar to those
9970 used by Standard C. The recognized escape sequences are:
9971
9972 +---------------------------+-----------------------------------+---------+
9973 | Escape Sequence | Meaning | Notes |
9974 |===========================|===================================|=========|
9975 | "\\"<newline> | Backslash and newline ignored | (1) |
9976 +---------------------------+-----------------------------------+---------+
9977 | "\\\\" | Backslash ("\\") | |
9978 +---------------------------+-----------------------------------+---------+
9979 | "\\'" | Single quote ("'") | |
9980 +---------------------------+-----------------------------------+---------+
9981 | "\\"" | Double quote (""") | |
9982 +---------------------------+-----------------------------------+---------+
9983 | "\\a" | ASCII Bell (BEL) | |
9984 +---------------------------+-----------------------------------+---------+
9985 | "\\b" | ASCII Backspace (BS) | |
9986 +---------------------------+-----------------------------------+---------+
9987 | "\\f" | ASCII Formfeed (FF) | |
9988 +---------------------------+-----------------------------------+---------+
9989 | "\\n" | ASCII Linefeed (LF) | |
9990 +---------------------------+-----------------------------------+---------+
9991 | "\\r" | ASCII Carriage Return (CR) | |
9992 +---------------------------+-----------------------------------+---------+
9993 | "\\t" | ASCII Horizontal Tab (TAB) | |
9994 +---------------------------+-----------------------------------+---------+
9995 | "\\v" | ASCII Vertical Tab (VT) | |
9996 +---------------------------+-----------------------------------+---------+
9997 | "\\*ooo*" | Character with octal value *ooo* | (2,4) |
9998 +---------------------------+-----------------------------------+---------+
9999 | "\\x*hh*" | Character with hex value *hh* | (3,4) |
10000 +---------------------------+-----------------------------------+---------+
10001
10002 Escape sequences only recognized in string literals are:
10003
10004 +---------------------------+-----------------------------------+---------+
10005 | Escape Sequence | Meaning | Notes |
10006 |===========================|===================================|=========|
10007 | "\\N{*name*}" | Character named *name* in the | (5) |
10008 | | Unicode database | |
10009 +---------------------------+-----------------------------------+---------+
10010 | "\\u*xxxx*" | Character with 16-bit hex value | (6) |
10011 | | *xxxx* | |
10012 +---------------------------+-----------------------------------+---------+
10013 | "\\U*xxxxxxxx*" | Character with 32-bit hex value | (7) |
10014 | | *xxxxxxxx* | |
10015 +---------------------------+-----------------------------------+---------+
10016
10017 Notes:
10018
10019 1. A backslash can be added at the end of a line to ignore the
10020 newline:
10021
10022 >>> 'This string will not include \\
10023 ... backslashes or newline characters.'
10024 'This string will not include backslashes or newline characters.'
10025
10026 The same result can be achieved using triple-quoted strings, or
10027 parentheses and string literal concatenation.
10028
10029 2. As in Standard C, up to three octal digits are accepted.
10030
10031 Changed in version 3.11: Octal escapes with value larger than
10032 "0o377" produce a "DeprecationWarning".
10033
10034 Changed in version 3.12: Octal escapes with value larger than
10035 "0o377" produce a "SyntaxWarning". In a future Python version they
10036 will be eventually a "SyntaxError".
10037
10038 3. Unlike in Standard C, exactly two hex digits are required.
10039
10040 4. In a bytes literal, hexadecimal and octal escapes denote the byte
10041 with the given value. In a string literal, these escapes denote a
10042 Unicode character with the given value.
10043
10044 5. Changed in version 3.3: Support for name aliases [1] has been
10045 added.
10046
10047 6. Exactly four hex digits are required.
10048
10049 7. Any Unicode character can be encoded this way. Exactly eight hex
10050 digits are required.
10051
10052 Unlike Standard C, all unrecognized escape sequences are left in the
10053 string unchanged, i.e., *the backslash is left in the result*. (This
10054 behavior is useful when debugging: if an escape sequence is mistyped,
10055 the resulting output is more easily recognized as broken.) It is also
10056 important to note that the escape sequences only recognized in string
10057 literals fall into the category of unrecognized escapes for bytes
10058 literals.
10059
10060 Changed in version 3.6: Unrecognized escape sequences produce a
10061 "DeprecationWarning".
10062
10063 Changed in version 3.12: Unrecognized escape sequences produce a
10064 "SyntaxWarning". In a future Python version they will be eventually a
10065 "SyntaxError".
10066
10067 Even in a raw literal, quotes can be escaped with a backslash, but the
10068 backslash remains in the result; for example, "r"\\""" is a valid
10069 string literal consisting of two characters: a backslash and a double
10070 quote; "r"\\"" is not a valid string literal (even a raw string cannot
10071 end in an odd number of backslashes). Specifically, *a raw literal
10072 cannot end in a single backslash* (since the backslash would escape
10073 the following quote character). Note also that a single backslash
10074 followed by a newline is interpreted as those two characters as part
10075 of the literal, *not* as a line continuation.
10076 ''',
10077 'subscriptions': r'''Subscriptions
10078 *************
10079
10080 The subscription of an instance of a container class will generally
10081 select an element from the container. The subscription of a *generic
10082 class* will generally return a GenericAlias object.
10083
10084 subscription ::= primary "[" flexible_expression_list "]"
10085
10086 When an object is subscripted, the interpreter will evaluate the
10087 primary and the expression list.
10088
10089 The primary must evaluate to an object that supports subscription. An
10090 object may support subscription through defining one or both of
10091 "__getitem__()" and "__class_getitem__()". When the primary is
10092 subscripted, the evaluated result of the expression list will be
10093 passed to one of these methods. For more details on when
10094 "__class_getitem__" is called instead of "__getitem__", see
10095 __class_getitem__ versus __getitem__.
10096
10097 If the expression list contains at least one comma, or if any of the
10098 expressions are starred, the expression list will evaluate to a
10099 "tuple" containing the items of the expression list. Otherwise, the
10100 expression list will evaluate to the value of the list’s sole member.
10101
10102 Changed in version 3.11: Expressions in an expression list may be
10103 starred. See **PEP 646**.
10104
10105 For built-in objects, there are two types of objects that support
10106 subscription via "__getitem__()":
10107
10108 1. Mappings. If the primary is a *mapping*, the expression list must
10109 evaluate to an object whose value is one of the keys of the
10110 mapping, and the subscription selects the value in the mapping that
10111 corresponds to that key. An example of a builtin mapping class is
10112 the "dict" class.
10113
10114 2. Sequences. If the primary is a *sequence*, the expression list must
10115 evaluate to an "int" or a "slice" (as discussed in the following
10116 section). Examples of builtin sequence classes include the "str",
10117 "list" and "tuple" classes.
10118
10119 The formal syntax makes no special provision for negative indices in
10120 *sequences*. However, built-in sequences all provide a "__getitem__()"
10121 method that interprets negative indices by adding the length of the
10122 sequence to the index so that, for example, "x[-1]" selects the last
10123 item of "x". The resulting value must be a nonnegative integer less
10124 than the number of items in the sequence, and the subscription selects
10125 the item whose index is that value (counting from zero). Since the
10126 support for negative indices and slicing occurs in the object’s
10127 "__getitem__()" method, subclasses overriding this method will need to
10128 explicitly add that support.
10129
10130 A "string" is a special kind of sequence whose items are *characters*.
10131 A character is not a separate data type but a string of exactly one
10132 character.
10133 ''',
10134 'truth': r'''Truth Value Testing
10135 *******************
10136
10137 Any object can be tested for truth value, for use in an "if" or
10138 "while" condition or as operand of the Boolean operations below.
10139
10140 By default, an object is considered true unless its class defines
10141 either a "__bool__()" method that returns "False" or a "__len__()"
10142 method that returns zero, when called with the object. [1] Here are
10143 most of the built-in objects considered false:
10144
10145 * constants defined to be false: "None" and "False"
10146
10147 * zero of any numeric type: "0", "0.0", "0j", "Decimal(0)",
10148 "Fraction(0, 1)"
10149
10150 * empty sequences and collections: "''", "()", "[]", "{}", "set()",
10151 "range(0)"
10152
10153 Operations and built-in functions that have a Boolean result always
10154 return "0" or "False" for false and "1" or "True" for true, unless
10155 otherwise stated. (Important exception: the Boolean operations "or"
10156 and "and" always return one of their operands.)
10157 ''',
10158 'try': r'''The "try" statement
10159 *******************
10160
10161 The "try" statement specifies exception handlers and/or cleanup code
10162 for a group of statements:
10163
10164 try_stmt ::= try1_stmt | try2_stmt | try3_stmt
10165 try1_stmt ::= "try" ":" suite
10166 ("except" [expression ["as" identifier]] ":" suite)+
10167 ["else" ":" suite]
10168 ["finally" ":" suite]
10169 try2_stmt ::= "try" ":" suite
10170 ("except" "*" expression ["as" identifier] ":" suite)+
10171 ["else" ":" suite]
10172 ["finally" ":" suite]
10173 try3_stmt ::= "try" ":" suite
10174 "finally" ":" suite
10175
10176 Additional information on exceptions can be found in section
10177 Exceptions, and information on using the "raise" statement to generate
10178 exceptions may be found in section The raise statement.
10179
10180
10181 "except" clause
10182 ===============
10183
10184 The "except" clause(s) specify one or more exception handlers. When no
10185 exception occurs in the "try" clause, no exception handler is
10186 executed. When an exception occurs in the "try" suite, a search for an
10187 exception handler is started. This search inspects the "except"
10188 clauses in turn until one is found that matches the exception. An
10189 expression-less "except" clause, if present, must be last; it matches
10190 any exception.
10191
10192 For an "except" clause with an expression, the expression must
10193 evaluate to an exception type or a tuple of exception types. The
10194 raised exception matches an "except" clause whose expression evaluates
10195 to the class or a *non-virtual base class* of the exception object, or
10196 to a tuple that contains such a class.
10197
10198 If no "except" clause matches the exception, the search for an
10199 exception handler continues in the surrounding code and on the
10200 invocation stack. [1]
10201
10202 If the evaluation of an expression in the header of an "except" clause
10203 raises an exception, the original search for a handler is canceled and
10204 a search starts for the new exception in the surrounding code and on
10205 the call stack (it is treated as if the entire "try" statement raised
10206 the exception).
10207
10208 When a matching "except" clause is found, the exception is assigned to
10209 the target specified after the "as" keyword in that "except" clause,
10210 if present, and the "except" clause’s suite is executed. All "except"
10211 clauses must have an executable block. When the end of this block is
10212 reached, execution continues normally after the entire "try"
10213 statement. (This means that if two nested handlers exist for the same
10214 exception, and the exception occurs in the "try" clause of the inner
10215 handler, the outer handler will not handle the exception.)
10216
10217 When an exception has been assigned using "as target", it is cleared
10218 at the end of the "except" clause. This is as if
10219
10220 except E as N:
10221 foo
10222
10223 was translated to
10224
10225 except E as N:
10226 try:
10227 foo
10228 finally:
10229 del N
10230
10231 This means the exception must be assigned to a different name to be
10232 able to refer to it after the "except" clause. Exceptions are cleared
10233 because with the traceback attached to them, they form a reference
10234 cycle with the stack frame, keeping all locals in that frame alive
10235 until the next garbage collection occurs.
10236
10237 Before an "except" clause’s suite is executed, the exception is stored
10238 in the "sys" module, where it can be accessed from within the body of
10239 the "except" clause by calling "sys.exception()". When leaving an
10240 exception handler, the exception stored in the "sys" module is reset
10241 to its previous value:
10242
10243 >>> print(sys.exception())
10244 None
10245 >>> try:
10246 ... raise TypeError
10247 ... except:
10248 ... print(repr(sys.exception()))
10249 ... try:
10250 ... raise ValueError
10251 ... except:
10252 ... print(repr(sys.exception()))
10253 ... print(repr(sys.exception()))
10254 ...
10255 TypeError()
10256 ValueError()
10257 TypeError()
10258 >>> print(sys.exception())
10259 None
10260
10261
10262 "except*" clause
10263 ================
10264
10265 The "except*" clause(s) specify one or more handlers for groups of
10266 exceptions ("BaseExceptionGroup" instances). A "try" statement can
10267 have either "except" or "except*" clauses, but not both. The exception
10268 type for matching is mandatory in the case of "except*", so "except*:"
10269 is a syntax error. The type is interpreted as in the case of "except",
10270 but matching is performed on the exceptions contained in the group
10271 that is being handled. An "TypeError" is raised if a matching type is
10272 a subclass of "BaseExceptionGroup", because that would have ambiguous
10273 semantics.
10274
10275 When an exception group is raised in the try block, each "except*"
10276 clause splits (see "split()") it into the subgroups of matching and
10277 non-matching exceptions. If the matching subgroup is not empty, it
10278 becomes the handled exception (the value returned from
10279 "sys.exception()") and assigned to the target of the "except*" clause
10280 (if there is one). Then, the body of the "except*" clause executes. If
10281 the non-matching subgroup is not empty, it is processed by the next
10282 "except*" in the same manner. This continues until all exceptions in
10283 the group have been matched, or the last "except*" clause has run.
10284
10285 After all "except*" clauses execute, the group of unhandled exceptions
10286 is merged with any exceptions that were raised or re-raised from
10287 within "except*" clauses. This merged exception group propagates on.:
10288
10289 >>> try:
10290 ... raise ExceptionGroup("eg",
10291 ... [ValueError(1), TypeError(2), OSError(3), OSError(4)])
10292 ... except* TypeError as e:
10293 ... print(f'caught {type(e)} with nested {e.exceptions}')
10294 ... except* OSError as e:
10295 ... print(f'caught {type(e)} with nested {e.exceptions}')
10296 ...
10297 caught <class 'ExceptionGroup'> with nested (TypeError(2),)
10298 caught <class 'ExceptionGroup'> with nested (OSError(3), OSError(4))
10299 + Exception Group Traceback (most recent call last):
10300 | File "<doctest default[0]>", line 2, in <module>
10301 | raise ExceptionGroup("eg",
10302 | [ValueError(1), TypeError(2), OSError(3), OSError(4)])
10303 | ExceptionGroup: eg (1 sub-exception)
10304 +-+---------------- 1 ----------------
10305 | ValueError: 1
10306 +------------------------------------
10307
10308 If the exception raised from the "try" block is not an exception group
10309 and its type matches one of the "except*" clauses, it is caught and
10310 wrapped by an exception group with an empty message string. This
10311 ensures that the type of the target "e" is consistently
10312 "BaseExceptionGroup":
10313
10314 >>> try:
10315 ... raise BlockingIOError
10316 ... except* BlockingIOError as e:
10317 ... print(repr(e))
10318 ...
10319 ExceptionGroup('', (BlockingIOError(),))
10320
10321 "break", "continue" and "return" cannot appear in an "except*" clause.
10322
10323
10324 "else" clause
10325 =============
10326
10327 The optional "else" clause is executed if the control flow leaves the
10328 "try" suite, no exception was raised, and no "return", "continue", or
10329 "break" statement was executed. Exceptions in the "else" clause are
10330 not handled by the preceding "except" clauses.
10331
10332
10333 "finally" clause
10334 ================
10335
10336 If "finally" is present, it specifies a ‘cleanup’ handler. The "try"
10337 clause is executed, including any "except" and "else" clauses. If an
10338 exception occurs in any of the clauses and is not handled, the
10339 exception is temporarily saved. The "finally" clause is executed. If
10340 there is a saved exception it is re-raised at the end of the "finally"
10341 clause. If the "finally" clause raises another exception, the saved
10342 exception is set as the context of the new exception. If the "finally"
10343 clause executes a "return", "break" or "continue" statement, the saved
10344 exception is discarded:
10345
10346 >>> def f():
10347 ... try:
10348 ... 1/0
10349 ... finally:
10350 ... return 42
10351 ...
10352 >>> f()
10353 42
10354
10355 The exception information is not available to the program during
10356 execution of the "finally" clause.
10357
10358 When a "return", "break" or "continue" statement is executed in the
10359 "try" suite of a "try"…"finally" statement, the "finally" clause is
10360 also executed ‘on the way out.’
10361
10362 The return value of a function is determined by the last "return"
10363 statement executed. Since the "finally" clause always executes, a
10364 "return" statement executed in the "finally" clause will always be the
10365 last one executed:
10366
10367 >>> def foo():
10368 ... try:
10369 ... return 'try'
10370 ... finally:
10371 ... return 'finally'
10372 ...
10373 >>> foo()
10374 'finally'
10375
10376 Changed in version 3.8: Prior to Python 3.8, a "continue" statement
10377 was illegal in the "finally" clause due to a problem with the
10378 implementation.
10379 ''',
10380 'types': r'''The standard type hierarchy
10381 ***************************
10382
10383 Below is a list of the types that are built into Python. Extension
10384 modules (written in C, Java, or other languages, depending on the
10385 implementation) can define additional types. Future versions of
10386 Python may add types to the type hierarchy (e.g., rational numbers,
10387 efficiently stored arrays of integers, etc.), although such additions
10388 will often be provided via the standard library instead.
10389
10390 Some of the type descriptions below contain a paragraph listing
10391 ‘special attributes.’ These are attributes that provide access to the
10392 implementation and are not intended for general use. Their definition
10393 may change in the future.
10394
10395
10396 None
10397 ====
10398
10399 This type has a single value. There is a single object with this
10400 value. This object is accessed through the built-in name "None". It is
10401 used to signify the absence of a value in many situations, e.g., it is
10402 returned from functions that don’t explicitly return anything. Its
10403 truth value is false.
10404
10405
10406 NotImplemented
10407 ==============
10408
10409 This type has a single value. There is a single object with this
10410 value. This object is accessed through the built-in name
10411 "NotImplemented". Numeric methods and rich comparison methods should
10412 return this value if they do not implement the operation for the
10413 operands provided. (The interpreter will then try the reflected
10414 operation, or some other fallback, depending on the operator.) It
10415 should not be evaluated in a boolean context.
10416
10417 See Implementing the arithmetic operations for more details.
10418
10419 Changed in version 3.9: Evaluating "NotImplemented" in a boolean
10420 context is deprecated. While it currently evaluates as true, it will
10421 emit a "DeprecationWarning". It will raise a "TypeError" in a future
10422 version of Python.
10423
10424
10425 Ellipsis
10426 ========
10427
10428 This type has a single value. There is a single object with this
10429 value. This object is accessed through the literal "..." or the built-
10430 in name "Ellipsis". Its truth value is true.
10431
10432
10433 "numbers.Number"
10434 ================
10435
10436 These are created by numeric literals and returned as results by
10437 arithmetic operators and arithmetic built-in functions. Numeric
10438 objects are immutable; once created their value never changes. Python
10439 numbers are of course strongly related to mathematical numbers, but
10440 subject to the limitations of numerical representation in computers.
10441
10442 The string representations of the numeric classes, computed by
10443 "__repr__()" and "__str__()", have the following properties:
10444
10445 * They are valid numeric literals which, when passed to their class
10446 constructor, produce an object having the value of the original
10447 numeric.
10448
10449 * The representation is in base 10, when possible.
10450
10451 * Leading zeros, possibly excepting a single zero before a decimal
10452 point, are not shown.
10453
10454 * Trailing zeros, possibly excepting a single zero after a decimal
10455 point, are not shown.
10456
10457 * A sign is shown only when the number is negative.
10458
10459 Python distinguishes between integers, floating-point numbers, and
10460 complex numbers:
10461
10462
10463 "numbers.Integral"
10464 ------------------
10465
10466 These represent elements from the mathematical set of integers
10467 (positive and negative).
10468
10469 Note:
10470
10471 The rules for integer representation are intended to give the most
10472 meaningful interpretation of shift and mask operations involving
10473 negative integers.
10474
10475 There are two types of integers:
10476
10477 Integers ("int")
10478 These represent numbers in an unlimited range, subject to available
10479 (virtual) memory only. For the purpose of shift and mask
10480 operations, a binary representation is assumed, and negative
10481 numbers are represented in a variant of 2’s complement which gives
10482 the illusion of an infinite string of sign bits extending to the
10483 left.
10484
10485 Booleans ("bool")
10486 These represent the truth values False and True. The two objects
10487 representing the values "False" and "True" are the only Boolean
10488 objects. The Boolean type is a subtype of the integer type, and
10489 Boolean values behave like the values 0 and 1, respectively, in
10490 almost all contexts, the exception being that when converted to a
10491 string, the strings ""False"" or ""True"" are returned,
10492 respectively.
10493
10494
10495 "numbers.Real" ("float")
10496 ------------------------
10497
10498 These represent machine-level double precision floating-point numbers.
10499 You are at the mercy of the underlying machine architecture (and C or
10500 Java implementation) for the accepted range and handling of overflow.
10501 Python does not support single-precision floating-point numbers; the
10502 savings in processor and memory usage that are usually the reason for
10503 using these are dwarfed by the overhead of using objects in Python, so
10504 there is no reason to complicate the language with two kinds of
10505 floating-point numbers.
10506
10507
10508 "numbers.Complex" ("complex")
10509 -----------------------------
10510
10511 These represent complex numbers as a pair of machine-level double
10512 precision floating-point numbers. The same caveats apply as for
10513 floating-point numbers. The real and imaginary parts of a complex
10514 number "z" can be retrieved through the read-only attributes "z.real"
10515 and "z.imag".
10516
10517
10518 Sequences
10519 =========
10520
10521 These represent finite ordered sets indexed by non-negative numbers.
10522 The built-in function "len()" returns the number of items of a
10523 sequence. When the length of a sequence is *n*, the index set contains
10524 the numbers 0, 1, …, *n*-1. Item *i* of sequence *a* is selected by
10525 "a[i]". Some sequences, including built-in sequences, interpret
10526 negative subscripts by adding the sequence length. For example,
10527 "a[-2]" equals "a[n-2]", the second to last item of sequence a with
10528 length "n".
10529
10530 Sequences also support slicing: "a[i:j]" selects all items with index
10531 *k* such that *i* "<=" *k* "<" *j*. When used as an expression, a
10532 slice is a sequence of the same type. The comment above about negative
10533 indexes also applies to negative slice positions.
10534
10535 Some sequences also support “extended slicing” with a third “step”
10536 parameter: "a[i:j:k]" selects all items of *a* with index *x* where "x
10537 = i + n*k", *n* ">=" "0" and *i* "<=" *x* "<" *j*.
10538
10539 Sequences are distinguished according to their mutability:
10540
10541
10542 Immutable sequences
10543 -------------------
10544
10545 An object of an immutable sequence type cannot change once it is
10546 created. (If the object contains references to other objects, these
10547 other objects may be mutable and may be changed; however, the
10548 collection of objects directly referenced by an immutable object
10549 cannot change.)
10550
10551 The following types are immutable sequences:
10552
10553 Strings
10554 A string is a sequence of values that represent Unicode code
10555 points. All the code points in the range "U+0000 - U+10FFFF" can be
10556 represented in a string. Python doesn’t have a char type; instead,
10557 every code point in the string is represented as a string object
10558 with length "1". The built-in function "ord()" converts a code
10559 point from its string form to an integer in the range "0 - 10FFFF";
10560 "chr()" converts an integer in the range "0 - 10FFFF" to the
10561 corresponding length "1" string object. "str.encode()" can be used
10562 to convert a "str" to "bytes" using the given text encoding, and
10563 "bytes.decode()" can be used to achieve the opposite.
10564
10565 Tuples
10566 The items of a tuple are arbitrary Python objects. Tuples of two or
10567 more items are formed by comma-separated lists of expressions. A
10568 tuple of one item (a ‘singleton’) can be formed by affixing a comma
10569 to an expression (an expression by itself does not create a tuple,
10570 since parentheses must be usable for grouping of expressions). An
10571 empty tuple can be formed by an empty pair of parentheses.
10572
10573 Bytes
10574 A bytes object is an immutable array. The items are 8-bit bytes,
10575 represented by integers in the range 0 <= x < 256. Bytes literals
10576 (like "b'abc'") and the built-in "bytes()" constructor can be used
10577 to create bytes objects. Also, bytes objects can be decoded to
10578 strings via the "decode()" method.
10579
10580
10581 Mutable sequences
10582 -----------------
10583
10584 Mutable sequences can be changed after they are created. The
10585 subscription and slicing notations can be used as the target of
10586 assignment and "del" (delete) statements.
10587
10588 Note:
10589
10590 The "collections" and "array" module provide additional examples of
10591 mutable sequence types.
10592
10593 There are currently two intrinsic mutable sequence types:
10594
10595 Lists
10596 The items of a list are arbitrary Python objects. Lists are formed
10597 by placing a comma-separated list of expressions in square
10598 brackets. (Note that there are no special cases needed to form
10599 lists of length 0 or 1.)
10600
10601 Byte Arrays
10602 A bytearray object is a mutable array. They are created by the
10603 built-in "bytearray()" constructor. Aside from being mutable (and
10604 hence unhashable), byte arrays otherwise provide the same interface
10605 and functionality as immutable "bytes" objects.
10606
10607
10608 Set types
10609 =========
10610
10611 These represent unordered, finite sets of unique, immutable objects.
10612 As such, they cannot be indexed by any subscript. However, they can be
10613 iterated over, and the built-in function "len()" returns the number of
10614 items in a set. Common uses for sets are fast membership testing,
10615 removing duplicates from a sequence, and computing mathematical
10616 operations such as intersection, union, difference, and symmetric
10617 difference.
10618
10619 For set elements, the same immutability rules apply as for dictionary
10620 keys. Note that numeric types obey the normal rules for numeric
10621 comparison: if two numbers compare equal (e.g., "1" and "1.0"), only
10622 one of them can be contained in a set.
10623
10624 There are currently two intrinsic set types:
10625
10626 Sets
10627 These represent a mutable set. They are created by the built-in
10628 "set()" constructor and can be modified afterwards by several
10629 methods, such as "add()".
10630
10631 Frozen sets
10632 These represent an immutable set. They are created by the built-in
10633 "frozenset()" constructor. As a frozenset is immutable and
10634 *hashable*, it can be used again as an element of another set, or
10635 as a dictionary key.
10636
10637
10638 Mappings
10639 ========
10640
10641 These represent finite sets of objects indexed by arbitrary index
10642 sets. The subscript notation "a[k]" selects the item indexed by "k"
10643 from the mapping "a"; this can be used in expressions and as the
10644 target of assignments or "del" statements. The built-in function
10645 "len()" returns the number of items in a mapping.
10646
10647 There is currently a single intrinsic mapping type:
10648
10649
10650 Dictionaries
10651 ------------
10652
10653 These represent finite sets of objects indexed by nearly arbitrary
10654 values. The only types of values not acceptable as keys are values
10655 containing lists or dictionaries or other mutable types that are
10656 compared by value rather than by object identity, the reason being
10657 that the efficient implementation of dictionaries requires a key’s
10658 hash value to remain constant. Numeric types used for keys obey the
10659 normal rules for numeric comparison: if two numbers compare equal
10660 (e.g., "1" and "1.0") then they can be used interchangeably to index
10661 the same dictionary entry.
10662
10663 Dictionaries preserve insertion order, meaning that keys will be
10664 produced in the same order they were added sequentially over the
10665 dictionary. Replacing an existing key does not change the order,
10666 however removing a key and re-inserting it will add it to the end
10667 instead of keeping its old place.
10668
10669 Dictionaries are mutable; they can be created by the "{}" notation
10670 (see section Dictionary displays).
10671
10672 The extension modules "dbm.ndbm" and "dbm.gnu" provide additional
10673 examples of mapping types, as does the "collections" module.
10674
10675 Changed in version 3.7: Dictionaries did not preserve insertion order
10676 in versions of Python before 3.6. In CPython 3.6, insertion order was
10677 preserved, but it was considered an implementation detail at that time
10678 rather than a language guarantee.
10679
10680
10681 Callable types
10682 ==============
10683
10684 These are the types to which the function call operation (see section
10685 Calls) can be applied:
10686
10687
10688 User-defined functions
10689 ----------------------
10690
10691 A user-defined function object is created by a function definition
10692 (see section Function definitions). It should be called with an
10693 argument list containing the same number of items as the function’s
10694 formal parameter list.
10695
10696
10697 Special read-only attributes
10698 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
10699
10700 +----------------------------------------------------+----------------------------------------------------+
10701 | Attribute | Meaning |
10702 |====================================================|====================================================|
10703 | function.__builtins__ | A reference to the "dictionary" that holds the |
10704 | | function’s builtins namespace. Added in version |
10705 | | 3.10. |
10706 +----------------------------------------------------+----------------------------------------------------+
10707 | function.__globals__ | A reference to the "dictionary" that holds the |
10708 | | function’s global variables – the global namespace |
10709 | | of the module in which the function was defined. |
10710 +----------------------------------------------------+----------------------------------------------------+
10711 | function.__closure__ | "None" or a "tuple" of cells that contain bindings |
10712 | | for the names specified in the "co_freevars" |
10713 | | attribute of the function’s "code object". A cell |
10714 | | object has the attribute "cell_contents". This can |
10715 | | be used to get the value of the cell, as well as |
10716 | | set the value. |
10717 +----------------------------------------------------+----------------------------------------------------+
10718
10719
10720 Special writable attributes
10721 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
10722
10723 Most of these attributes check the type of the assigned value:
10724
10725 +----------------------------------------------------+----------------------------------------------------+
10726 | Attribute | Meaning |
10727 |====================================================|====================================================|
10728 | function.__doc__ | The function’s documentation string, or "None" if |
10729 | | unavailable. |
10730 +----------------------------------------------------+----------------------------------------------------+
10731 | function.__name__ | The function’s name. See also: "__name__ |
10732 | | attributes". |
10733 +----------------------------------------------------+----------------------------------------------------+
10734 | function.__qualname__ | The function’s *qualified name*. See also: |
10735 | | "__qualname__ attributes". Added in version 3.3. |
10736 +----------------------------------------------------+----------------------------------------------------+
10737 | function.__module__ | The name of the module the function was defined |
10738 | | in, or "None" if unavailable. |
10739 +----------------------------------------------------+----------------------------------------------------+
10740 | function.__defaults__ | A "tuple" containing default *parameter* values |
10741 | | for those parameters that have defaults, or "None" |
10742 | | if no parameters have a default value. |
10743 +----------------------------------------------------+----------------------------------------------------+
10744 | function.__code__ | The code object representing the compiled function |
10745 | | body. |
10746 +----------------------------------------------------+----------------------------------------------------+
10747 | function.__dict__ | The namespace supporting arbitrary function |
10748 | | attributes. See also: "__dict__ attributes". |
10749 +----------------------------------------------------+----------------------------------------------------+
10750 | function.__annotations__ | A "dictionary" containing annotations of |
10751 | | *parameters*. The keys of the dictionary are the |
10752 | | parameter names, and "'return'" for the return |
10753 | | annotation, if provided. See also: Annotations |
10754 | | Best Practices. |
10755 +----------------------------------------------------+----------------------------------------------------+
10756 | function.__kwdefaults__ | A "dictionary" containing defaults for keyword- |
10757 | | only *parameters*. |
10758 +----------------------------------------------------+----------------------------------------------------+
10759 | function.__type_params__ | A "tuple" containing the type parameters of a |
10760 | | generic function. Added in version 3.12. |
10761 +----------------------------------------------------+----------------------------------------------------+
10762
10763 Function objects also support getting and setting arbitrary
10764 attributes, which can be used, for example, to attach metadata to
10765 functions. Regular attribute dot-notation is used to get and set such
10766 attributes.
10767
10768 **CPython implementation detail:** CPython’s current implementation
10769 only supports function attributes on user-defined functions. Function
10770 attributes on built-in functions may be supported in the future.
10771
10772 Additional information about a function’s definition can be retrieved
10773 from its code object (accessible via the "__code__" attribute).
10774
10775
10776 Instance methods
10777 ----------------
10778
10779 An instance method object combines a class, a class instance and any
10780 callable object (normally a user-defined function).
10781
10782 Special read-only attributes:
10783
10784 +----------------------------------------------------+----------------------------------------------------+
10785 | method.__self__ | Refers to the class instance object to which the |
10786 | | method is bound |
10787 +----------------------------------------------------+----------------------------------------------------+
10788 | method.__func__ | Refers to the original function object |
10789 +----------------------------------------------------+----------------------------------------------------+
10790 | method.__doc__ | The method’s documentation (same as |
10791 | | "method.__func__.__doc__"). A "string" if the |
10792 | | original function had a docstring, else "None". |
10793 +----------------------------------------------------+----------------------------------------------------+
10794 | method.__name__ | The name of the method (same as |
10795 | | "method.__func__.__name__") |
10796 +----------------------------------------------------+----------------------------------------------------+
10797 | method.__module__ | The name of the module the method was defined in, |
10798 | | or "None" if unavailable. |
10799 +----------------------------------------------------+----------------------------------------------------+
10800
10801 Methods also support accessing (but not setting) the arbitrary
10802 function attributes on the underlying function object.
10803
10804 User-defined method objects may be created when getting an attribute
10805 of a class (perhaps via an instance of that class), if that attribute
10806 is a user-defined function object or a "classmethod" object.
10807
10808 When an instance method object is created by retrieving a user-defined
10809 function object from a class via one of its instances, its "__self__"
10810 attribute is the instance, and the method object is said to be
10811 *bound*. The new method’s "__func__" attribute is the original
10812 function object.
10813
10814 When an instance method object is created by retrieving a
10815 "classmethod" object from a class or instance, its "__self__"
10816 attribute is the class itself, and its "__func__" attribute is the
10817 function object underlying the class method.
10818
10819 When an instance method object is called, the underlying function
10820 ("__func__") is called, inserting the class instance ("__self__") in
10821 front of the argument list. For instance, when "C" is a class which
10822 contains a definition for a function "f()", and "x" is an instance of
10823 "C", calling "x.f(1)" is equivalent to calling "C.f(x, 1)".
10824
10825 When an instance method object is derived from a "classmethod" object,
10826 the “class instance” stored in "__self__" will actually be the class
10827 itself, so that calling either "x.f(1)" or "C.f(1)" is equivalent to
10828 calling "f(C,1)" where "f" is the underlying function.
10829
10830 It is important to note that user-defined functions which are
10831 attributes of a class instance are not converted to bound methods;
10832 this *only* happens when the function is an attribute of the class.
10833
10834
10835 Generator functions
10836 -------------------
10837
10838 A function or method which uses the "yield" statement (see section The
10839 yield statement) is called a *generator function*. Such a function,
10840 when called, always returns an *iterator* object which can be used to
10841 execute the body of the function: calling the iterator’s
10842 "iterator.__next__()" method will cause the function to execute until
10843 it provides a value using the "yield" statement. When the function
10844 executes a "return" statement or falls off the end, a "StopIteration"
10845 exception is raised and the iterator will have reached the end of the
10846 set of values to be returned.
10847
10848
10849 Coroutine functions
10850 -------------------
10851
10852 A function or method which is defined using "async def" is called a
10853 *coroutine function*. Such a function, when called, returns a
10854 *coroutine* object. It may contain "await" expressions, as well as
10855 "async with" and "async for" statements. See also the Coroutine
10856 Objects section.
10857
10858
10859 Asynchronous generator functions
10860 --------------------------------
10861
10862 A function or method which is defined using "async def" and which uses
10863 the "yield" statement is called a *asynchronous generator function*.
10864 Such a function, when called, returns an *asynchronous iterator*
10865 object which can be used in an "async for" statement to execute the
10866 body of the function.
10867
10868 Calling the asynchronous iterator’s "aiterator.__anext__" method will
10869 return an *awaitable* which when awaited will execute until it
10870 provides a value using the "yield" expression. When the function
10871 executes an empty "return" statement or falls off the end, a
10872 "StopAsyncIteration" exception is raised and the asynchronous iterator
10873 will have reached the end of the set of values to be yielded.
10874
10875
10876 Built-in functions
10877 ------------------
10878
10879 A built-in function object is a wrapper around a C function. Examples
10880 of built-in functions are "len()" and "math.sin()" ("math" is a
10881 standard built-in module). The number and type of the arguments are
10882 determined by the C function. Special read-only attributes:
10883
10884 * "__doc__" is the function’s documentation string, or "None" if
10885 unavailable. See "function.__doc__".
10886
10887 * "__name__" is the function’s name. See "function.__name__".
10888
10889 * "__self__" is set to "None" (but see the next item).
10890
10891 * "__module__" is the name of the module the function was defined in
10892 or "None" if unavailable. See "function.__module__".
10893
10894
10895 Built-in methods
10896 ----------------
10897
10898 This is really a different disguise of a built-in function, this time
10899 containing an object passed to the C function as an implicit extra
10900 argument. An example of a built-in method is "alist.append()",
10901 assuming *alist* is a list object. In this case, the special read-only
10902 attribute "__self__" is set to the object denoted by *alist*. (The
10903 attribute has the same semantics as it does with "other instance
10904 methods".)
10905
10906
10907 Classes
10908 -------
10909
10910 Classes are callable. These objects normally act as factories for new
10911 instances of themselves, but variations are possible for class types
10912 that override "__new__()". The arguments of the call are passed to
10913 "__new__()" and, in the typical case, to "__init__()" to initialize
10914 the new instance.
10915
10916
10917 Class Instances
10918 ---------------
10919
10920 Instances of arbitrary classes can be made callable by defining a
10921 "__call__()" method in their class.
10922
10923
10924 Modules
10925 =======
10926
10927 Modules are a basic organizational unit of Python code, and are
10928 created by the import system as invoked either by the "import"
10929 statement, or by calling functions such as "importlib.import_module()"
10930 and built-in "__import__()". A module object has a namespace
10931 implemented by a "dictionary" object (this is the dictionary
10932 referenced by the "__globals__" attribute of functions defined in the
10933 module). Attribute references are translated to lookups in this
10934 dictionary, e.g., "m.x" is equivalent to "m.__dict__["x"]". A module
10935 object does not contain the code object used to initialize the module
10936 (since it isn’t needed once the initialization is done).
10937
10938 Attribute assignment updates the module’s namespace dictionary, e.g.,
10939 "m.x = 1" is equivalent to "m.__dict__["x"] = 1".
10940
10941
10942 Import-related attributes on module objects
10943 -------------------------------------------
10944
10945 Module objects have the following attributes that relate to the import
10946 system. When a module is created using the machinery associated with
10947 the import system, these attributes are filled in based on the
10948 module’s *spec*, before the *loader* executes and loads the module.
10949
10950 To create a module dynamically rather than using the import system,
10951 it’s recommended to use "importlib.util.module_from_spec()", which
10952 will set the various import-controlled attributes to appropriate
10953 values. It’s also possible to use the "types.ModuleType" constructor
10954 to create modules directly, but this technique is more error-prone, as
10955 most attributes must be manually set on the module object after it has
10956 been created when using this approach.
10957
10958 Caution:
10959
10960 With the exception of "__name__", it is **strongly** recommended
10961 that you rely on "__spec__" and its attributes instead of any of the
10962 other individual attributes listed in this subsection. Note that
10963 updating an attribute on "__spec__" will not update the
10964 corresponding attribute on the module itself:
10965
10966 >>> import typing
10967 >>> typing.__name__, typing.__spec__.name
10968 ('typing', 'typing')
10969 >>> typing.__spec__.name = 'spelling'
10970 >>> typing.__name__, typing.__spec__.name
10971 ('typing', 'spelling')
10972 >>> typing.__name__ = 'keyboard_smashing'
10973 >>> typing.__name__, typing.__spec__.name
10974 ('keyboard_smashing', 'spelling')
10975
10976 module.__name__
10977
10978 The name used to uniquely identify the module in the import system.
10979 For a directly executed module, this will be set to ""__main__"".
10980
10981 This attribute must be set to the fully qualified name of the
10982 module. It is expected to match the value of
10983 "module.__spec__.name".
10984
10985 module.__spec__
10986
10987 A record of the module’s import-system-related state.
10988
10989 Set to the "module spec" that was used when importing the module.
10990 See Module specs for more details.
10991
10992 Added in version 3.4.
10993
10994 module.__package__
10995
10996 The *package* a module belongs to.
10997
10998 If the module is top-level (that is, not a part of any specific
10999 package) then the attribute should be set to "''" (the empty
11000 string). Otherwise, it should be set to the name of the module’s
11001 package (which can be equal to "module.__name__" if the module
11002 itself is a package). See **PEP 366** for further details.
11003
11004 This attribute is used instead of "__name__" to calculate explicit
11005 relative imports for main modules. It defaults to "None" for
11006 modules created dynamically using the "types.ModuleType"
11007 constructor; use "importlib.util.module_from_spec()" instead to
11008 ensure the attribute is set to a "str".
11009
11010 It is **strongly** recommended that you use
11011 "module.__spec__.parent" instead of "module.__package__".
11012 "__package__" is now only used as a fallback if "__spec__.parent"
11013 is not set, and this fallback path is deprecated.
11014
11015 Changed in version 3.4: This attribute now defaults to "None" for
11016 modules created dynamically using the "types.ModuleType"
11017 constructor. Previously the attribute was optional.
11018
11019 Changed in version 3.6: The value of "__package__" is expected to
11020 be the same as "__spec__.parent". "__package__" is now only used as
11021 a fallback during import resolution if "__spec__.parent" is not
11022 defined.
11023
11024 Changed in version 3.10: "ImportWarning" is raised if an import
11025 resolution falls back to "__package__" instead of
11026 "__spec__.parent".
11027
11028 Changed in version 3.12: Raise "DeprecationWarning" instead of
11029 "ImportWarning" when falling back to "__package__" during import
11030 resolution.
11031
11032 Deprecated since version 3.13, will be removed in version 3.15:
11033 "__package__" will cease to be set or taken into consideration by
11034 the import system or standard library.
11035
11036 module.__loader__
11037
11038 The *loader* object that the import machinery used to load the
11039 module.
11040
11041 This attribute is mostly useful for introspection, but can be used
11042 for additional loader-specific functionality, for example getting
11043 data associated with a loader.
11044
11045 "__loader__" defaults to "None" for modules created dynamically
11046 using the "types.ModuleType" constructor; use
11047 "importlib.util.module_from_spec()" instead to ensure the attribute
11048 is set to a *loader* object.
11049
11050 It is **strongly** recommended that you use
11051 "module.__spec__.loader" instead of "module.__loader__".
11052
11053 Changed in version 3.4: This attribute now defaults to "None" for
11054 modules created dynamically using the "types.ModuleType"
11055 constructor. Previously the attribute was optional.
11056
11057 Deprecated since version 3.12, will be removed in version 3.16:
11058 Setting "__loader__" on a module while failing to set
11059 "__spec__.loader" is deprecated. In Python 3.16, "__loader__" will
11060 cease to be set or taken into consideration by the import system or
11061 the standard library.
11062
11063 module.__path__
11064
11065 A (possibly empty) *sequence* of strings enumerating the locations
11066 where the package’s submodules will be found. Non-package modules
11067 should not have a "__path__" attribute. See __path__ attributes on
11068 modules for more details.
11069
11070 It is **strongly** recommended that you use
11071 "module.__spec__.submodule_search_locations" instead of
11072 "module.__path__".
11073
11074 module.__file__
11075
11076 module.__cached__
11077
11078 "__file__" and "__cached__" are both optional attributes that may
11079 or may not be set. Both attributes should be a "str" when they are
11080 available.
11081
11082 "__file__" indicates the pathname of the file from which the module
11083 was loaded (if loaded from a file), or the pathname of the shared
11084 library file for extension modules loaded dynamically from a shared
11085 library. It might be missing for certain types of modules, such as
11086 C modules that are statically linked into the interpreter, and the
11087 import system may opt to leave it unset if it has no semantic
11088 meaning (for example, a module loaded from a database).
11089
11090 If "__file__" is set then the "__cached__" attribute might also be
11091 set, which is the path to any compiled version of the code (for
11092 example, a byte-compiled file). The file does not need to exist to
11093 set this attribute; the path can simply point to where the compiled
11094 file *would* exist (see **PEP 3147**).
11095
11096 Note that "__cached__" may be set even if "__file__" is not set.
11097 However, that scenario is quite atypical. Ultimately, the *loader*
11098 is what makes use of the module spec provided by the *finder* (from
11099 which "__file__" and "__cached__" are derived). So if a loader can
11100 load from a cached module but otherwise does not load from a file,
11101 that atypical scenario may be appropriate.
11102
11103 It is **strongly** recommended that you use
11104 "module.__spec__.cached" instead of "module.__cached__".
11105
11106 Deprecated since version 3.13, will be removed in version 3.15:
11107 Setting "__cached__" on a module while failing to set
11108 "__spec__.cached" is deprecated. In Python 3.15, "__cached__" will
11109 cease to be set or taken into consideration by the import system or
11110 standard library.
11111
11112
11113 Other writable attributes on module objects
11114 -------------------------------------------
11115
11116 As well as the import-related attributes listed above, module objects
11117 also have the following writable attributes:
11118
11119 module.__doc__
11120
11121 The module’s documentation string, or "None" if unavailable. See
11122 also: "__doc__ attributes".
11123
11124 module.__annotations__
11125
11126 A dictionary containing *variable annotations* collected during
11127 module body execution. For best practices on working with
11128 "__annotations__", please see Annotations Best Practices.
11129
11130
11131 Module dictionaries
11132 -------------------
11133
11134 Module objects also have the following special read-only attribute:
11135
11136 module.__dict__
11137
11138 The module’s namespace as a dictionary object. Uniquely among the
11139 attributes listed here, "__dict__" cannot be accessed as a global
11140 variable from within a module; it can only be accessed as an
11141 attribute on module objects.
11142
11143 **CPython implementation detail:** Because of the way CPython
11144 clears module dictionaries, the module dictionary will be cleared
11145 when the module falls out of scope even if the dictionary still has
11146 live references. To avoid this, copy the dictionary or keep the
11147 module around while using its dictionary directly.
11148
11149
11150 Custom classes
11151 ==============
11152
11153 Custom class types are typically created by class definitions (see
11154 section Class definitions). A class has a namespace implemented by a
11155 dictionary object. Class attribute references are translated to
11156 lookups in this dictionary, e.g., "C.x" is translated to
11157 "C.__dict__["x"]" (although there are a number of hooks which allow
11158 for other means of locating attributes). When the attribute name is
11159 not found there, the attribute search continues in the base classes.
11160 This search of the base classes uses the C3 method resolution order
11161 which behaves correctly even in the presence of ‘diamond’ inheritance
11162 structures where there are multiple inheritance paths leading back to
11163 a common ancestor. Additional details on the C3 MRO used by Python can
11164 be found at The Python 2.3 Method Resolution Order.
11165
11166 When a class attribute reference (for class "C", say) would yield a
11167 class method object, it is transformed into an instance method object
11168 whose "__self__" attribute is "C". When it would yield a
11169 "staticmethod" object, it is transformed into the object wrapped by
11170 the static method object. See section Implementing Descriptors for
11171 another way in which attributes retrieved from a class may differ from
11172 those actually contained in its "__dict__".
11173
11174 Class attribute assignments update the class’s dictionary, never the
11175 dictionary of a base class.
11176
11177 A class object can be called (see above) to yield a class instance
11178 (see below).
11179
11180
11181 Special attributes
11182 ------------------
11183
11184 +----------------------------------------------------+----------------------------------------------------+
11185 | Attribute | Meaning |
11186 |====================================================|====================================================|
11187 | type.__name__ | The class’s name. See also: "__name__ attributes". |
11188 +----------------------------------------------------+----------------------------------------------------+
11189 | type.__qualname__ | The class’s *qualified name*. See also: |
11190 | | "__qualname__ attributes". |
11191 +----------------------------------------------------+----------------------------------------------------+
11192 | type.__module__ | The name of the module in which the class was |
11193 | | defined. |
11194 +----------------------------------------------------+----------------------------------------------------+
11195 | type.__dict__ | A "mapping proxy" providing a read-only view of |
11196 | | the class’s namespace. See also: "__dict__ |
11197 | | attributes". |
11198 +----------------------------------------------------+----------------------------------------------------+
11199 | type.__bases__ | A "tuple" containing the class’s bases. In most |
11200 | | cases, for a class defined as "class X(A, B, C)", |
11201 | | "X.__bases__" will be exactly equal to "(A, B, |
11202 | | C)". |
11203 +----------------------------------------------------+----------------------------------------------------+
11204 | type.__base__ | **CPython implementation detail:** The single base |
11205 | | class in the inheritance chain that is responsible |
11206 | | for the memory layout of instances. This attribute |
11207 | | corresponds to "tp_base" at the C level. |
11208 +----------------------------------------------------+----------------------------------------------------+
11209 | type.__doc__ | The class’s documentation string, or "None" if |
11210 | | undefined. Not inherited by subclasses. |
11211 +----------------------------------------------------+----------------------------------------------------+
11212 | type.__annotations__ | A dictionary containing *variable annotations* |
11213 | | collected during class body execution. For best |
11214 | | practices on working with "__annotations__", |
11215 | | please see Annotations Best Practices. Caution: |
11216 | | Accessing the "__annotations__" attribute of a |
11217 | | class object directly may yield incorrect results |
11218 | | in the presence of metaclasses. In addition, the |
11219 | | attribute may not exist for some classes. Use |
11220 | | "inspect.get_annotations()" to retrieve class |
11221 | | annotations safely. |
11222 +----------------------------------------------------+----------------------------------------------------+
11223 | type.__type_params__ | A "tuple" containing the type parameters of a |
11224 | | generic class. Added in version 3.12. |
11225 +----------------------------------------------------+----------------------------------------------------+
11226 | type.__static_attributes__ | A "tuple" containing names of attributes of this |
11227 | | class which are assigned through "self.X" from any |
11228 | | function in its body. Added in version 3.13. |
11229 +----------------------------------------------------+----------------------------------------------------+
11230 | type.__firstlineno__ | The line number of the first line of the class |
11231 | | definition, including decorators. Setting the |
11232 | | "__module__" attribute removes the |
11233 | | "__firstlineno__" item from the type’s dictionary. |
11234 | | Added in version 3.13. |
11235 +----------------------------------------------------+----------------------------------------------------+
11236 | type.__mro__ | The "tuple" of classes that are considered when |
11237 | | looking for base classes during method resolution. |
11238 +----------------------------------------------------+----------------------------------------------------+
11239
11240
11241 Special methods
11242 ---------------
11243
11244 In addition to the special attributes described above, all Python
11245 classes also have the following two methods available:
11246
11247 type.mro()
11248
11249 This method can be overridden by a metaclass to customize the
11250 method resolution order for its instances. It is called at class
11251 instantiation, and its result is stored in "__mro__".
11252
11253 type.__subclasses__()
11254
11255 Each class keeps a list of weak references to its immediate
11256 subclasses. This method returns a list of all those references
11257 still alive. The list is in definition order. Example:
11258
11259 >>> class A: pass
11260 >>> class B(A): pass
11261 >>> A.__subclasses__()
11262 [<class 'B'>]
11263
11264
11265 Class instances
11266 ===============
11267
11268 A class instance is created by calling a class object (see above). A
11269 class instance has a namespace implemented as a dictionary which is
11270 the first place in which attribute references are searched. When an
11271 attribute is not found there, and the instance’s class has an
11272 attribute by that name, the search continues with the class
11273 attributes. If a class attribute is found that is a user-defined
11274 function object, it is transformed into an instance method object
11275 whose "__self__" attribute is the instance. Static method and class
11276 method objects are also transformed; see above under “Classes”. See
11277 section Implementing Descriptors for another way in which attributes
11278 of a class retrieved via its instances may differ from the objects
11279 actually stored in the class’s "__dict__". If no class attribute is
11280 found, and the object’s class has a "__getattr__()" method, that is
11281 called to satisfy the lookup.
11282
11283 Attribute assignments and deletions update the instance’s dictionary,
11284 never a class’s dictionary. If the class has a "__setattr__()" or
11285 "__delattr__()" method, this is called instead of updating the
11286 instance dictionary directly.
11287
11288 Class instances can pretend to be numbers, sequences, or mappings if
11289 they have methods with certain special names. See section Special
11290 method names.
11291
11292
11293 Special attributes
11294 ------------------
11295
11296 object.__class__
11297
11298 The class to which a class instance belongs.
11299
11300 object.__dict__
11301
11302 A dictionary or other mapping object used to store an object’s
11303 (writable) attributes. Not all instances have a "__dict__"
11304 attribute; see the section on __slots__ for more details.
11305
11306
11307 I/O objects (also known as file objects)
11308 ========================================
11309
11310 A *file object* represents an open file. Various shortcuts are
11311 available to create file objects: the "open()" built-in function, and
11312 also "os.popen()", "os.fdopen()", and the "makefile()" method of
11313 socket objects (and perhaps by other functions or methods provided by
11314 extension modules).
11315
11316 The objects "sys.stdin", "sys.stdout" and "sys.stderr" are initialized
11317 to file objects corresponding to the interpreter’s standard input,
11318 output and error streams; they are all open in text mode and therefore
11319 follow the interface defined by the "io.TextIOBase" abstract class.
11320
11321
11322 Internal types
11323 ==============
11324
11325 A few types used internally by the interpreter are exposed to the
11326 user. Their definitions may change with future versions of the
11327 interpreter, but they are mentioned here for completeness.
11328
11329
11330 Code objects
11331 ------------
11332
11333 Code objects represent *byte-compiled* executable Python code, or
11334 *bytecode*. The difference between a code object and a function object
11335 is that the function object contains an explicit reference to the
11336 function’s globals (the module in which it was defined), while a code
11337 object contains no context; also the default argument values are
11338 stored in the function object, not in the code object (because they
11339 represent values calculated at run-time). Unlike function objects,
11340 code objects are immutable and contain no references (directly or
11341 indirectly) to mutable objects.
11342
11343
11344 Special read-only attributes
11345 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
11346
11347 +----------------------------------------------------+----------------------------------------------------+
11348 | codeobject.co_name | The function name |
11349 +----------------------------------------------------+----------------------------------------------------+
11350 | codeobject.co_qualname | The fully qualified function name Added in |
11351 | | version 3.11. |
11352 +----------------------------------------------------+----------------------------------------------------+
11353 | codeobject.co_argcount | The total number of positional *parameters* |
11354 | | (including positional-only parameters and |
11355 | | parameters with default values) that the function |
11356 | | has |
11357 +----------------------------------------------------+----------------------------------------------------+
11358 | codeobject.co_posonlyargcount | The number of positional-only *parameters* |
11359 | | (including arguments with default values) that the |
11360 | | function has |
11361 +----------------------------------------------------+----------------------------------------------------+
11362 | codeobject.co_kwonlyargcount | The number of keyword-only *parameters* (including |
11363 | | arguments with default values) that the function |
11364 | | has |
11365 +----------------------------------------------------+----------------------------------------------------+
11366 | codeobject.co_nlocals | The number of local variables used by the function |
11367 | | (including parameters) |
11368 +----------------------------------------------------+----------------------------------------------------+
11369 | codeobject.co_varnames | A "tuple" containing the names of the local |
11370 | | variables in the function (starting with the |
11371 | | parameter names) |
11372 +----------------------------------------------------+----------------------------------------------------+
11373 | codeobject.co_cellvars | A "tuple" containing the names of local variables |
11374 | | that are referenced from at least one *nested |
11375 | | scope* inside the function |
11376 +----------------------------------------------------+----------------------------------------------------+
11377 | codeobject.co_freevars | A "tuple" containing the names of *free (closure) |
11378 | | variables* that a *nested scope* references in an |
11379 | | outer scope. See also "function.__closure__". |
11380 | | Note: references to global and builtin names are |
11381 | | *not* included. |
11382 +----------------------------------------------------+----------------------------------------------------+
11383 | codeobject.co_code | A string representing the sequence of *bytecode* |
11384 | | instructions in the function |
11385 +----------------------------------------------------+----------------------------------------------------+
11386 | codeobject.co_consts | A "tuple" containing the literals used by the |
11387 | | *bytecode* in the function |
11388 +----------------------------------------------------+----------------------------------------------------+
11389 | codeobject.co_names | A "tuple" containing the names used by the |
11390 | | *bytecode* in the function |
11391 +----------------------------------------------------+----------------------------------------------------+
11392 | codeobject.co_filename | The name of the file from which the code was |
11393 | | compiled |
11394 +----------------------------------------------------+----------------------------------------------------+
11395 | codeobject.co_firstlineno | The line number of the first line of the function |
11396 +----------------------------------------------------+----------------------------------------------------+
11397 | codeobject.co_lnotab | A string encoding the mapping from *bytecode* |
11398 | | offsets to line numbers. For details, see the |
11399 | | source code of the interpreter. Deprecated since |
11400 | | version 3.12: This attribute of code objects is |
11401 | | deprecated, and may be removed in Python 3.15. |
11402 +----------------------------------------------------+----------------------------------------------------+
11403 | codeobject.co_stacksize | The required stack size of the code object |
11404 +----------------------------------------------------+----------------------------------------------------+
11405 | codeobject.co_flags | An "integer" encoding a number of flags for the |
11406 | | interpreter. |
11407 +----------------------------------------------------+----------------------------------------------------+
11408
11409 The following flag bits are defined for "co_flags": bit "0x04" is set
11410 if the function uses the "*arguments" syntax to accept an arbitrary
11411 number of positional arguments; bit "0x08" is set if the function uses
11412 the "**keywords" syntax to accept arbitrary keyword arguments; bit
11413 "0x20" is set if the function is a generator. See Code Objects Bit
11414 Flags for details on the semantics of each flags that might be
11415 present.
11416
11417 Future feature declarations (for example, "from __future__ import
11418 division") also use bits in "co_flags" to indicate whether a code
11419 object was compiled with a particular feature enabled. See
11420 "compiler_flag".
11421
11422 Other bits in "co_flags" are reserved for internal use.
11423
11424 If a code object represents a function, the first item in "co_consts"
11425 is the documentation string of the function, or "None" if undefined.
11426
11427
11428 Methods on code objects
11429 ~~~~~~~~~~~~~~~~~~~~~~~
11430
11431 codeobject.co_positions()
11432
11433 Returns an iterable over the source code positions of each
11434 *bytecode* instruction in the code object.
11435
11436 The iterator returns "tuple"s containing the "(start_line,
11437 end_line, start_column, end_column)". The *i-th* tuple corresponds
11438 to the position of the source code that compiled to the *i-th* code
11439 unit. Column information is 0-indexed utf-8 byte offsets on the
11440 given source line.
11441
11442 This positional information can be missing. A non-exhaustive lists
11443 of cases where this may happen:
11444
11445 * Running the interpreter with "-X" "no_debug_ranges".
11446
11447 * Loading a pyc file compiled while using "-X" "no_debug_ranges".
11448
11449 * Position tuples corresponding to artificial instructions.
11450
11451 * Line and column numbers that can’t be represented due to
11452 implementation specific limitations.
11453
11454 When this occurs, some or all of the tuple elements can be "None".
11455
11456 Added in version 3.11.
11457
11458 Note:
11459
11460 This feature requires storing column positions in code objects
11461 which may result in a small increase of disk usage of compiled
11462 Python files or interpreter memory usage. To avoid storing the
11463 extra information and/or deactivate printing the extra traceback
11464 information, the "-X" "no_debug_ranges" command line flag or the
11465 "PYTHONNODEBUGRANGES" environment variable can be used.
11466
11467 codeobject.co_lines()
11468
11469 Returns an iterator that yields information about successive ranges
11470 of *bytecode*s. Each item yielded is a "(start, end, lineno)"
11471 "tuple":
11472
11473 * "start" (an "int") represents the offset (inclusive) of the start
11474 of the *bytecode* range
11475
11476 * "end" (an "int") represents the offset (exclusive) of the end of
11477 the *bytecode* range
11478
11479 * "lineno" is an "int" representing the line number of the
11480 *bytecode* range, or "None" if the bytecodes in the given range
11481 have no line number
11482
11483 The items yielded will have the following properties:
11484
11485 * The first range yielded will have a "start" of 0.
11486
11487 * The "(start, end)" ranges will be non-decreasing and consecutive.
11488 That is, for any pair of "tuple"s, the "start" of the second will
11489 be equal to the "end" of the first.
11490
11491 * No range will be backwards: "end >= start" for all triples.
11492
11493 * The last "tuple" yielded will have "end" equal to the size of the
11494 *bytecode*.
11495
11496 Zero-width ranges, where "start == end", are allowed. Zero-width
11497 ranges are used for lines that are present in the source code, but
11498 have been eliminated by the *bytecode* compiler.
11499
11500 Added in version 3.10.
11501
11502 See also:
11503
11504 **PEP 626** - Precise line numbers for debugging and other tools.
11505 The PEP that introduced the "co_lines()" method.
11506
11507 codeobject.replace(**kwargs)
11508
11509 Return a copy of the code object with new values for the specified
11510 fields.
11511
11512 Code objects are also supported by the generic function
11513 "copy.replace()".
11514
11515 Added in version 3.8.
11516
11517
11518 Frame objects
11519 -------------
11520
11521 Frame objects represent execution frames. They may occur in traceback
11522 objects, and are also passed to registered trace functions.
11523
11524
11525 Special read-only attributes
11526 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
11527
11528 +----------------------------------------------------+----------------------------------------------------+
11529 | frame.f_back | Points to the previous stack frame (towards the |
11530 | | caller), or "None" if this is the bottom stack |
11531 | | frame |
11532 +----------------------------------------------------+----------------------------------------------------+
11533 | frame.f_code | The code object being executed in this frame. |
11534 | | Accessing this attribute raises an auditing event |
11535 | | "object.__getattr__" with arguments "obj" and |
11536 | | ""f_code"". |
11537 +----------------------------------------------------+----------------------------------------------------+
11538 | frame.f_locals | The mapping used by the frame to look up local |
11539 | | variables. If the frame refers to an *optimized |
11540 | | scope*, this may return a write-through proxy |
11541 | | object. Changed in version 3.13: Return a proxy |
11542 | | for optimized scopes. |
11543 +----------------------------------------------------+----------------------------------------------------+
11544 | frame.f_globals | The dictionary used by the frame to look up global |
11545 | | variables |
11546 +----------------------------------------------------+----------------------------------------------------+
11547 | frame.f_builtins | The dictionary used by the frame to look up built- |
11548 | | in (intrinsic) names |
11549 +----------------------------------------------------+----------------------------------------------------+
11550 | frame.f_lasti | The “precise instruction” of the frame object |
11551 | | (this is an index into the *bytecode* string of |
11552 | | the code object) |
11553 +----------------------------------------------------+----------------------------------------------------+
11554
11555
11556 Special writable attributes
11557 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
11558
11559 +----------------------------------------------------+----------------------------------------------------+
11560 | frame.f_trace | If not "None", this is a function called for |
11561 | | various events during code execution (this is used |
11562 | | by debuggers). Normally an event is triggered for |
11563 | | each new source line (see "f_trace_lines"). |
11564 +----------------------------------------------------+----------------------------------------------------+
11565 | frame.f_trace_lines | Set this attribute to "False" to disable |
11566 | | triggering a tracing event for each source line. |
11567 +----------------------------------------------------+----------------------------------------------------+
11568 | frame.f_trace_opcodes | Set this attribute to "True" to allow per-opcode |
11569 | | events to be requested. Note that this may lead to |
11570 | | undefined interpreter behaviour if exceptions |
11571 | | raised by the trace function escape to the |
11572 | | function being traced. |
11573 +----------------------------------------------------+----------------------------------------------------+
11574 | frame.f_lineno | The current line number of the frame – writing to |
11575 | | this from within a trace function jumps to the |
11576 | | given line (only for the bottom-most frame). A |
11577 | | debugger can implement a Jump command (aka Set |
11578 | | Next Statement) by writing to this attribute. |
11579 +----------------------------------------------------+----------------------------------------------------+
11580
11581
11582 Frame object methods
11583 ~~~~~~~~~~~~~~~~~~~~
11584
11585 Frame objects support one method:
11586
11587 frame.clear()
11588
11589 This method clears all references to local variables held by the
11590 frame. Also, if the frame belonged to a *generator*, the generator
11591 is finalized. This helps break reference cycles involving frame
11592 objects (for example when catching an exception and storing its
11593 traceback for later use).
11594
11595 "RuntimeError" is raised if the frame is currently executing or
11596 suspended.
11597
11598 Added in version 3.4.
11599
11600 Changed in version 3.13: Attempting to clear a suspended frame
11601 raises "RuntimeError" (as has always been the case for executing
11602 frames).
11603
11604
11605 Traceback objects
11606 -----------------
11607
11608 Traceback objects represent the stack trace of an exception. A
11609 traceback object is implicitly created when an exception occurs, and
11610 may also be explicitly created by calling "types.TracebackType".
11611
11612 Changed in version 3.7: Traceback objects can now be explicitly
11613 instantiated from Python code.
11614
11615 For implicitly created tracebacks, when the search for an exception
11616 handler unwinds the execution stack, at each unwound level a traceback
11617 object is inserted in front of the current traceback. When an
11618 exception handler is entered, the stack trace is made available to the
11619 program. (See section The try statement.) It is accessible as the
11620 third item of the tuple returned by "sys.exc_info()", and as the
11621 "__traceback__" attribute of the caught exception.
11622
11623 When the program contains no suitable handler, the stack trace is
11624 written (nicely formatted) to the standard error stream; if the
11625 interpreter is interactive, it is also made available to the user as
11626 "sys.last_traceback".
11627
11628 For explicitly created tracebacks, it is up to the creator of the
11629 traceback to determine how the "tb_next" attributes should be linked
11630 to form a full stack trace.
11631
11632 Special read-only attributes:
11633
11634 +----------------------------------------------------+----------------------------------------------------+
11635 | traceback.tb_frame | Points to the execution frame of the current |
11636 | | level. Accessing this attribute raises an |
11637 | | auditing event "object.__getattr__" with arguments |
11638 | | "obj" and ""tb_frame"". |
11639 +----------------------------------------------------+----------------------------------------------------+
11640 | traceback.tb_lineno | Gives the line number where the exception occurred |
11641 +----------------------------------------------------+----------------------------------------------------+
11642 | traceback.tb_lasti | Indicates the “precise instruction”. |
11643 +----------------------------------------------------+----------------------------------------------------+
11644
11645 The line number and last instruction in the traceback may differ from
11646 the line number of its frame object if the exception occurred in a
11647 "try" statement with no matching except clause or with a "finally"
11648 clause.
11649
11650 traceback.tb_next
11651
11652 The special writable attribute "tb_next" is the next level in the
11653 stack trace (towards the frame where the exception occurred), or
11654 "None" if there is no next level.
11655
11656 Changed in version 3.7: This attribute is now writable
11657
11658
11659 Slice objects
11660 -------------
11661
11662 Slice objects are used to represent slices for "__getitem__()"
11663 methods. They are also created by the built-in "slice()" function.
11664
11665 Special read-only attributes: "start" is the lower bound; "stop" is
11666 the upper bound; "step" is the step value; each is "None" if omitted.
11667 These attributes can have any type.
11668
11669 Slice objects support one method:
11670
11671 slice.indices(self, length)
11672
11673 This method takes a single integer argument *length* and computes
11674 information about the slice that the slice object would describe if
11675 applied to a sequence of *length* items. It returns a tuple of
11676 three integers; respectively these are the *start* and *stop*
11677 indices and the *step* or stride length of the slice. Missing or
11678 out-of-bounds indices are handled in a manner consistent with
11679 regular slices.
11680
11681
11682 Static method objects
11683 ---------------------
11684
11685 Static method objects provide a way of defeating the transformation of
11686 function objects to method objects described above. A static method
11687 object is a wrapper around any other object, usually a user-defined
11688 method object. When a static method object is retrieved from a class
11689 or a class instance, the object actually returned is the wrapped
11690 object, which is not subject to any further transformation. Static
11691 method objects are also callable. Static method objects are created by
11692 the built-in "staticmethod()" constructor.
11693
11694
11695 Class method objects
11696 --------------------
11697
11698 A class method object, like a static method object, is a wrapper
11699 around another object that alters the way in which that object is
11700 retrieved from classes and class instances. The behaviour of class
11701 method objects upon such retrieval is described above, under “instance
11702 methods”. Class method objects are created by the built-in
11703 "classmethod()" constructor.
11704 ''',
11705 'typesfunctions': r'''Functions
11706 *********
11707
11708 Function objects are created by function definitions. The only
11709 operation on a function object is to call it: "func(argument-list)".
11710
11711 There are really two flavors of function objects: built-in functions
11712 and user-defined functions. Both support the same operation (to call
11713 the function), but the implementation is different, hence the
11714 different object types.
11715
11716 See Function definitions for more information.
11717 ''',
11718 'typesmapping': r'''Mapping Types — "dict"
11719 **********************
11720
11721 A *mapping* object maps *hashable* values to arbitrary objects.
11722 Mappings are mutable objects. There is currently only one standard
11723 mapping type, the *dictionary*. (For other containers see the built-
11724 in "list", "set", and "tuple" classes, and the "collections" module.)
11725
11726 A dictionary’s keys are *almost* arbitrary values. Values that are
11727 not *hashable*, that is, values containing lists, dictionaries or
11728 other mutable types (that are compared by value rather than by object
11729 identity) may not be used as keys. Values that compare equal (such as
11730 "1", "1.0", and "True") can be used interchangeably to index the same
11731 dictionary entry.
11732
11733 class dict(**kwargs)
11734 class dict(mapping, /, **kwargs)
11735 class dict(iterable, /, **kwargs)
11736
11737 Return a new dictionary initialized from an optional positional
11738 argument and a possibly empty set of keyword arguments.
11739
11740 Dictionaries can be created by several means:
11741
11742 * Use a comma-separated list of "key: value" pairs within braces:
11743 "{'jack': 4098, 'sjoerd': 4127}" or "{4098: 'jack', 4127:
11744 'sjoerd'}"
11745
11746 * Use a dict comprehension: "{}", "{x: x ** 2 for x in range(10)}"
11747
11748 * Use the type constructor: "dict()", "dict([('foo', 100), ('bar',
11749 200)])", "dict(foo=100, bar=200)"
11750
11751 If no positional argument is given, an empty dictionary is created.
11752 If a positional argument is given and it defines a "keys()" method,
11753 a dictionary is created by calling "__getitem__()" on the argument
11754 with each returned key from the method. Otherwise, the positional
11755 argument must be an *iterable* object. Each item in the iterable
11756 must itself be an iterable with exactly two elements. The first
11757 element of each item becomes a key in the new dictionary, and the
11758 second element the corresponding value. If a key occurs more than
11759 once, the last value for that key becomes the corresponding value
11760 in the new dictionary.
11761
11762 If keyword arguments are given, the keyword arguments and their
11763 values are added to the dictionary created from the positional
11764 argument. If a key being added is already present, the value from
11765 the keyword argument replaces the value from the positional
11766 argument.
11767
11768 Dictionaries compare equal if and only if they have the same "(key,
11769 value)" pairs (regardless of ordering). Order comparisons (‘<’,
11770 ‘<=’, ‘>=’, ‘>’) raise "TypeError". To illustrate dictionary
11771 creation and equality, the following examples all return a
11772 dictionary equal to "{"one": 1, "two": 2, "three": 3}":
11773
11774 >>> a = dict(one=1, two=2, three=3)
11775 >>> b = {'one': 1, 'two': 2, 'three': 3}
11776 >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
11777 >>> d = dict([('two', 2), ('one', 1), ('three', 3)])
11778 >>> e = dict({'three': 3, 'one': 1, 'two': 2})
11779 >>> f = dict({'one': 1, 'three': 3}, two=2)
11780 >>> a == b == c == d == e == f
11781 True
11782
11783 Providing keyword arguments as in the first example only works for
11784 keys that are valid Python identifiers. Otherwise, any valid keys
11785 can be used.
11786
11787 Dictionaries preserve insertion order. Note that updating a key
11788 does not affect the order. Keys added after deletion are inserted
11789 at the end.
11790
11791 >>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
11792 >>> d
11793 {'one': 1, 'two': 2, 'three': 3, 'four': 4}
11794 >>> list(d)
11795 ['one', 'two', 'three', 'four']
11796 >>> list(d.values())
11797 [1, 2, 3, 4]
11798 >>> d["one"] = 42
11799 >>> d
11800 {'one': 42, 'two': 2, 'three': 3, 'four': 4}
11801 >>> del d["two"]
11802 >>> d["two"] = None
11803 >>> d
11804 {'one': 42, 'three': 3, 'four': 4, 'two': None}
11805
11806 Changed in version 3.7: Dictionary order is guaranteed to be
11807 insertion order. This behavior was an implementation detail of
11808 CPython from 3.6.
11809
11810 These are the operations that dictionaries support (and therefore,
11811 custom mapping types should support too):
11812
11813 list(d)
11814
11815 Return a list of all the keys used in the dictionary *d*.
11816
11817 len(d)
11818
11819 Return the number of items in the dictionary *d*.
11820
11821 d[key]
11822
11823 Return the item of *d* with key *key*. Raises a "KeyError" if
11824 *key* is not in the map.
11825
11826 If a subclass of dict defines a method "__missing__()" and *key*
11827 is not present, the "d[key]" operation calls that method with
11828 the key *key* as argument. The "d[key]" operation then returns
11829 or raises whatever is returned or raised by the
11830 "__missing__(key)" call. No other operations or methods invoke
11831 "__missing__()". If "__missing__()" is not defined, "KeyError"
11832 is raised. "__missing__()" must be a method; it cannot be an
11833 instance variable:
11834
11835 >>> class Counter(dict):
11836 ... def __missing__(self, key):
11837 ... return 0
11838 ...
11839 >>> c = Counter()
11840 >>> c['red']
11841 0
11842 >>> c['red'] += 1
11843 >>> c['red']
11844 1
11845
11846 The example above shows part of the implementation of
11847 "collections.Counter". A different "__missing__()" method is
11848 used by "collections.defaultdict".
11849
11850 d[key] = value
11851
11852 Set "d[key]" to *value*.
11853
11854 del d[key]
11855
11856 Remove "d[key]" from *d*. Raises a "KeyError" if *key* is not
11857 in the map.
11858
11859 key in d
11860
11861 Return "True" if *d* has a key *key*, else "False".
11862
11863 key not in d
11864
11865 Equivalent to "not key in d".
11866
11867 iter(d)
11868
11869 Return an iterator over the keys of the dictionary. This is a
11870 shortcut for "iter(d.keys())".
11871
11872 clear()
11873
11874 Remove all items from the dictionary.
11875
11876 copy()
11877
11878 Return a shallow copy of the dictionary.
11879
11880 classmethod fromkeys(iterable, value=None, /)
11881
11882 Create a new dictionary with keys from *iterable* and values set
11883 to *value*.
11884
11885 "fromkeys()" is a class method that returns a new dictionary.
11886 *value* defaults to "None". All of the values refer to just a
11887 single instance, so it generally doesn’t make sense for *value*
11888 to be a mutable object such as an empty list. To get distinct
11889 values, use a dict comprehension instead.
11890
11891 get(key, default=None, /)
11892
11893 Return the value for *key* if *key* is in the dictionary, else
11894 *default*. If *default* is not given, it defaults to "None", so
11895 that this method never raises a "KeyError".
11896
11897 items()
11898
11899 Return a new view of the dictionary’s items ("(key, value)"
11900 pairs). See the documentation of view objects.
11901
11902 keys()
11903
11904 Return a new view of the dictionary’s keys. See the
11905 documentation of view objects.
11906
11907 pop(key, /)
11908 pop(key, default, /)
11909
11910 If *key* is in the dictionary, remove it and return its value,
11911 else return *default*. If *default* is not given and *key* is
11912 not in the dictionary, a "KeyError" is raised.
11913
11914 popitem()
11915
11916 Remove and return a "(key, value)" pair from the dictionary.
11917 Pairs are returned in LIFO (last-in, first-out) order.
11918
11919 "popitem()" is useful to destructively iterate over a
11920 dictionary, as often used in set algorithms. If the dictionary
11921 is empty, calling "popitem()" raises a "KeyError".
11922
11923 Changed in version 3.7: LIFO order is now guaranteed. In prior
11924 versions, "popitem()" would return an arbitrary key/value pair.
11925
11926 reversed(d)
11927
11928 Return a reverse iterator over the keys of the dictionary. This
11929 is a shortcut for "reversed(d.keys())".
11930
11931 Added in version 3.8.
11932
11933 setdefault(key, default=None, /)
11934
11935 If *key* is in the dictionary, return its value. If not, insert
11936 *key* with a value of *default* and return *default*. *default*
11937 defaults to "None".
11938
11939 update(**kwargs)
11940 update(mapping, /, **kwargs)
11941 update(iterable, /, **kwargs)
11942
11943 Update the dictionary with the key/value pairs from *mapping* or
11944 *iterable* and *kwargs*, overwriting existing keys. Return
11945 "None".
11946
11947 "update()" accepts either another object with a "keys()" method
11948 (in which case "__getitem__()" is called with every key returned
11949 from the method) or an iterable of key/value pairs (as tuples or
11950 other iterables of length two). If keyword arguments are
11951 specified, the dictionary is then updated with those key/value
11952 pairs: "d.update(red=1, blue=2)".
11953
11954 values()
11955
11956 Return a new view of the dictionary’s values. See the
11957 documentation of view objects.
11958
11959 An equality comparison between one "dict.values()" view and
11960 another will always return "False". This also applies when
11961 comparing "dict.values()" to itself:
11962
11963 >>> d = {'a': 1}
11964 >>> d.values() == d.values()
11965 False
11966
11967 d | other
11968
11969 Create a new dictionary with the merged keys and values of *d*
11970 and *other*, which must both be dictionaries. The values of
11971 *other* take priority when *d* and *other* share keys.
11972
11973 Added in version 3.9.
11974
11975 d |= other
11976
11977 Update the dictionary *d* with keys and values from *other*,
11978 which may be either a *mapping* or an *iterable* of key/value
11979 pairs. The values of *other* take priority when *d* and *other*
11980 share keys.
11981
11982 Added in version 3.9.
11983
11984 Dictionaries and dictionary views are reversible.
11985
11986 >>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
11987 >>> d
11988 {'one': 1, 'two': 2, 'three': 3, 'four': 4}
11989 >>> list(reversed(d))
11990 ['four', 'three', 'two', 'one']
11991 >>> list(reversed(d.values()))
11992 [4, 3, 2, 1]
11993 >>> list(reversed(d.items()))
11994 [('four', 4), ('three', 3), ('two', 2), ('one', 1)]
11995
11996 Changed in version 3.8: Dictionaries are now reversible.
11997
11998 See also:
11999
12000 "types.MappingProxyType" can be used to create a read-only view of a
12001 "dict".
12002
12003
12004 Dictionary view objects
12005 =======================
12006
12007 The objects returned by "dict.keys()", "dict.values()" and
12008 "dict.items()" are *view objects*. They provide a dynamic view on the
12009 dictionary’s entries, which means that when the dictionary changes,
12010 the view reflects these changes.
12011
12012 Dictionary views can be iterated over to yield their respective data,
12013 and support membership tests:
12014
12015 len(dictview)
12016
12017 Return the number of entries in the dictionary.
12018
12019 iter(dictview)
12020
12021 Return an iterator over the keys, values or items (represented as
12022 tuples of "(key, value)") in the dictionary.
12023
12024 Keys and values are iterated over in insertion order. This allows
12025 the creation of "(value, key)" pairs using "zip()": "pairs =
12026 zip(d.values(), d.keys())". Another way to create the same list is
12027 "pairs = [(v, k) for (k, v) in d.items()]".
12028
12029 Iterating views while adding or deleting entries in the dictionary
12030 may raise a "RuntimeError" or fail to iterate over all entries.
12031
12032 Changed in version 3.7: Dictionary order is guaranteed to be
12033 insertion order.
12034
12035 x in dictview
12036
12037 Return "True" if *x* is in the underlying dictionary’s keys, values
12038 or items (in the latter case, *x* should be a "(key, value)"
12039 tuple).
12040
12041 reversed(dictview)
12042
12043 Return a reverse iterator over the keys, values or items of the
12044 dictionary. The view will be iterated in reverse order of the
12045 insertion.
12046
12047 Changed in version 3.8: Dictionary views are now reversible.
12048
12049 dictview.mapping
12050
12051 Return a "types.MappingProxyType" that wraps the original
12052 dictionary to which the view refers.
12053
12054 Added in version 3.10.
12055
12056 Keys views are set-like since their entries are unique and *hashable*.
12057 Items views also have set-like operations since the (key, value) pairs
12058 are unique and the keys are hashable. If all values in an items view
12059 are hashable as well, then the items view can interoperate with other
12060 sets. (Values views are not treated as set-like since the entries are
12061 generally not unique.) For set-like views, all of the operations
12062 defined for the abstract base class "collections.abc.Set" are
12063 available (for example, "==", "<", or "^"). While using set
12064 operators, set-like views accept any iterable as the other operand,
12065 unlike sets which only accept sets as the input.
12066
12067 An example of dictionary view usage:
12068
12069 >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
12070 >>> keys = dishes.keys()
12071 >>> values = dishes.values()
12072
12073 >>> # iteration
12074 >>> n = 0
12075 >>> for val in values:
12076 ... n += val
12077 ...
12078 >>> print(n)
12079 504
12080
12081 >>> # keys and values are iterated over in the same order (insertion order)
12082 >>> list(keys)
12083 ['eggs', 'sausage', 'bacon', 'spam']
12084 >>> list(values)
12085 [2, 1, 1, 500]
12086
12087 >>> # view objects are dynamic and reflect dict changes
12088 >>> del dishes['eggs']
12089 >>> del dishes['sausage']
12090 >>> list(keys)
12091 ['bacon', 'spam']
12092
12093 >>> # set operations
12094 >>> keys & {'eggs', 'bacon', 'salad'}
12095 {'bacon'}
12096 >>> keys ^ {'sausage', 'juice'} == {'juice', 'sausage', 'bacon', 'spam'}
12097 True
12098 >>> keys | ['juice', 'juice', 'juice'] == {'bacon', 'spam', 'juice'}
12099 True
12100
12101 >>> # get back a read-only proxy for the original dictionary
12102 >>> values.mapping
12103 mappingproxy({'bacon': 1, 'spam': 500})
12104 >>> values.mapping['spam']
12105 500
12106 ''',
12107 'typesmethods': r'''Methods
12108 *******
12109
12110 Methods are functions that are called using the attribute notation.
12111 There are two flavors: built-in methods (such as "append()" on lists)
12112 and class instance method. Built-in methods are described with the
12113 types that support them.
12114
12115 If you access a method (a function defined in a class namespace)
12116 through an instance, you get a special object: a *bound method* (also
12117 called instance method) object. When called, it will add the "self"
12118 argument to the argument list. Bound methods have two special read-
12119 only attributes: "m.__self__" is the object on which the method
12120 operates, and "m.__func__" is the function implementing the method.
12121 Calling "m(arg-1, arg-2, ..., arg-n)" is completely equivalent to
12122 calling "m.__func__(m.__self__, arg-1, arg-2, ..., arg-n)".
12123
12124 Like function objects, bound method objects support getting arbitrary
12125 attributes. However, since method attributes are actually stored on
12126 the underlying function object ("method.__func__"), setting method
12127 attributes on bound methods is disallowed. Attempting to set an
12128 attribute on a method results in an "AttributeError" being raised. In
12129 order to set a method attribute, you need to explicitly set it on the
12130 underlying function object:
12131
12132 >>> class C:
12133 ... def method(self):
12134 ... pass
12135 ...
12136 >>> c = C()
12137 >>> c.method.whoami = 'my name is method' # can't set on the method
12138 Traceback (most recent call last):
12139 File "<stdin>", line 1, in <module>
12140 AttributeError: 'method' object has no attribute 'whoami'
12141 >>> c.method.__func__.whoami = 'my name is method'
12142 >>> c.method.whoami
12143 'my name is method'
12144
12145 See Instance methods for more information.
12146 ''',
12147 'typesmodules': r'''Modules
12148 *******
12149
12150 The only special operation on a module is attribute access: "m.name",
12151 where *m* is a module and *name* accesses a name defined in *m*’s
12152 symbol table. Module attributes can be assigned to. (Note that the
12153 "import" statement is not, strictly speaking, an operation on a module
12154 object; "import foo" does not require a module object named *foo* to
12155 exist, rather it requires an (external) *definition* for a module
12156 named *foo* somewhere.)
12157
12158 A special attribute of every module is "__dict__". This is the
12159 dictionary containing the module’s symbol table. Modifying this
12160 dictionary will actually change the module’s symbol table, but direct
12161 assignment to the "__dict__" attribute is not possible (you can write
12162 "m.__dict__['a'] = 1", which defines "m.a" to be "1", but you can’t
12163 write "m.__dict__ = {}"). Modifying "__dict__" directly is not
12164 recommended.
12165
12166 Modules built into the interpreter are written like this: "<module
12167 'sys' (built-in)>". If loaded from a file, they are written as
12168 "<module 'os' from '/usr/local/lib/pythonX.Y/os.pyc'>".
12169 ''',
12170 'typesseq': r'''Sequence Types — "list", "tuple", "range"
12171 *****************************************
12172
12173 There are three basic sequence types: lists, tuples, and range
12174 objects. Additional sequence types tailored for processing of binary
12175 data and text strings are described in dedicated sections.
12176
12177
12178 Common Sequence Operations
12179 ==========================
12180
12181 The operations in the following table are supported by most sequence
12182 types, both mutable and immutable. The "collections.abc.Sequence" ABC
12183 is provided to make it easier to correctly implement these operations
12184 on custom sequence types.
12185
12186 This table lists the sequence operations sorted in ascending priority.
12187 In the table, *s* and *t* are sequences of the same type, *n*, *i*,
12188 *j* and *k* are integers and *x* is an arbitrary object that meets any
12189 type and value restrictions imposed by *s*.
12190
12191 The "in" and "not in" operations have the same priorities as the
12192 comparison operations. The "+" (concatenation) and "*" (repetition)
12193 operations have the same priority as the corresponding numeric
12194 operations. [3]
12195
12196 +----------------------------+----------------------------------+------------+
12197 | Operation | Result | Notes |
12198 |============================|==================================|============|
12199 | "x in s" | "True" if an item of *s* is | (1) |
12200 | | equal to *x*, else "False" | |
12201 +----------------------------+----------------------------------+------------+
12202 | "x not in s" | "False" if an item of *s* is | (1) |
12203 | | equal to *x*, else "True" | |
12204 +----------------------------+----------------------------------+------------+
12205 | "s + t" | the concatenation of *s* and *t* | (6)(7) |
12206 +----------------------------+----------------------------------+------------+
12207 | "s * n" or "n * s" | equivalent to adding *s* to | (2)(7) |
12208 | | itself *n* times | |
12209 +----------------------------+----------------------------------+------------+
12210 | "s[i]" | *i*th item of *s*, origin 0 | (3)(8) |
12211 +----------------------------+----------------------------------+------------+
12212 | "s[i:j]" | slice of *s* from *i* to *j* | (3)(4) |
12213 +----------------------------+----------------------------------+------------+
12214 | "s[i:j:k]" | slice of *s* from *i* to *j* | (3)(5) |
12215 | | with step *k* | |
12216 +----------------------------+----------------------------------+------------+
12217 | "len(s)" | length of *s* | |
12218 +----------------------------+----------------------------------+------------+
12219 | "min(s)" | smallest item of *s* | |
12220 +----------------------------+----------------------------------+------------+
12221 | "max(s)" | largest item of *s* | |
12222 +----------------------------+----------------------------------+------------+
12223
12224 Sequences of the same type also support comparisons. In particular,
12225 tuples and lists are compared lexicographically by comparing
12226 corresponding elements. This means that to compare equal, every
12227 element must compare equal and the two sequences must be of the same
12228 type and have the same length. (For full details see Comparisons in
12229 the language reference.)
12230
12231 Forward and reversed iterators over mutable sequences access values
12232 using an index. That index will continue to march forward (or
12233 backward) even if the underlying sequence is mutated. The iterator
12234 terminates only when an "IndexError" or a "StopIteration" is
12235 encountered (or when the index drops below zero).
12236
12237 Notes:
12238
12239 1. While the "in" and "not in" operations are used only for simple
12240 containment testing in the general case, some specialised sequences
12241 (such as "str", "bytes" and "bytearray") also use them for
12242 subsequence testing:
12243
12244 >>> "gg" in "eggs"
12245 True
12246
12247 2. Values of *n* less than "0" are treated as "0" (which yields an
12248 empty sequence of the same type as *s*). Note that items in the
12249 sequence *s* are not copied; they are referenced multiple times.
12250 This often haunts new Python programmers; consider:
12251
12252 >>> lists = [[]] * 3
12253 >>> lists
12254 [[], [], []]
12255 >>> lists[0].append(3)
12256 >>> lists
12257 [[3], [3], [3]]
12258
12259 What has happened is that "[[]]" is a one-element list containing
12260 an empty list, so all three elements of "[[]] * 3" are references
12261 to this single empty list. Modifying any of the elements of
12262 "lists" modifies this single list. You can create a list of
12263 different lists this way:
12264
12265 >>> lists = [[] for i in range(3)]
12266 >>> lists[0].append(3)
12267 >>> lists[1].append(5)
12268 >>> lists[2].append(7)
12269 >>> lists
12270 [[3], [5], [7]]
12271
12272 Further explanation is available in the FAQ entry How do I create a
12273 multidimensional list?.
12274
12275 3. If *i* or *j* is negative, the index is relative to the end of
12276 sequence *s*: "len(s) + i" or "len(s) + j" is substituted. But
12277 note that "-0" is still "0".
12278
12279 4. The slice of *s* from *i* to *j* is defined as the sequence of
12280 items with index *k* such that "i <= k < j".
12281
12282 * If *i* is omitted or "None", use "0".
12283
12284 * If *j* is omitted or "None", use "len(s)".
12285
12286 * If *i* or *j* is less than "-len(s)", use "0".
12287
12288 * If *i* or *j* is greater than "len(s)", use "len(s)".
12289
12290 * If *i* is greater than or equal to *j*, the slice is empty.
12291
12292 5. The slice of *s* from *i* to *j* with step *k* is defined as the
12293 sequence of items with index "x = i + n*k" such that "0 <= n <
12294 (j-i)/k". In other words, the indices are "i", "i+k", "i+2*k",
12295 "i+3*k" and so on, stopping when *j* is reached (but never
12296 including *j*). When *k* is positive, *i* and *j* are reduced to
12297 "len(s)" if they are greater. When *k* is negative, *i* and *j* are
12298 reduced to "len(s) - 1" if they are greater. If *i* or *j* are
12299 omitted or "None", they become “end” values (which end depends on
12300 the sign of *k*). Note, *k* cannot be zero. If *k* is "None", it
12301 is treated like "1".
12302
12303 6. Concatenating immutable sequences always results in a new object.
12304 This means that building up a sequence by repeated concatenation
12305 will have a quadratic runtime cost in the total sequence length.
12306 To get a linear runtime cost, you must switch to one of the
12307 alternatives below:
12308
12309 * if concatenating "str" objects, you can build a list and use
12310 "str.join()" at the end or else write to an "io.StringIO"
12311 instance and retrieve its value when complete
12312
12313 * if concatenating "bytes" objects, you can similarly use
12314 "bytes.join()" or "io.BytesIO", or you can do in-place
12315 concatenation with a "bytearray" object. "bytearray" objects are
12316 mutable and have an efficient overallocation mechanism
12317
12318 * if concatenating "tuple" objects, extend a "list" instead
12319
12320 * for other types, investigate the relevant class documentation
12321
12322 7. Some sequence types (such as "range") only support item sequences
12323 that follow specific patterns, and hence don’t support sequence
12324 concatenation or repetition.
12325
12326 8. An "IndexError" is raised if *i* is outside the sequence range.
12327
12328 -[ Sequence Methods ]-
12329
12330 Sequence types also support the following methods:
12331
12332 sequence.count(value, /)
12333
12334 Return the total number of occurrences of *value* in *sequence*.
12335
12336 sequence.index(value[, start[, stop])
12337
12338 Return the index of the first occurrence of *value* in *sequence*.
12339
12340 Raises "ValueError" if *value* is not found in *sequence*.
12341
12342 The *start* or *stop* arguments allow for efficient searching of
12343 subsections of the sequence, beginning at *start* and ending at
12344 *stop*. This is roughly equivalent to "start +
12345 sequence[start:stop].index(value)", only without copying any data.
12346
12347 Caution:
12348
12349 Not all sequence types support passing the *start* and *stop*
12350 arguments.
12351
12352
12353 Immutable Sequence Types
12354 ========================
12355
12356 The only operation that immutable sequence types generally implement
12357 that is not also implemented by mutable sequence types is support for
12358 the "hash()" built-in.
12359
12360 This support allows immutable sequences, such as "tuple" instances, to
12361 be used as "dict" keys and stored in "set" and "frozenset" instances.
12362
12363 Attempting to hash an immutable sequence that contains unhashable
12364 values will result in "TypeError".
12365
12366
12367 Mutable Sequence Types
12368 ======================
12369
12370 The operations in the following table are defined on mutable sequence
12371 types. The "collections.abc.MutableSequence" ABC is provided to make
12372 it easier to correctly implement these operations on custom sequence
12373 types.
12374
12375 In the table *s* is an instance of a mutable sequence type, *t* is any
12376 iterable object and *x* is an arbitrary object that meets any type and
12377 value restrictions imposed by *s* (for example, "bytearray" only
12378 accepts integers that meet the value restriction "0 <= x <= 255").
12379
12380 +--------------------------------+----------------------------------+-----------------------+
12381 | Operation | Result | Notes |
12382 |================================|==================================|=======================|
12383 | "s[i] = x" | item *i* of *s* is replaced by | |
12384 | | *x* | |
12385 +--------------------------------+----------------------------------+-----------------------+
12386 | "del s[i]" | removes item *i* of *s* | |
12387 +--------------------------------+----------------------------------+-----------------------+
12388 | "s[i:j] = t" | slice of *s* from *i* to *j* is | |
12389 | | replaced by the contents of the | |
12390 | | iterable *t* | |
12391 +--------------------------------+----------------------------------+-----------------------+
12392 | "del s[i:j]" | removes the elements of "s[i:j]" | |
12393 | | from the list (same as "s[i:j] = | |
12394 | | []") | |
12395 +--------------------------------+----------------------------------+-----------------------+
12396 | "s[i:j:k] = t" | the elements of "s[i:j:k]" are | (1) |
12397 | | replaced by those of *t* | |
12398 +--------------------------------+----------------------------------+-----------------------+
12399 | "del s[i:j:k]" | removes the elements of | |
12400 | | "s[i:j:k]" from the list | |
12401 +--------------------------------+----------------------------------+-----------------------+
12402 | "s += t" | extends *s* with the contents of | |
12403 | | *t* (for the most part the same | |
12404 | | as "s[len(s):len(s)] = t") | |
12405 +--------------------------------+----------------------------------+-----------------------+
12406 | "s *= n" | updates *s* with its contents | (2) |
12407 | | repeated *n* times | |
12408 +--------------------------------+----------------------------------+-----------------------+
12409
12410 Notes:
12411
12412 1. If *k* is not equal to "1", *t* must have the same length as the
12413 slice it is replacing.
12414
12415 2. The value *n* is an integer, or an object implementing
12416 "__index__()". Zero and negative values of *n* clear the sequence.
12417 Items in the sequence are not copied; they are referenced multiple
12418 times, as explained for "s * n" under Common Sequence Operations.
12419
12420 -[ Mutable Sequence Methods ]-
12421
12422 Mutable sequence types also support the following methods:
12423
12424 sequence.append(value, /)
12425
12426 Append *value* to the end of the sequence This is equivalent to
12427 writing "seq[len(seq):len(seq)] = [value]".
12428
12429 sequence.clear()
12430
12431 Added in version 3.3.
12432
12433 Remove all items from *sequence*. This is equivalent to writing
12434 "del sequence[:]".
12435
12436 sequence.copy()
12437
12438 Added in version 3.3.
12439
12440 Create a shallow copy of *sequence*. This is equivalent to writing
12441 "sequence[:]".
12442
12443 Hint:
12444
12445 The "copy()" method is not part of the "MutableSequence" "ABC",
12446 but most concrete mutable sequence types provide it.
12447
12448 sequence.extend(iterable, /)
12449
12450 Extend *sequence* with the contents of *iterable*. For the most
12451 part, this is the same as writing "seq[len(seq):len(seq)] =
12452 iterable".
12453
12454 sequence.insert(index, value, /)
12455
12456 Insert *value* into *sequence* at the given *index*. This is
12457 equivalent to writing "sequence[index:index] = [value]".
12458
12459 sequence.pop(index=-1, /)
12460
12461 Retrieve the item at *index* and also removes it from *sequence*.
12462 By default, the last item in *sequence* is removed and returned.
12463
12464 sequence.remove(value, /)
12465
12466 Remove the first item from *sequence* where "sequence[i] == value".
12467
12468 Raises "ValueError" if *value* is not found in *sequence*.
12469
12470 sequence.reverse()
12471
12472 Reverse the items of *sequence* in place. This method maintains
12473 economy of space when reversing a large sequence. To remind users
12474 that it operates by side-effect, it returns "None".
12475
12476
12477 Lists
12478 =====
12479
12480 Lists are mutable sequences, typically used to store collections of
12481 homogeneous items (where the precise degree of similarity will vary by
12482 application).
12483
12484 class list(iterable=(), /)
12485
12486 Lists may be constructed in several ways:
12487
12488 * Using a pair of square brackets to denote the empty list: "[]"
12489
12490 * Using square brackets, separating items with commas: "[a]", "[a,
12491 b, c]"
12492
12493 * Using a list comprehension: "[x for x in iterable]"
12494
12495 * Using the type constructor: "list()" or "list(iterable)"
12496
12497 The constructor builds a list whose items are the same and in the
12498 same order as *iterable*’s items. *iterable* may be either a
12499 sequence, a container that supports iteration, or an iterator
12500 object. If *iterable* is already a list, a copy is made and
12501 returned, similar to "iterable[:]". For example, "list('abc')"
12502 returns "['a', 'b', 'c']" and "list( (1, 2, 3) )" returns "[1, 2,
12503 3]". If no argument is given, the constructor creates a new empty
12504 list, "[]".
12505
12506 Many other operations also produce lists, including the "sorted()"
12507 built-in.
12508
12509 Lists implement all of the common and mutable sequence operations.
12510 Lists also provide the following additional method:
12511
12512 sort(*, key=None, reverse=False)
12513
12514 This method sorts the list in place, using only "<" comparisons
12515 between items. Exceptions are not suppressed - if any comparison
12516 operations fail, the entire sort operation will fail (and the
12517 list will likely be left in a partially modified state).
12518
12519 "sort()" accepts two arguments that can only be passed by
12520 keyword (keyword-only arguments):
12521
12522 *key* specifies a function of one argument that is used to
12523 extract a comparison key from each list element (for example,
12524 "key=str.lower"). The key corresponding to each item in the list
12525 is calculated once and then used for the entire sorting process.
12526 The default value of "None" means that list items are sorted
12527 directly without calculating a separate key value.
12528
12529 The "functools.cmp_to_key()" utility is available to convert a
12530 2.x style *cmp* function to a *key* function.
12531
12532 *reverse* is a boolean value. If set to "True", then the list
12533 elements are sorted as if each comparison were reversed.
12534
12535 This method modifies the sequence in place for economy of space
12536 when sorting a large sequence. To remind users that it operates
12537 by side effect, it does not return the sorted sequence (use
12538 "sorted()" to explicitly request a new sorted list instance).
12539
12540 The "sort()" method is guaranteed to be stable. A sort is
12541 stable if it guarantees not to change the relative order of
12542 elements that compare equal — this is helpful for sorting in
12543 multiple passes (for example, sort by department, then by salary
12544 grade).
12545
12546 For sorting examples and a brief sorting tutorial, see Sorting
12547 Techniques.
12548
12549 **CPython implementation detail:** While a list is being sorted,
12550 the effect of attempting to mutate, or even inspect, the list is
12551 undefined. The C implementation of Python makes the list appear
12552 empty for the duration, and raises "ValueError" if it can detect
12553 that the list has been mutated during a sort.
12554
12555
12556 Tuples
12557 ======
12558
12559 Tuples are immutable sequences, typically used to store collections of
12560 heterogeneous data (such as the 2-tuples produced by the "enumerate()"
12561 built-in). Tuples are also used for cases where an immutable sequence
12562 of homogeneous data is needed (such as allowing storage in a "set" or
12563 "dict" instance).
12564
12565 class tuple(iterable=(), /)
12566
12567 Tuples may be constructed in a number of ways:
12568
12569 * Using a pair of parentheses to denote the empty tuple: "()"
12570
12571 * Using a trailing comma for a singleton tuple: "a," or "(a,)"
12572
12573 * Separating items with commas: "a, b, c" or "(a, b, c)"
12574
12575 * Using the "tuple()" built-in: "tuple()" or "tuple(iterable)"
12576
12577 The constructor builds a tuple whose items are the same and in the
12578 same order as *iterable*’s items. *iterable* may be either a
12579 sequence, a container that supports iteration, or an iterator
12580 object. If *iterable* is already a tuple, it is returned
12581 unchanged. For example, "tuple('abc')" returns "('a', 'b', 'c')"
12582 and "tuple( [1, 2, 3] )" returns "(1, 2, 3)". If no argument is
12583 given, the constructor creates a new empty tuple, "()".
12584
12585 Note that it is actually the comma which makes a tuple, not the
12586 parentheses. The parentheses are optional, except in the empty
12587 tuple case, or when they are needed to avoid syntactic ambiguity.
12588 For example, "f(a, b, c)" is a function call with three arguments,
12589 while "f((a, b, c))" is a function call with a 3-tuple as the sole
12590 argument.
12591
12592 Tuples implement all of the common sequence operations.
12593
12594 For heterogeneous collections of data where access by name is clearer
12595 than access by index, "collections.namedtuple()" may be a more
12596 appropriate choice than a simple tuple object.
12597
12598
12599 Ranges
12600 ======
12601
12602 The "range" type represents an immutable sequence of numbers and is
12603 commonly used for looping a specific number of times in "for" loops.
12604
12605 class range(stop, /)
12606 class range(start, stop, step=1, /)
12607
12608 The arguments to the range constructor must be integers (either
12609 built-in "int" or any object that implements the "__index__()"
12610 special method). If the *step* argument is omitted, it defaults to
12611 "1". If the *start* argument is omitted, it defaults to "0". If
12612 *step* is zero, "ValueError" is raised.
12613
12614 For a positive *step*, the contents of a range "r" are determined
12615 by the formula "r[i] = start + step*i" where "i >= 0" and "r[i] <
12616 stop".
12617
12618 For a negative *step*, the contents of the range are still
12619 determined by the formula "r[i] = start + step*i", but the
12620 constraints are "i >= 0" and "r[i] > stop".
12621
12622 A range object will be empty if "r[0]" does not meet the value
12623 constraint. Ranges do support negative indices, but these are
12624 interpreted as indexing from the end of the sequence determined by
12625 the positive indices.
12626
12627 Ranges containing absolute values larger than "sys.maxsize" are
12628 permitted but some features (such as "len()") may raise
12629 "OverflowError".
12630
12631 Range examples:
12632
12633 >>> list(range(10))
12634 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
12635 >>> list(range(1, 11))
12636 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
12637 >>> list(range(0, 30, 5))
12638 [0, 5, 10, 15, 20, 25]
12639 >>> list(range(0, 10, 3))
12640 [0, 3, 6, 9]
12641 >>> list(range(0, -10, -1))
12642 [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
12643 >>> list(range(0))
12644 []
12645 >>> list(range(1, 0))
12646 []
12647
12648 Ranges implement all of the common sequence operations except
12649 concatenation and repetition (due to the fact that range objects
12650 can only represent sequences that follow a strict pattern and
12651 repetition and concatenation will usually violate that pattern).
12652
12653 start
12654
12655 The value of the *start* parameter (or "0" if the parameter was
12656 not supplied)
12657
12658 stop
12659
12660 The value of the *stop* parameter
12661
12662 step
12663
12664 The value of the *step* parameter (or "1" if the parameter was
12665 not supplied)
12666
12667 The advantage of the "range" type over a regular "list" or "tuple" is
12668 that a "range" object will always take the same (small) amount of
12669 memory, no matter the size of the range it represents (as it only
12670 stores the "start", "stop" and "step" values, calculating individual
12671 items and subranges as needed).
12672
12673 Range objects implement the "collections.abc.Sequence" ABC, and
12674 provide features such as containment tests, element index lookup,
12675 slicing and support for negative indices (see Sequence Types — list,
12676 tuple, range):
12677
12678 >>> r = range(0, 20, 2)
12679 >>> r
12680 range(0, 20, 2)
12681 >>> 11 in r
12682 False
12683 >>> 10 in r
12684 True
12685 >>> r.index(10)
12686 5
12687 >>> r[5]
12688 10
12689 >>> r[:5]
12690 range(0, 10, 2)
12691 >>> r[-1]
12692 18
12693
12694 Testing range objects for equality with "==" and "!=" compares them as
12695 sequences. That is, two range objects are considered equal if they
12696 represent the same sequence of values. (Note that two range objects
12697 that compare equal might have different "start", "stop" and "step"
12698 attributes, for example "range(0) == range(2, 1, 3)" or "range(0, 3,
12699 2) == range(0, 4, 2)".)
12700
12701 Changed in version 3.2: Implement the Sequence ABC. Support slicing
12702 and negative indices. Test "int" objects for membership in constant
12703 time instead of iterating through all items.
12704
12705 Changed in version 3.3: Define ‘==’ and ‘!=’ to compare range objects
12706 based on the sequence of values they define (instead of comparing
12707 based on object identity).Added the "start", "stop" and "step"
12708 attributes.
12709
12710 See also:
12711
12712 * The linspace recipe shows how to implement a lazy version of range
12713 suitable for floating-point applications.
12714 ''',
12715 'typesseq-mutable': r'''Mutable Sequence Types
12716 **********************
12717
12718 The operations in the following table are defined on mutable sequence
12719 types. The "collections.abc.MutableSequence" ABC is provided to make
12720 it easier to correctly implement these operations on custom sequence
12721 types.
12722
12723 In the table *s* is an instance of a mutable sequence type, *t* is any
12724 iterable object and *x* is an arbitrary object that meets any type and
12725 value restrictions imposed by *s* (for example, "bytearray" only
12726 accepts integers that meet the value restriction "0 <= x <= 255").
12727
12728 +--------------------------------+----------------------------------+-----------------------+
12729 | Operation | Result | Notes |
12730 |================================|==================================|=======================|
12731 | "s[i] = x" | item *i* of *s* is replaced by | |
12732 | | *x* | |
12733 +--------------------------------+----------------------------------+-----------------------+
12734 | "del s[i]" | removes item *i* of *s* | |
12735 +--------------------------------+----------------------------------+-----------------------+
12736 | "s[i:j] = t" | slice of *s* from *i* to *j* is | |
12737 | | replaced by the contents of the | |
12738 | | iterable *t* | |
12739 +--------------------------------+----------------------------------+-----------------------+
12740 | "del s[i:j]" | removes the elements of "s[i:j]" | |
12741 | | from the list (same as "s[i:j] = | |
12742 | | []") | |
12743 +--------------------------------+----------------------------------+-----------------------+
12744 | "s[i:j:k] = t" | the elements of "s[i:j:k]" are | (1) |
12745 | | replaced by those of *t* | |
12746 +--------------------------------+----------------------------------+-----------------------+
12747 | "del s[i:j:k]" | removes the elements of | |
12748 | | "s[i:j:k]" from the list | |
12749 +--------------------------------+----------------------------------+-----------------------+
12750 | "s += t" | extends *s* with the contents of | |
12751 | | *t* (for the most part the same | |
12752 | | as "s[len(s):len(s)] = t") | |
12753 +--------------------------------+----------------------------------+-----------------------+
12754 | "s *= n" | updates *s* with its contents | (2) |
12755 | | repeated *n* times | |
12756 +--------------------------------+----------------------------------+-----------------------+
12757
12758 Notes:
12759
12760 1. If *k* is not equal to "1", *t* must have the same length as the
12761 slice it is replacing.
12762
12763 2. The value *n* is an integer, or an object implementing
12764 "__index__()". Zero and negative values of *n* clear the sequence.
12765 Items in the sequence are not copied; they are referenced multiple
12766 times, as explained for "s * n" under Common Sequence Operations.
12767
12768 -[ Mutable Sequence Methods ]-
12769
12770 Mutable sequence types also support the following methods:
12771
12772 sequence.append(value, /)
12773
12774 Append *value* to the end of the sequence This is equivalent to
12775 writing "seq[len(seq):len(seq)] = [value]".
12776
12777 sequence.clear()
12778
12779 Added in version 3.3.
12780
12781 Remove all items from *sequence*. This is equivalent to writing
12782 "del sequence[:]".
12783
12784 sequence.copy()
12785
12786 Added in version 3.3.
12787
12788 Create a shallow copy of *sequence*. This is equivalent to writing
12789 "sequence[:]".
12790
12791 Hint:
12792
12793 The "copy()" method is not part of the "MutableSequence" "ABC",
12794 but most concrete mutable sequence types provide it.
12795
12796 sequence.extend(iterable, /)
12797
12798 Extend *sequence* with the contents of *iterable*. For the most
12799 part, this is the same as writing "seq[len(seq):len(seq)] =
12800 iterable".
12801
12802 sequence.insert(index, value, /)
12803
12804 Insert *value* into *sequence* at the given *index*. This is
12805 equivalent to writing "sequence[index:index] = [value]".
12806
12807 sequence.pop(index=-1, /)
12808
12809 Retrieve the item at *index* and also removes it from *sequence*.
12810 By default, the last item in *sequence* is removed and returned.
12811
12812 sequence.remove(value, /)
12813
12814 Remove the first item from *sequence* where "sequence[i] == value".
12815
12816 Raises "ValueError" if *value* is not found in *sequence*.
12817
12818 sequence.reverse()
12819
12820 Reverse the items of *sequence* in place. This method maintains
12821 economy of space when reversing a large sequence. To remind users
12822 that it operates by side-effect, it returns "None".
12823 ''',
12824 'unary': r'''Unary arithmetic and bitwise operations
12825 ***************************************
12826
12827 All unary arithmetic and bitwise operations have the same priority:
12828
12829 u_expr ::= power | "-" u_expr | "+" u_expr | "~" u_expr
12830
12831 The unary "-" (minus) operator yields the negation of its numeric
12832 argument; the operation can be overridden with the "__neg__()" special
12833 method.
12834
12835 The unary "+" (plus) operator yields its numeric argument unchanged;
12836 the operation can be overridden with the "__pos__()" special method.
12837
12838 The unary "~" (invert) operator yields the bitwise inversion of its
12839 integer argument. The bitwise inversion of "x" is defined as
12840 "-(x+1)". It only applies to integral numbers or to custom objects
12841 that override the "__invert__()" special method.
12842
12843 In all three cases, if the argument does not have the proper type, a
12844 "TypeError" exception is raised.
12845 ''',
12846 'while': r'''The "while" statement
12847 *********************
12848
12849 The "while" statement is used for repeated execution as long as an
12850 expression is true:
12851
12852 while_stmt ::= "while" assignment_expression ":" suite
12853 ["else" ":" suite]
12854
12855 This repeatedly tests the expression and, if it is true, executes the
12856 first suite; if the expression is false (which may be the first time
12857 it is tested) the suite of the "else" clause, if present, is executed
12858 and the loop terminates.
12859
12860 A "break" statement executed in the first suite terminates the loop
12861 without executing the "else" clause’s suite. A "continue" statement
12862 executed in the first suite skips the rest of the suite and goes back
12863 to testing the expression.
12864 ''',
12865 'with': r'''The "with" statement
12866 ********************
12867
12868 The "with" statement is used to wrap the execution of a block with
12869 methods defined by a context manager (see section With Statement
12870 Context Managers). This allows common "try"…"except"…"finally" usage
12871 patterns to be encapsulated for convenient reuse.
12872
12873 with_stmt ::= "with" ( "(" with_stmt_contents ","? ")" | with_stmt_contents ) ":" suite
12874 with_stmt_contents ::= with_item ("," with_item)*
12875 with_item ::= expression ["as" target]
12876
12877 The execution of the "with" statement with one “item” proceeds as
12878 follows:
12879
12880 1. The context expression (the expression given in the "with_item") is
12881 evaluated to obtain a context manager.
12882
12883 2. The context manager’s "__enter__()" is loaded for later use.
12884
12885 3. The context manager’s "__exit__()" is loaded for later use.
12886
12887 4. The context manager’s "__enter__()" method is invoked.
12888
12889 5. If a target was included in the "with" statement, the return value
12890 from "__enter__()" is assigned to it.
12891
12892 Note:
12893
12894 The "with" statement guarantees that if the "__enter__()" method
12895 returns without an error, then "__exit__()" will always be
12896 called. Thus, if an error occurs during the assignment to the
12897 target list, it will be treated the same as an error occurring
12898 within the suite would be. See step 7 below.
12899
12900 6. The suite is executed.
12901
12902 7. The context manager’s "__exit__()" method is invoked. If an
12903 exception caused the suite to be exited, its type, value, and
12904 traceback are passed as arguments to "__exit__()". Otherwise, three
12905 "None" arguments are supplied.
12906
12907 If the suite was exited due to an exception, and the return value
12908 from the "__exit__()" method was false, the exception is reraised.
12909 If the return value was true, the exception is suppressed, and
12910 execution continues with the statement following the "with"
12911 statement.
12912
12913 If the suite was exited for any reason other than an exception, the
12914 return value from "__exit__()" is ignored, and execution proceeds
12915 at the normal location for the kind of exit that was taken.
12916
12917 The following code:
12918
12919 with EXPRESSION as TARGET:
12920 SUITE
12921
12922 is semantically equivalent to:
12923
12924 manager = (EXPRESSION)
12925 enter = type(manager).__enter__
12926 exit = type(manager).__exit__
12927 value = enter(manager)
12928 hit_except = False
12929
12930 try:
12931 TARGET = value
12932 SUITE
12933 except:
12934 hit_except = True
12935 if not exit(manager, *sys.exc_info()):
12936 raise
12937 finally:
12938 if not hit_except:
12939 exit(manager, None, None, None)
12940
12941 With more than one item, the context managers are processed as if
12942 multiple "with" statements were nested:
12943
12944 with A() as a, B() as b:
12945 SUITE
12946
12947 is semantically equivalent to:
12948
12949 with A() as a:
12950 with B() as b:
12951 SUITE
12952
12953 You can also write multi-item context managers in multiple lines if
12954 the items are surrounded by parentheses. For example:
12955
12956 with (
12957 A() as a,
12958 B() as b,
12959 ):
12960 SUITE
12961
12962 Changed in version 3.1: Support for multiple context expressions.
12963
12964 Changed in version 3.10: Support for using grouping parentheses to
12965 break the statement in multiple lines.
12966
12967 See also:
12968
12969 **PEP 343** - The “with” statement
12970 The specification, background, and examples for the Python "with"
12971 statement.
12972 ''',
12973 'yield': r'''The "yield" statement
12974 *********************
12975
12976 yield_stmt ::= yield_expression
12977
12978 A "yield" statement is semantically equivalent to a yield expression.
12979 The "yield" statement can be used to omit the parentheses that would
12980 otherwise be required in the equivalent yield expression statement.
12981 For example, the yield statements
12982
12983 yield <expr>
12984 yield from <expr>
12985
12986 are equivalent to the yield expression statements
12987
12988 (yield <expr>)
12989 (yield from <expr>)
12990
12991 Yield expressions and statements are only used when defining a
12992 *generator* function, and are only used in the body of the generator
12993 function. Using "yield" in a function definition is sufficient to
12994 cause that definition to create a generator function instead of a
12995 normal function.
12996
12997 For full details of "yield" semantics, refer to the Yield expressions
12998 section.
12999 ''',
13000 }