Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
topics.py14507 linesDownload Raw Back to pydoc_data
1# Autogenerated by Sphinx on Tue Apr  7 16:13:12 20262# as part of the release process.3 4topics = {5    'assert': r'''The "assert" statement6**********************7 8Assert statements are a convenient way to insert debugging assertions9into a program:10 11   assert_stmt: "assert" expression ["," expression]12 13The simple form, "assert expression", is equivalent to14 15   if __debug__:16       if not expression: raise AssertionError17 18The extended form, "assert expression1, expression2", is equivalent to19 20   if __debug__:21       if not expression1: raise AssertionError(expression2)22 23These equivalences assume that "__debug__" and "AssertionError" refer24to the built-in variables with those names.  In the current25implementation, the built-in variable "__debug__" is "True" under26normal circumstances, "False" when optimization is requested (command27line option "-O").  The current code generator emits no code for an28"assert" statement when optimization is requested at compile time.29Note that it is unnecessary to include the source code for the30expression that failed in the error message; it will be displayed as31part of the stack trace.32 33Assignments to "__debug__" are illegal.  The value for the built-in34variable is determined when the interpreter starts.35''',36    'assignment': r'''Assignment statements37*********************38 39Assignment statements are used to (re)bind names to values and to40modify attributes or items of mutable objects:41 42   assignment_stmt: (target_list "=")+ (starred_expression | yield_expression)43   target_list:     target ("," target)* [","]44   target:          identifier45                    | "(" [target_list] ")"46                    | "[" [target_list] "]"47                    | attributeref48                    | subscription49                    | "*" target50 51(See section Primaries for the syntax definitions for *attributeref*52and *subscription*.)53 54An assignment statement evaluates the expression list (remember that55this can be a single expression or a comma-separated list, the latter56yielding a tuple) and assigns the single resulting object to each of57the target lists, from left to right.58 59Assignment is defined recursively depending on the form of the target60(list). When a target is part of a mutable object (an attribute61reference or subscription), the mutable object must ultimately perform62the assignment and decide about its validity, and may raise an63exception if the assignment is unacceptable.  The rules observed by64various types and the exceptions raised are given with the definition65of the object types (see section The standard type hierarchy).66 67Assignment of an object to a target list, optionally enclosed in68parentheses or square brackets, is recursively defined as follows.69 70* If the target list is a single target with no trailing comma,71  optionally in parentheses, the object is assigned to that target.72 73* Else:74 75  * If the target list contains one target prefixed with an asterisk,76    called a “starred” target: The object must be an iterable with at77    least as many items as there are targets in the target list, minus78    one.  The first items of the iterable are assigned, from left to79    right, to the targets before the starred target.  The final items80    of the iterable are assigned to the targets after the starred81    target.  A list of the remaining items in the iterable is then82    assigned to the starred target (the list can be empty).83 84  * Else: The object must be an iterable with the same number of items85    as there are targets in the target list, and the items are86    assigned, from left to right, to the corresponding targets.87 88Assignment of an object to a single target is recursively defined as89follows.90 91* If the target is an identifier (name):92 93  * If the name does not occur in a "global" or "nonlocal" statement94    in the current code block: the name is bound to the object in the95    current local namespace.96 97  * Otherwise: the name is bound to the object in the global namespace98    or the outer namespace determined by "nonlocal", respectively.99 100  The name is rebound if it was already bound.  This may cause the101  reference count for the object previously bound to the name to reach102  zero, causing the object to be deallocated and its destructor (if it103  has one) to be called.104 105* If the target is an attribute reference: The primary expression in106  the reference is evaluated.  It should yield an object with107  assignable attributes; if this is not the case, "TypeError" is108  raised.  That object is then asked to assign the assigned object to109  the given attribute; if it cannot perform the assignment, it raises110  an exception (usually but not necessarily "AttributeError").111 112  Note: If the object is a class instance and the attribute reference113  occurs on both sides of the assignment operator, the right-hand side114  expression, "a.x" can access either an instance attribute or (if no115  instance attribute exists) a class attribute.  The left-hand side116  target "a.x" is always set as an instance attribute, creating it if117  necessary.  Thus, the two occurrences of "a.x" do not necessarily118  refer to the same attribute: if the right-hand side expression119  refers to a class attribute, the left-hand side creates a new120  instance attribute as the target of the assignment:121 122     class Cls:123         x = 3             # class variable124     inst = Cls()125     inst.x = inst.x + 1   # writes inst.x as 4 leaving Cls.x as 3126 127  This description does not necessarily apply to descriptor128  attributes, such as properties created with "property()".129 130* If the target is a subscription: The primary expression in the131  reference is evaluated. Next, the subscript expression is evaluated.132  Then, the primary’s "__setitem__()" method is called with two133  arguments: the subscript and the assigned object.134 135  Typically, "__setitem__()" is defined on mutable sequence objects136  (such as lists) and mapping objects (such as dictionaries), and137  behaves as follows.138 139  If the primary is a mutable sequence object (such as a list), the140  subscript must yield an integer.  If it is negative, the sequence’s141  length is added to it.  The resulting value must be a nonnegative142  integer less than the sequence’s length, and the sequence is asked143  to assign the assigned object to its item with that index.  If the144  index is out of range, "IndexError" is raised (assignment to a145  subscripted sequence cannot add new items to a list).146 147  If the primary is a mapping object (such as a dictionary), the148  subscript must have a type compatible with the mapping’s key type,149  and the mapping is then asked to create a key/value pair which maps150  the subscript to the assigned object.  This can either replace an151  existing key/value pair with the same key value, or insert a new152  key/value pair (if no key with the same value existed).153 154  If the target is a slicing: The primary expression should evaluate155  to a mutable sequence object (such as a list). The assigned object156  should be *iterable*. The slicing’s lower and upper bounds should be157  integers; if they are "None" (or not present), the defaults are zero158  and the sequence’s length. If either bound is negative, the159  sequence’s length is added to it.  The resulting bounds are clipped160  to lie between zero and the sequence’s length, inclusive.  Finally,161  the sequence object is asked to replace the slice with the items of162  the assigned sequence.  The length of the slice may be different163  from the length of the assigned sequence, thus changing the length164  of the target sequence, if the target sequence allows it.165 166Although the definition of assignment implies that overlaps between167the left-hand side and the right-hand side are ‘simultaneous’ (for168example "a, b = b, a" swaps two variables), overlaps *within* the169collection of assigned-to variables occur left-to-right, sometimes170resulting in confusion.  For instance, the following program prints171"[0, 2]":172 173   x = [0, 1]174   i = 0175   i, x[i] = 1, 2         # i is updated, then x[i] is updated176   print(x)177 178See also:179 180  **PEP 3132** - Extended Iterable Unpacking181     The specification for the "*target" feature.182 183 184Augmented assignment statements185===============================186 187Augmented assignment is the combination, in a single statement, of a188binary operation and an assignment statement:189 190   augmented_assignment_stmt: augtarget augop (expression_list | yield_expression)191   augtarget:                 identifier | attributeref | subscription192   augop:                     "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="193                              | ">>=" | "<<=" | "&=" | "^=" | "|="194 195(See section Primaries for the syntax definitions of the last three196symbols.)197 198An augmented assignment evaluates the target (which, unlike normal199assignment statements, cannot be an unpacking) and the expression200list, performs the binary operation specific to the type of assignment201on the two operands, and assigns the result to the original target.202The target is only evaluated once.203 204An augmented assignment statement like "x += 1" can be rewritten as "x205= x + 1" to achieve a similar, but not exactly equal effect. In the206augmented version, "x" is only evaluated once. Also, when possible,207the actual operation is performed *in-place*, meaning that rather than208creating a new object and assigning that to the target, the old object209is modified instead.210 211Unlike normal assignments, augmented assignments evaluate the left-212hand side *before* evaluating the right-hand side.  For example, "a[i]213+= f(x)" first looks-up "a[i]", then it evaluates "f(x)" and performs214the addition, and lastly, it writes the result back to "a[i]".215 216With the exception of assigning to tuples and multiple targets in a217single statement, the assignment done by augmented assignment218statements is handled the same way as normal assignments. Similarly,219with the exception of the possible *in-place* behavior, the binary220operation performed by augmented assignment is the same as the normal221binary operations.222 223For targets which are attribute references, the same caveat about224class and instance attributes applies as for regular assignments.225 226 227Annotated assignment statements228===============================229 230*Annotation* assignment is the combination, in a single statement, of231a variable or attribute annotation and an optional assignment232statement:233 234   annotated_assignment_stmt: augtarget ":" expression235                              ["=" (starred_expression | yield_expression)]236 237The difference from normal Assignment statements is that only a single238target is allowed.239 240The assignment target is considered “simple” if it consists of a241single name that is not enclosed in parentheses. For simple assignment242targets, if in class or module scope, the annotations are gathered in243a lazily evaluated annotation scope. The annotations can be evaluated244using the "__annotations__" attribute of a class or module, or using245the facilities in the "annotationlib" module.246 247If the assignment target is not simple (an attribute, subscript node,248or parenthesized name), the annotation is never evaluated.249 250If a name is annotated in a function scope, then this name is local251for that scope. Annotations are never evaluated and stored in function252scopes.253 254If the right hand side is present, an annotated assignment performs255the actual assignment as if there was no annotation present. If the256right hand side is not present for an expression target, then the257interpreter evaluates the target except for the last "__setitem__()"258or "__setattr__()" call.259 260See also:261 262  **PEP 526** - Syntax for Variable Annotations263     The proposal that added syntax for annotating the types of264     variables (including class variables and instance variables),265     instead of expressing them through comments.266 267  **PEP 484** - Type hints268     The proposal that added the "typing" module to provide a standard269     syntax for type annotations that can be used in static analysis270     tools and IDEs.271 272Changed in version 3.8: Now annotated assignments allow the same273expressions in the right hand side as regular assignments. Previously,274some expressions (like un-parenthesized tuple expressions) caused a275syntax error.276 277Changed in version 3.14: Annotations are now lazily evaluated in a278separate annotation scope. If the assignment target is not simple,279annotations are never evaluated.280''',281    'assignment-expressions': r'''Assignment expressions282**********************283 284   assignment_expression: [identifier ":="] expression285 286An assignment expression (sometimes also called a “named expression”287or “walrus”) assigns an "expression" to an "identifier", while also288returning the value of the "expression".289 290One common use case is when handling matched regular expressions:291 292   if matching := pattern.search(data):293       do_something(matching)294 295Or, when processing a file stream in chunks:296 297   while chunk := file.read(9000):298       process(chunk)299 300Assignment expressions must be surrounded by parentheses when used as301expression statements and when used as sub-expressions in slicing,302conditional, lambda, keyword-argument, and comprehension-if303expressions and in "assert", "with", and "assignment" statements. In304all other places where they can be used, parentheses are not required,305including in "if" and "while" statements.306 307Added in version 3.8: See **PEP 572** for more details about308assignment expressions.309''',310    'async': r'''Coroutines311**********312 313Added in version 3.5.314 315 316Coroutine function definition317=============================318 319   async_funcdef: [decorators] "async" "def" funcname "(" [parameter_list] ")"320                  ["->" expression] ":" suite321 322Execution of Python coroutines can be suspended and resumed at many323points (see *coroutine*). "await" expressions, "async for" and "async324with" can only be used in the body of a coroutine function.325 326Functions defined with "async def" syntax are always coroutine327functions, even if they do not contain "await" or "async" keywords.328 329It is a "SyntaxError" to use a "yield from" expression inside the body330of a coroutine function.331 332An example of a coroutine function:333 334   async def func(param1, param2):335       do_stuff()336       await some_coroutine()337 338Changed in version 3.7: "await" and "async" are now keywords;339previously they were only treated as such inside the body of a340coroutine function.341 342 343The "async for" statement344=========================345 346   async_for_stmt: "async" for_stmt347 348An *asynchronous iterable* provides an "__aiter__" method that349directly returns an *asynchronous iterator*, which can call350asynchronous code in its "__anext__" method.351 352The "async for" statement allows convenient iteration over353asynchronous iterables.354 355The following code:356 357   async for TARGET in ITER:358       SUITE359   else:360       SUITE2361 362Is semantically equivalent to:363 364   iter = (ITER).__aiter__()365   running = True366 367   while running:368       try:369           TARGET = await iter.__anext__()370       except StopAsyncIteration:371           running = False372       else:373           SUITE374   else:375       SUITE2376 377except that implicit special method lookup is used for "__aiter__()"378and "__anext__()".379 380It is a "SyntaxError" to use an "async for" statement outside the body381of a coroutine function.382 383 384The "async with" statement385==========================386 387   async_with_stmt: "async" with_stmt388 389An *asynchronous context manager* is a *context manager* that is able390to suspend execution in its *enter* and *exit* methods.391 392The following code:393 394   async with EXPRESSION as TARGET:395       SUITE396 397is semantically equivalent to:398 399   manager = (EXPRESSION)400   aenter = manager.__aenter__401   aexit = manager.__aexit__402   value = await aenter()403   hit_except = False404 405   try:406       TARGET = value407       SUITE408   except:409       hit_except = True410       if not await aexit(*sys.exc_info()):411           raise412   finally:413       if not hit_except:414           await aexit(None, None, None)415 416except that implicit special method lookup is used for "__aenter__()"417and "__aexit__()".418 419It is a "SyntaxError" to use an "async with" statement outside the420body of a coroutine function.421 422See also:423 424  **PEP 492** - Coroutines with async and await syntax425     The proposal that made coroutines a proper standalone concept in426     Python, and added supporting syntax.427''',428    'atom-identifiers': r'''Identifiers (Names)429*******************430 431An identifier occurring as an atom is a name.  See section Names432(identifiers and keywords) for lexical definition and section Naming433and binding for documentation of naming and binding.434 435When the name is bound to an object, evaluation of the atom yields436that object. When a name is not bound, an attempt to evaluate it437raises a "NameError" exception.438 439 440Private name mangling441=====================442 443When an identifier that textually occurs in a class definition begins444with two or more underscore characters and does not end in two or more445underscores, it is considered a *private name* of that class.446 447See also: The class specifications.448 449More precisely, private names are transformed to a longer form before450code is generated for them.  If the transformed name is longer than451255 characters, implementation-defined truncation may happen.452 453The transformation is independent of the syntactical context in which454the identifier is used but only the following private identifiers are455mangled:456 457* Any name used as the name of a variable that is assigned or read or458  any name of an attribute being accessed.459 460  The "__name__" attribute of nested functions, classes, and type461  aliases is however not mangled.462 463* The name of imported modules, e.g., "__spam" in "import __spam". If464  the module is part of a package (i.e., its name contains a dot), the465  name is *not* mangled, e.g., the "__foo" in "import __foo.bar" is466  not mangled.467 468* The name of an imported member, e.g., "__f" in "from spam import469  __f".470 471The transformation rule is defined as follows:472 473* The class name, with leading underscores removed and a single474  leading underscore inserted, is inserted in front of the identifier,475  e.g., the identifier "__spam" occurring in a class named "Foo",476  "_Foo" or "__Foo" is transformed to "_Foo__spam".477 478* If the class name consists only of underscores, the transformation479  is the identity, e.g., the identifier "__spam" occurring in a class480  named "_" or "__" is left as is.481''',482    'atom-literals': r'''Literals483********484 485A *literal* is a textual representation of a value. Python supports486numeric, string and bytes literals. Format strings and template487strings are treated as string literals.488 489Numeric literals consist of a single "NUMBER" token, which names an490integer, floating-point number, or an imaginary number. See the491Numeric literals section in Lexical analysis documentation for492details.493 494String and bytes literals may consist of several tokens. See section495String literal concatenation for details.496 497Note that negative and complex numbers, like "-3" or "3+4.2j", are498syntactically not literals, but unary or binary arithmetic operations499involving the "-" or "+" operator.500 501Evaluation of a literal yields an object of the given type ("int",502"float", "complex", "str", "bytes", or "Template") with the given503value. The value may be approximated in the case of floating-point and504imaginary literals.505 506The formal grammar for literals is:507 508   literal: strings | NUMBER509 510 511Literals and object identity512============================513 514All literals correspond to immutable data types, and hence the515object’s identity is less important than its value.  Multiple516evaluations of literals with the same value (either the same517occurrence in the program text or a different occurrence) may obtain518the same object or a different object with the same value.519 520CPython implementation detail: For example, in CPython, *small*521integers with the same value evaluate to the same object:522 523   >>> x = 7524   >>> y = 7525   >>> x is y526   True527 528However, large integers evaluate to different objects:529 530   >>> x = 123456789531   >>> y = 123456789532   >>> x is y533   False534 535This behavior may change in future versions of CPython. In particular,536the boundary between “small” and “large” integers has already changed537in the past.CPython will emit a "SyntaxWarning" when you compare538literals using "is":539 540   >>> x = 7541   >>> x is 7542   <input>:1: SyntaxWarning: "is" with 'int' literal. Did you mean "=="?543   True544 545See When can I rely on identity tests with the is operator? for more546information.547 548Template strings are immutable but may reference mutable objects as549"Interpolation" values. For the purposes of this section, two550t-strings have the “same value” if both their structure and the551*identity* of the values match.552 553**CPython implementation detail:** Currently, each evaluation of a554template string results in a different object.555 556 557String literal concatenation558============================559 560Multiple adjacent string or bytes literals, possibly using different561quoting conventions, are allowed, and their meaning is the same as562their concatenation:563 564   >>> "hello" 'world'565   "helloworld"566 567This feature is defined at the syntactical level, so it only works568with literals. To concatenate string expressions at run time, the ‘+’569operator may be used:570 571   >>> greeting = "Hello"572   >>> space = " "573   >>> name = "Blaise"574   >>> print(greeting + space + name)   # not: print(greeting space name)575   Hello Blaise576 577Literal concatenation can freely mix raw strings, triple-quoted578strings, and formatted string literals. For example:579 580   >>> "Hello" r', ' f"{name}!"581   "Hello, Blaise!"582 583This feature can be used to reduce the number of backslashes needed,584to split long strings conveniently across long lines, or even to add585comments to parts of strings. For example:586 587   re.compile("[A-Za-z_]"       # letter or underscore588              "[A-Za-z0-9_]*"   # letter, digit or underscore589             )590 591However, bytes literals may only be combined with other byte literals;592not with string literals of any kind. Also, template string literals593may only be combined with other template string literals:594 595   >>> t"Hello" t"{name}!"596   Template(strings=('Hello', '!'), interpolations=(...))597 598Formally:599 600   strings: (STRING | fstring)+ | tstring+601''',602    'attribute-access': r'''Customizing attribute access603****************************604 605The following methods can be defined to customize the meaning of606attribute access (use of, assignment to, or deletion of "x.name") for607class instances.608 609object.__getattr__(self, name)610 611   Called when the default attribute access fails with an612   "AttributeError" (either "__getattribute__()" raises an613   "AttributeError" because *name* is not an instance attribute or an614   attribute in the class tree for "self"; or "__get__()" of a *name*615   property raises "AttributeError").  This method should either616   return the (computed) attribute value or raise an "AttributeError"617   exception. The "object" class itself does not provide this method.618 619   Note that if the attribute is found through the normal mechanism,620   "__getattr__()" is not called.  (This is an intentional asymmetry621   between "__getattr__()" and "__setattr__()".) This is done both for622   efficiency reasons and because otherwise "__getattr__()" would have623   no way to access other attributes of the instance.  Note that at624   least for instance variables, you can take total control by not625   inserting any values in the instance attribute dictionary (but626   instead inserting them in another object).  See the627   "__getattribute__()" method below for a way to actually get total628   control over attribute access.629 630object.__getattribute__(self, name)631 632   Called unconditionally to implement attribute accesses for633   instances of the class. If the class also defines "__getattr__()",634   the latter will not be called unless "__getattribute__()" either635   calls it explicitly or raises an "AttributeError". This method636   should return the (computed) attribute value or raise an637   "AttributeError" exception. In order to avoid infinite recursion in638   this method, its implementation should always call the base class639   method with the same name to access any attributes it needs, for640   example, "object.__getattribute__(self, name)".641 642   Note:643 644     This method may still be bypassed when looking up special methods645     as the result of implicit invocation via language syntax or646     built-in functions. See Special method lookup.647 648   For certain sensitive attribute accesses, raises an auditing event649   "object.__getattr__" with arguments "obj" and "name".650 651object.__setattr__(self, name, value)652 653   Called when an attribute assignment is attempted.  This is called654   instead of the normal mechanism (i.e. store the value in the655   instance dictionary). *name* is the attribute name, *value* is the656   value to be assigned to it.657 658   If "__setattr__()" wants to assign to an instance attribute, it659   should call the base class method with the same name, for example,660   "object.__setattr__(self, name, value)".661 662   For certain sensitive attribute assignments, raises an auditing663   event "object.__setattr__" with arguments "obj", "name", "value".664 665object.__delattr__(self, name)666 667   Like "__setattr__()" but for attribute deletion instead of668   assignment.  This should only be implemented if "del obj.name" is669   meaningful for the object.670 671   For certain sensitive attribute deletions, raises an auditing event672   "object.__delattr__" with arguments "obj" and "name".673 674object.__dir__(self)675 676   Called when "dir()" is called on the object. An iterable must be677   returned. "dir()" converts the returned iterable to a list and678   sorts it.679 680 681Customizing module attribute access682===================================683 684module.__getattr__()685module.__dir__()686 687Special names "__getattr__" and "__dir__" can be also used to688customize access to module attributes. The "__getattr__" function at689the module level should accept one argument which is the name of an690attribute and return the computed value or raise an "AttributeError".691If an attribute is not found on a module object through the normal692lookup, i.e. "object.__getattribute__()", then "__getattr__" is693searched in the module "__dict__" before raising an "AttributeError".694If found, it is called with the attribute name and the result is695returned.696 697The "__dir__" function should accept no arguments, and return an698iterable of strings that represents the names accessible on module. If699present, this function overrides the standard "dir()" search on a700module.701 702module.__class__703 704For a more fine grained customization of the module behavior (setting705attributes, properties, etc.), one can set the "__class__" attribute706of a module object to a subclass of "types.ModuleType". For example:707 708   import sys709   from types import ModuleType710 711   class VerboseModule(ModuleType):712       def __repr__(self):713           return f'Verbose {self.__name__}'714 715       def __setattr__(self, attr, value):716           print(f'Setting {attr}...')717           super().__setattr__(attr, value)718 719   sys.modules[__name__].__class__ = VerboseModule720 721Note:722 723  Defining module "__getattr__" and setting module "__class__" only724  affect lookups made using the attribute access syntax – directly725  accessing the module globals (whether by code within the module, or726  via a reference to the module’s globals dictionary) is unaffected.727 728Changed in version 3.5: "__class__" module attribute is now writable.729 730Added in version 3.7: "__getattr__" and "__dir__" module attributes.731 732See also:733 734  **PEP 562** - Module __getattr__ and __dir__735     Describes the "__getattr__" and "__dir__" functions on modules.736 737 738Implementing Descriptors739========================740 741The following methods only apply when an instance of the class742containing the method (a so-called *descriptor* class) appears in an743*owner* class (the descriptor must be in either the owner’s class744dictionary or in the class dictionary for one of its parents).  In the745examples below, “the attribute” refers to the attribute whose name is746the key of the property in the owner class’ "__dict__".  The "object"747class itself does not implement any of these protocols.748 749object.__get__(self, instance, owner=None)750 751   Called to get the attribute of the owner class (class attribute752   access) or of an instance of that class (instance attribute753   access). The optional *owner* argument is the owner class, while754   *instance* is the instance that the attribute was accessed through,755   or "None" when the attribute is accessed through the *owner*.756 757   This method should return the computed attribute value or raise an758   "AttributeError" exception.759 760   **PEP 252** specifies that "__get__()" is callable with one or two761   arguments.  Python’s own built-in descriptors support this762   specification; however, it is likely that some third-party tools763   have descriptors that require both arguments.  Python’s own764   "__getattribute__()" implementation always passes in both arguments765   whether they are required or not.766 767object.__set__(self, instance, value)768 769   Called to set the attribute on an instance *instance* of the owner770   class to a new value, *value*.771 772   Note, adding "__set__()" or "__delete__()" changes the kind of773   descriptor to a “data descriptor”.  See Invoking Descriptors for774   more details.775 776object.__delete__(self, instance)777 778   Called to delete the attribute on an instance *instance* of the779   owner class.780 781Instances of descriptors may also have the "__objclass__" attribute782present:783 784object.__objclass__785 786   The attribute "__objclass__" is interpreted by the "inspect" module787   as specifying the class where this object was defined (setting this788   appropriately can assist in runtime introspection of dynamic class789   attributes). For callables, it may indicate that an instance of the790   given type (or a subclass) is expected or required as the first791   positional argument (for example, CPython sets this attribute for792   unbound methods that are implemented in C).793 794 795Invoking Descriptors796====================797 798In general, a descriptor is an object attribute with “binding799behavior”, one whose attribute access has been overridden by methods800in the descriptor protocol:  "__get__()", "__set__()", and801"__delete__()". If any of those methods are defined for an object, it802is said to be a descriptor.803 804The default behavior for attribute access is to get, set, or delete805the attribute from an object’s dictionary. For instance, "a.x" has a806lookup chain starting with "a.__dict__['x']", then807"type(a).__dict__['x']", and continuing through the base classes of808"type(a)" excluding metaclasses.809 810However, if the looked-up value is an object defining one of the811descriptor methods, then Python may override the default behavior and812invoke the descriptor method instead.  Where this occurs in the813precedence chain depends on which descriptor methods were defined and814how they were called.815 816The starting point for descriptor invocation is a binding, "a.x". How817the arguments are assembled depends on "a":818 819Direct Call820   The simplest and least common call is when user code directly821   invokes a descriptor method:    "x.__get__(a)".822 823Instance Binding824   If binding to an object instance, "a.x" is transformed into the825   call: "type(a).__dict__['x'].__get__(a, type(a))".826 827Class Binding828   If binding to a class, "A.x" is transformed into the call:829   "A.__dict__['x'].__get__(None, A)".830 831Super Binding832   A dotted lookup such as "super(A, a).x" searches833   "a.__class__.__mro__" for a base class "B" following "A" and then834   returns "B.__dict__['x'].__get__(a, A)".  If not a descriptor, "x"835   is returned unchanged.836 837For instance bindings, the precedence of descriptor invocation depends838on which descriptor methods are defined.  A descriptor can define any839combination of "__get__()", "__set__()" and "__delete__()".  If it840does not define "__get__()", then accessing the attribute will return841the descriptor object itself unless there is a value in the object’s842instance dictionary.  If the descriptor defines "__set__()" and/or843"__delete__()", it is a data descriptor; if it defines neither, it is844a non-data descriptor.  Normally, data descriptors define both845"__get__()" and "__set__()", while non-data descriptors have just the846"__get__()" method.  Data descriptors with "__get__()" and "__set__()"847(and/or "__delete__()") defined always override a redefinition in an848instance dictionary.  In contrast, non-data descriptors can be849overridden by instances.850 851Python methods (including those decorated with "@staticmethod" and852"@classmethod") are implemented as non-data descriptors.  Accordingly,853instances can redefine and override methods.  This allows individual854instances to acquire behaviors that differ from other instances of the855same class.856 857The "property()" function is implemented as a data descriptor.858Accordingly, instances cannot override the behavior of a property.859 860 861__slots__862=========863 864*__slots__* allow us to explicitly declare data members (like865properties) and deny the creation of "__dict__" and *__weakref__*866(unless explicitly declared in *__slots__* or available in a parent.)867 868The space saved over using "__dict__" can be significant. Attribute869lookup speed can be significantly improved as well.870 871object.__slots__872 873   This class variable can be assigned a string, iterable, or sequence874   of strings with variable names used by instances.  *__slots__*875   reserves space for the declared variables and prevents the876   automatic creation of "__dict__" and *__weakref__* for each877   instance.878 879Notes on using *__slots__*:880 881* When inheriting from a class without *__slots__*, the "__dict__" and882  *__weakref__* attribute of the instances will always be accessible.883 884* Without a "__dict__" variable, instances cannot be assigned new885  variables not listed in the *__slots__* definition.  Attempts to886  assign to an unlisted variable name raises "AttributeError". If887  dynamic assignment of new variables is desired, then add888  "'__dict__'" to the sequence of strings in the *__slots__*889  declaration.890 891* Without a *__weakref__* variable for each instance, classes defining892  *__slots__* do not support "weak references" to its instances. If893  weak reference support is needed, then add "'__weakref__'" to the894  sequence of strings in the *__slots__* declaration.895 896* *__slots__* are implemented at the class level by creating897  descriptors for each variable name.  As a result, class attributes898  cannot be used to set default values for instance variables defined899  by *__slots__*; otherwise, the class attribute would overwrite the900  descriptor assignment.901 902* The action of a *__slots__* declaration is not limited to the class903  where it is defined.  *__slots__* declared in parents are available904  in child classes. However, instances of a child subclass will get a905  "__dict__" and *__weakref__* unless the subclass also defines906  *__slots__* (which should only contain names of any *additional*907  slots).908 909* If a class defines a slot also defined in a base class, the instance910  variable defined by the base class slot is inaccessible (except by911  retrieving its descriptor directly from the base class). This912  renders the meaning of the program undefined.  In the future, a913  check may be added to prevent this.914 915* "TypeError" will be raised if nonempty *__slots__* are defined for a916  class derived from a ""variable-length" built-in type" such as917  "int", "bytes", and "tuple".918 919* Any non-string *iterable* may be assigned to *__slots__*.920 921* If a "dictionary" is used to assign *__slots__*, the dictionary keys922  will be used as the slot names. The values of the dictionary can be923  used to provide per-attribute docstrings that will be recognised by924  "inspect.getdoc()" and displayed in the output of "help()".925 926* "__class__" assignment works only if both classes have the same927  *__slots__*.928 929* Multiple inheritance with multiple slotted parent classes can be930  used, but only one parent is allowed to have attributes created by931  slots (the other bases must have empty slot layouts) - violations932  raise "TypeError".933 934* If an *iterator* is used for *__slots__* then a *descriptor* is935  created for each of the iterator’s values. However, the *__slots__*936  attribute will be an empty iterator.937''',938    'attribute-references': r'''Attribute references939********************940 941An attribute reference is a primary followed by a period and a name:942 943   attributeref: primary "." identifier944 945The primary must evaluate to an object of a type that supports946attribute references, which most objects do.  This object is then947asked to produce the attribute whose name is the identifier. The type948and value produced is determined by the object.  Multiple evaluations949of the same attribute reference may yield different objects.950 951This production can be customized by overriding the952"__getattribute__()" method or the "__getattr__()" method.  The953"__getattribute__()" method is called first and either returns a value954or raises "AttributeError" if the attribute is not available.955 956If an "AttributeError" is raised and the object has a "__getattr__()"957method, that method is called as a fallback.958''',959    'augassign': r'''Augmented assignment statements960*******************************961 962Augmented assignment is the combination, in a single statement, of a963binary operation and an assignment statement:964 965   augmented_assignment_stmt: augtarget augop (expression_list | yield_expression)966   augtarget:                 identifier | attributeref | subscription967   augop:                     "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="968                              | ">>=" | "<<=" | "&=" | "^=" | "|="969 970(See section Primaries for the syntax definitions of the last three971symbols.)972 973An augmented assignment evaluates the target (which, unlike normal974assignment statements, cannot be an unpacking) and the expression975list, performs the binary operation specific to the type of assignment976on the two operands, and assigns the result to the original target.977The target is only evaluated once.978 979An augmented assignment statement like "x += 1" can be rewritten as "x980= x + 1" to achieve a similar, but not exactly equal effect. In the981augmented version, "x" is only evaluated once. Also, when possible,982the actual operation is performed *in-place*, meaning that rather than983creating a new object and assigning that to the target, the old object984is modified instead.985 986Unlike normal assignments, augmented assignments evaluate the left-987hand side *before* evaluating the right-hand side.  For example, "a[i]988+= f(x)" first looks-up "a[i]", then it evaluates "f(x)" and performs989the addition, and lastly, it writes the result back to "a[i]".990 991With the exception of assigning to tuples and multiple targets in a992single statement, the assignment done by augmented assignment993statements is handled the same way as normal assignments. Similarly,994with the exception of the possible *in-place* behavior, the binary995operation performed by augmented assignment is the same as the normal996binary operations.997 998For targets which are attribute references, the same caveat about999class and instance attributes applies as for regular assignments.1000''',1001    'await': r'''Await expression1002****************1003 1004Suspend the execution of *coroutine* on an *awaitable* object. Can1005only be used inside a *coroutine function*.1006 1007   await_expr: "await" primary1008 1009Added in version 3.5.1010''',1011    'binary': r'''Binary arithmetic operations1012****************************1013 1014The binary arithmetic operations have the conventional priority1015levels.  Note that some of these operations also apply to certain non-1016numeric types.  Apart from the power operator, there are only two1017levels, one for multiplicative operators and one for additive1018operators:1019 1020   m_expr: u_expr | m_expr "*" u_expr | m_expr "@" m_expr |1021           m_expr "//" u_expr | m_expr "/" u_expr |1022           m_expr "%" u_expr1023   a_expr: m_expr | a_expr "+" m_expr | a_expr "-" m_expr1024 1025The "*" (multiplication) operator yields the product of its arguments.1026The arguments must either both be numbers, or one argument must be an1027integer and the other must be a sequence. In the former case, the1028numbers are converted to a common real type and then multiplied1029together.  In the latter case, sequence repetition is performed; a1030negative repetition factor yields an empty sequence.1031 1032This operation can be customized using the special "__mul__()" and1033"__rmul__()" methods.1034 1035Changed in version 3.14: If only one operand is a complex number, the1036other operand is converted to a floating-point number.1037 1038The "@" (at) operator is intended to be used for matrix1039multiplication.  No builtin Python types implement this operator.1040 1041This operation can be customized using the special "__matmul__()" and1042"__rmatmul__()" methods.1043 1044Added in version 3.5.1045 1046The "/" (division) and "//" (floor division) operators yield the1047quotient of their arguments.  The numeric arguments are first1048converted to a common type. Division of integers yields a float, while1049floor division of integers results in an integer; the result is that1050of mathematical division with the ‘floor’ function applied to the1051result.  Division by zero raises the "ZeroDivisionError" exception.1052 1053The division operation can be customized using the special1054"__truediv__()" and "__rtruediv__()" methods. The floor division1055operation can be customized using the special "__floordiv__()" and1056"__rfloordiv__()" methods.1057 1058The "%" (modulo) operator yields the remainder from the division of1059the first argument by the second.  The numeric arguments are first1060converted to a common type. A zero right argument raises the1061"ZeroDivisionError" exception.  The arguments may be floating-point1062numbers, e.g., "3.14%0.7" equals "0.34" (since "3.14" equals "4*0.7 +10630.34".)  The modulo operator always yields a result with the same sign1064as its second operand (or zero); the absolute value of the result is1065strictly smaller than the absolute value of the second operand [1].1066 1067The floor division and modulo operators are connected by the following1068identity: "x == (x//y)*y + (x%y)".  Floor division and modulo are also1069connected with the built-in function "divmod()": "divmod(x, y) ==1070(x//y, x%y)". [2].1071 1072In addition to performing the modulo operation on numbers, the "%"1073operator is also overloaded by string objects to perform old-style1074string formatting (also known as interpolation).  The syntax for1075string formatting is described in the Python Library Reference,1076section printf-style String Formatting.1077 1078The *modulo* operation can be customized using the special "__mod__()"1079and "__rmod__()" methods.1080 1081The floor division operator, the modulo operator, and the "divmod()"1082function are not defined for complex numbers.  Instead, convert to a1083floating-point number using the "abs()" function if appropriate.1084 1085The "+" (addition) operator yields the sum of its arguments.  The1086arguments must either both be numbers or both be sequences of the same1087type.  In the former case, the numbers are converted to a common real1088type and then added together. In the latter case, the sequences are1089concatenated.1090 1091This operation can be customized using the special "__add__()" and1092"__radd__()" methods.1093 1094Changed in version 3.14: If only one operand is a complex number, the1095other operand is converted to a floating-point number.1096 1097The "-" (subtraction) operator yields the difference of its arguments.1098The numeric arguments are first converted to a common real type.1099 1100This operation can be customized using the special "__sub__()" and1101"__rsub__()" methods.1102 1103Changed in version 3.14: If only one operand is a complex number, the1104other operand is converted to a floating-point number.1105''',1106    'bitwise': r'''Binary bitwise operations1107*************************1108 1109Each of the three bitwise operations has a different priority level:1110 1111   and_expr: shift_expr | and_expr "&" shift_expr1112   xor_expr: and_expr | xor_expr "^" and_expr1113   or_expr:  xor_expr | or_expr "|" xor_expr1114 1115The "&" operator yields the bitwise AND of its arguments, which must1116be integers or one of them must be a custom object overriding1117"__and__()" or "__rand__()" special methods.1118 1119The "^" operator yields the bitwise XOR (exclusive OR) of its1120arguments, which must be integers or one of them must be a custom1121object overriding "__xor__()" or "__rxor__()" special methods.1122 1123The "|" operator yields the bitwise (inclusive) OR of its arguments,1124which must be integers or one of them must be a custom object1125overriding "__or__()" or "__ror__()" special methods.1126''',1127    'bltin-code-objects': r'''Code Objects1128************1129 1130Code objects are used by the implementation to represent “pseudo-1131compiled” executable Python code such as a function body. They differ1132from function objects because they don’t contain a reference to their1133global execution environment.  Code objects are returned by the built-1134in "compile()" function and can be extracted from function objects1135through their "__code__" attribute. See also the "code" module.1136 1137Accessing "__code__" raises an auditing event "object.__getattr__"1138with arguments "obj" and ""__code__"".1139 1140A code object can be executed or evaluated by passing it (instead of a1141source string) to the "exec()" or "eval()"  built-in functions.1142 1143See The standard type hierarchy for more information.1144''',1145    'bltin-ellipsis-object': r'''The Ellipsis Object1146*******************1147 1148This object is commonly used to indicate that something is omitted. It1149supports no special operations.  There is exactly one ellipsis object,1150named "Ellipsis" (a built-in name).  "type(Ellipsis)()" produces the1151"Ellipsis" singleton.1152 1153It is written as "Ellipsis" or "...".1154 1155In typical use, "..." as the "Ellipsis" object appears in a few1156different places, for instance:1157 1158* In type annotations, such as callable arguments or tuple elements.1159 1160* As the body of a function instead of a pass statement.1161 1162* In third-party libraries, such as Numpy’s slicing and striding.1163 1164Python also uses three dots in ways that are not "Ellipsis" objects,1165for instance:1166 1167* Doctest’s "ELLIPSIS", as a pattern for missing content.1168 1169* The default Python prompt of the *interactive* shell when partial1170  input is incomplete.1171 1172Lastly, the Python documentation often uses three dots in conventional1173English usage to mean omitted content, even in code examples that also1174use them as the "Ellipsis".1175''',1176    'bltin-null-object': r'''The Null Object1177***************1178 1179This object is returned by functions that don’t explicitly return a1180value.  It supports no special operations.  There is exactly one null1181object, named "None" (a built-in name).  "type(None)()" produces the1182same singleton.1183 1184It is written as "None".1185''',1186    'bltin-type-objects': r'''Type Objects1187************1188 1189Type objects represent the various object types.  An object’s type is1190accessed by the built-in function "type()".  There are no special1191operations on types.  The standard module "types" defines names for1192all standard built-in types.1193 1194Types are written like this: "<class 'int'>".1195''',1196    'booleans': r'''Boolean operations1197******************1198 1199   or_test:  and_test | or_test "or" and_test1200   and_test: not_test | and_test "and" not_test

Showing the first 1,200 of 14507 lines. Download the file for the rest.