Your IP : 18.191.147.146
U
e5d�s
� P @ s� d ddddddddd d
ddd
ddddddddddddddddddd d!d"d#d$d%d&d'd(dd)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdN�OZ dOS )Pau The "assert" statement
**********************
Assert statements are a convenient way to insert debugging assertions
into a program:
assert_stmt ::= "assert" expression ["," expression]
The simple form, "assert expression", is equivalent to
if __debug__:
if not expression: raise AssertionError
The extended form, "assert expression1, expression2", is equivalent to
if __debug__:
if not expression1: raise AssertionError(expression2)
These equivalences assume that "__debug__" and "AssertionError" refer
to the built-in variables with those names. In the current
implementation, the built-in variable "__debug__" is "True" under
normal circumstances, "False" when optimization is requested (command
line option "-O"). The current code generator emits no code for an
assert statement when optimization is requested at compile time. Note
that it is unnecessary to include the source code for the expression
that failed in the error message; it will be displayed as part of the
stack trace.
Assignments to "__debug__" are illegal. The value for the built-in
variable is determined when the interpreter starts.
u�, Assignment statements
*********************
Assignment statements are used to (re)bind names to values and to
modify attributes or items of mutable objects:
assignment_stmt ::= (target_list "=")+ (starred_expression | yield_expression)
target_list ::= target ("," target)* [","]
target ::= identifier
| "(" [target_list] ")"
| "[" [target_list] "]"
| attributeref
| subscription
| slicing
| "*" target
(See section Primaries for the syntax definitions for *attributeref*,
*subscription*, and *slicing*.)
An assignment statement evaluates the expression list (remember that
this can be a single expression or a comma-separated list, the latter
yielding a tuple) and assigns the single resulting object to each of
the target lists, from left to right.
Assignment is defined recursively depending on the form of the target
(list). When a target is part of a mutable object (an attribute
reference, subscription or slicing), the mutable object must
ultimately perform the assignment and decide about its validity, and
may raise an exception if the assignment is unacceptable. The rules
observed by various types and the exceptions raised are given with the
definition of the object types (see section The standard type
hierarchy).
Assignment of an object to a target list, optionally enclosed in
parentheses or square brackets, is recursively defined as follows.
* If the target list is a single target with no trailing comma,
optionally in parentheses, the object is assigned to that target.
* Else: The object must be an iterable with the same number of items
as there are targets in the target list, and the items are assigned,
from left to right, to the corresponding targets.
* If the target list contains one target prefixed with an asterisk,
called a “starred” target: The object must be an iterable with at
least as many items as there are targets in the target list, minus
one. The first items of the iterable are assigned, from left to
right, to the targets before the starred target. The final items
of the iterable are assigned to the targets after the starred
target. A list of the remaining items in the iterable is then
assigned to the starred target (the list can be empty).
* Else: The object must be an iterable with the same number of items
as there are targets in the target list, and the items are
assigned, from left to right, to the corresponding targets.
Assignment of an object to a single target is recursively defined as
follows.
* If the target is an identifier (name):
* If the name does not occur in a "global" or "nonlocal" statement
in the current code block: the name is bound to the object in the
current local namespace.
* Otherwise: the name is bound to the object in the global namespace
or the outer namespace determined by "nonlocal", respectively.
The name is rebound if it was already bound. This may cause the
reference count for the object previously bound to the name to reach
zero, causing the object to be deallocated and its destructor (if it
has one) to be called.
* If the target is an attribute reference: The primary expression in
the reference is evaluated. It should yield an object with
assignable attributes; if this is not the case, "TypeError" is
raised. That object is then asked to assign the assigned object to
the given attribute; if it cannot perform the assignment, it raises
an exception (usually but not necessarily "AttributeError").
Note: If the object is a class instance and the attribute reference
occurs on both sides of the assignment operator, the right-hand side
expression, "a.x" can access either an instance attribute or (if no
instance attribute exists) a class attribute. The left-hand side
target "a.x" is always set as an instance attribute, creating it if
necessary. Thus, the two occurrences of "a.x" do not necessarily
refer to the same attribute: if the right-hand side expression
refers to a class attribute, the left-hand side creates a new
instance attribute as the target of the assignment:
class Cls:
x = 3 # class variable
inst = Cls()
inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3
This description does not necessarily apply to descriptor
attributes, such as properties created with "property()".
* If the target is a subscription: The primary expression in the
reference is evaluated. It should yield either a mutable sequence
object (such as a list) or a mapping object (such as a dictionary).
Next, the subscript expression is evaluated.
If the primary is a mutable sequence object (such as a list), the
subscript must yield an integer. If it is negative, the sequence’s
length is added to it. The resulting value must be a nonnegative
integer less than the sequence’s length, and the sequence is asked
to assign the assigned object to its item with that index. If the
index is out of range, "IndexError" is raised (assignment to a
subscripted sequence cannot add new items to a list).
If the primary is a mapping object (such as a dictionary), the
subscript must have a type compatible with the mapping’s key type,
and the mapping is then asked to create a key/datum pair which maps
the subscript to the assigned object. This can either replace an
existing key/value pair with the same key value, or insert a new
key/value pair (if no key with the same value existed).
For user-defined objects, the "__setitem__()" method is called with
appropriate arguments.
* If the target is a slicing: The primary expression in the reference
is evaluated. It should yield a mutable sequence object (such as a
list). The assigned object should be a sequence object of the same
type. Next, the lower and upper bound expressions are evaluated,
insofar they are present; defaults are zero and the sequence’s
length. The bounds should evaluate to integers. If either bound is
negative, the sequence’s length is added to it. The resulting
bounds are clipped to lie between zero and the sequence’s length,
inclusive. Finally, the sequence object is asked to replace the
slice with the items of the assigned sequence. The length of the
slice may be different from the length of the assigned sequence,
thus changing the length of the target sequence, if the target
sequence allows it.
**CPython implementation detail:** In the current implementation, the
syntax for targets is taken to be the same as for expressions, and
invalid syntax is rejected during the code generation phase, causing
less detailed error messages.
Although the definition of assignment implies that overlaps between
the left-hand side and the right-hand side are ‘simultaneous’ (for
example "a, b = b, a" swaps two variables), overlaps *within* the
collection of assigned-to variables occur left-to-right, sometimes
resulting in confusion. For instance, the following program prints
"[0, 2]":
x = [0, 1]
i = 0
i, x[i] = 1, 2 # i is updated, then x[i] is updated
print(x)
See also:
**PEP 3132** - Extended Iterable Unpacking
The specification for the "*target" feature.
Augmented assignment statements
===============================
Augmented assignment is the combination, in a single statement, of a
binary operation and an assignment statement:
augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)
augtarget ::= identifier | attributeref | subscription | slicing
augop ::= "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="
| ">>=" | "<<=" | "&=" | "^=" | "|="
(See section Primaries for the syntax definitions of the last three
symbols.)
An augmented assignment evaluates the target (which, unlike normal
assignment statements, cannot be an unpacking) and the expression
list, performs the binary operation specific to the type of assignment
on the two operands, and assigns the result to the original target.
The target is only evaluated once.
An augmented assignment expression like "x += 1" can be rewritten as
"x = x + 1" to achieve a similar, but not exactly equal effect. In the
augmented version, "x" is only evaluated once. Also, when possible,
the actual operation is performed *in-place*, meaning that rather than
creating a new object and assigning that to the target, the old object
is modified instead.
Unlike normal assignments, augmented assignments evaluate the left-
hand side *before* evaluating the right-hand side. For example, "a[i]
+= f(x)" first looks-up "a[i]", then it evaluates "f(x)" and performs
the addition, and lastly, it writes the result back to "a[i]".
With the exception of assigning to tuples and multiple targets in a
single statement, the assignment done by augmented assignment
statements is handled the same way as normal assignments. Similarly,
with the exception of the possible *in-place* behavior, the binary
operation performed by augmented assignment is the same as the normal
binary operations.
For targets which are attribute references, the same caveat about
class and instance attributes applies as for regular assignments.
Annotated assignment statements
===============================
*Annotation* assignment is the combination, in a single statement, of
a variable or attribute annotation and an optional assignment
statement:
annotated_assignment_stmt ::= augtarget ":" expression
["=" (starred_expression | yield_expression)]
The difference from normal Assignment statements is that only single
target is allowed.
For simple names as assignment targets, if in class or module scope,
the annotations are evaluated and stored in a special class or module
attribute "__annotations__" that is a dictionary mapping from variable
names (mangled if private) to evaluated annotations. This attribute is
writable and is automatically created at the start of class or module
body execution, if annotations are found statically.
For expressions as assignment targets, the annotations are evaluated
if in class or module scope, but not stored.
If a name is annotated in a function scope, then this name is local
for that scope. Annotations are never evaluated and stored in function
scopes.
If the right hand side is present, an annotated assignment performs
the actual assignment before evaluating annotations (where
applicable). If the right hand side is not present for an expression
target, then the interpreter evaluates the target except for the last
"__setitem__()" or "__setattr__()" call.
See also:
**PEP 526** - Syntax for Variable Annotations
The proposal that added syntax for annotating the types of
variables (including class variables and instance variables),
instead of expressing them through comments.
**PEP 484** - Type hints
The proposal that added the "typing" module to provide a standard
syntax for type annotations that can be used in static analysis
tools and IDEs.
Changed in version 3.8: Now annotated assignments allow same
expressions in the right hand side as the regular assignments.
Previously, some expressions (like un-parenthesized tuple expressions)
caused a syntax error.
u>
Coroutines
**********
New in version 3.5.
Coroutine function definition
=============================
async_funcdef ::= [decorators] "async" "def" funcname "(" [parameter_list] ")"
["->" expression] ":" suite
Execution of Python coroutines can be suspended and resumed at many
points (see *coroutine*). Inside the body of a coroutine function,
"await" and "async" identifiers become reserved keywords; "await"
expressions, "async for" and "async with" can only be used in
coroutine function bodies.
Functions defined with "async def" syntax are always coroutine
functions, even if they do not contain "await" or "async" keywords.
It is a "SyntaxError" to use a "yield from" expression inside the body
of a coroutine function.
An example of a coroutine function:
async def func(param1, param2):
do_stuff()
await some_coroutine()
The "async for" statement
=========================
async_for_stmt ::= "async" for_stmt
An *asynchronous iterable* is able to call asynchronous code in its
*iter* implementation, and *asynchronous iterator* can call
asynchronous code in its *next* method.
The "async for" statement allows convenient iteration over
asynchronous iterators.
The following code:
async for TARGET in ITER:
SUITE
else:
SUITE2
Is semantically equivalent to:
iter = (ITER)
iter = type(iter).__aiter__(iter)
running = True
while running:
try:
TARGET = await type(iter).__anext__(iter)
except StopAsyncIteration:
running = False
else:
SUITE
else:
SUITE2
See also "__aiter__()" and "__anext__()" for details.
It is a "SyntaxError" to use an "async for" statement outside the body
of a coroutine function.
The "async with" statement
==========================
async_with_stmt ::= "async" with_stmt
An *asynchronous context manager* is a *context manager* that is able
to suspend execution in its *enter* and *exit* methods.
The following code:
async with EXPRESSION as TARGET:
SUITE
is semantically equivalent to:
manager = (EXPRESSION)
aexit = type(manager).__aexit__
aenter = type(manager).__aenter__
value = await aenter(manager)
hit_except = False
try:
TARGET = value
SUITE
except:
hit_except = True
if not await aexit(manager, *sys.exc_info()):
raise
finally:
if not hit_except:
await aexit(manager, None, None, None)
See also "__aenter__()" and "__aexit__()" for details.
It is a "SyntaxError" to use an "async with" statement outside the
body of a coroutine function.
See also:
**PEP 492** - Coroutines with async and await syntax
The proposal that made coroutines a proper standalone concept in
Python, and added supporting syntax.
-[ Footnotes ]-
[1] The exception is propagated to the invocation stack unless there
is a "finally" clause which happens to raise another exception.
That new exception causes the old one to be lost.
[2] A string literal appearing as the first statement in the function
body is transformed into the function’s "__doc__" attribute and
therefore the function’s *docstring*.
[3] A string literal appearing as the first statement in the class
body is transformed into the namespace’s "__doc__" item and
therefore the class’s *docstring*.
a� Identifiers (Names)
*******************
An identifier occurring as an atom is a name. See section Identifiers
and keywords for lexical definition and section Naming and binding for
documentation of naming and binding.
When the name is bound to an object, evaluation of the atom yields
that object. When a name is not bound, an attempt to evaluate it
raises a "NameError" exception.
**Private name mangling:** When an identifier that textually occurs in
a class definition begins with two or more underscore characters and
does not end in two or more underscores, it is considered a *private
name* of that class. Private names are transformed to a longer form
before code is generated for them. The transformation inserts the
class name, with leading underscores removed and a single underscore
inserted, in front of the name. For example, the identifier "__spam"
occurring in a class named "Ham" will be transformed to "_Ham__spam".
This transformation is independent of the syntactical context in which
the identifier is used. If the transformed name is extremely long
(longer than 255 characters), implementation defined truncation may
happen. If the class name consists only of underscores, no
transformation is done.
u
Literals
********
Python supports string and bytes literals and various numeric
literals:
literal ::= stringliteral | bytesliteral
| integer | floatnumber | imagnumber
Evaluation of a literal yields an object of the given type (string,
bytes, integer, floating point number, complex number) with the given
value. The value may be approximated in the case of floating point
and imaginary (complex) literals. See section Literals for details.
All literals correspond to immutable data types, and hence the
object’s identity is less important than its value. Multiple
evaluations of literals with the same value (either the same
occurrence in the program text or a different occurrence) may obtain
the same object or a different object with the same value.
uA7 Customizing attribute access
****************************
The following methods can be defined to customize the meaning of
attribute access (use of, assignment to, or deletion of "x.name") for
class instances.
object.__getattr__(self, name)
Called when the default attribute access fails with an
"AttributeError" (either "__getattribute__()" raises an
"AttributeError" because *name* is not an instance attribute or an
attribute in the class tree for "self"; or "__get__()" of a *name*
property raises "AttributeError"). This method should either
return the (computed) attribute value or raise an "AttributeError"
exception.
Note that if the attribute is found through the normal mechanism,
"__getattr__()" is not called. (This is an intentional asymmetry
between "__getattr__()" and "__setattr__()".) This is done both for
efficiency reasons and because otherwise "__getattr__()" would have
no way to access other attributes of the instance. Note that at
least for instance variables, you can fake total control by not
inserting any values in the instance attribute dictionary (but
instead inserting them in another object). See the
"__getattribute__()" method below for a way to actually get total
control over attribute access.
object.__getattribute__(self, name)
Called unconditionally to implement attribute accesses for
instances of the class. If the class also defines "__getattr__()",
the latter will not be called unless "__getattribute__()" either
calls it explicitly or raises an "AttributeError". This method
should return the (computed) attribute value or raise an
"AttributeError" exception. In order to avoid infinite recursion in
this method, its implementation should always call the base class
method with the same name to access any attributes it needs, for
example, "object.__getattribute__(self, name)".
Note:
This method may still be bypassed when looking up special methods
as the result of implicit invocation via language syntax or
built-in functions. See Special method lookup.
For certain sensitive attribute accesses, raises an auditing event
"object.__getattr__" with arguments "obj" and "name".
object.__setattr__(self, name, value)
Called when an attribute assignment is attempted. This is called
instead of the normal mechanism (i.e. store the value in the
instance dictionary). *name* is the attribute name, *value* is the
value to be assigned to it.
If "__setattr__()" wants to assign to an instance attribute, it
should call the base class method with the same name, for example,
"object.__setattr__(self, name, value)".
For certain sensitive attribute assignments, raises an auditing
event "object.__setattr__" with arguments "obj", "name", "value".
object.__delattr__(self, name)
Like "__setattr__()" but for attribute deletion instead of
assignment. This should only be implemented if "del obj.name" is
meaningful for the object.
For certain sensitive attribute deletions, raises an auditing event
"object.__delattr__" with arguments "obj" and "name".
object.__dir__(self)
Called when "dir()" is called on the object. A sequence must be
returned. "dir()" converts the returned sequence to a list and
sorts it.
Customizing module attribute access
===================================
Special names "__getattr__" and "__dir__" can be also used to
customize access to module attributes. The "__getattr__" function at
the module level should accept one argument which is the name of an
attribute and return the computed value or raise an "AttributeError".
If an attribute is not found on a module object through the normal
lookup, i.e. "object.__getattribute__()", then "__getattr__" is
searched in the module "__dict__" before raising an "AttributeError".
If found, it is called with the attribute name and the result is
returned.
The "__dir__" function should accept no arguments, and return a
sequence of strings that represents the names accessible on module. If
present, this function overrides the standard "dir()" search on a
module.
For a more fine grained customization of the module behavior (setting
attributes, properties, etc.), one can set the "__class__" attribute
of a module object to a subclass of "types.ModuleType". For example:
import sys
from types import ModuleType
class VerboseModule(ModuleType):
def __repr__(self):
return f'Verbose {self.__name__}'
def __setattr__(self, attr, value):
print(f'Setting {attr}...')
super().__setattr__(attr, value)
sys.modules[__name__].__class__ = VerboseModule
Note:
Defining module "__getattr__" and setting module "__class__" only
affect lookups made using the attribute access syntax – directly
accessing the module globals (whether by code within the module, or
via a reference to the module’s globals dictionary) is unaffected.
Changed in version 3.5: "__class__" module attribute is now writable.
New in version 3.7: "__getattr__" and "__dir__" module attributes.
See also:
**PEP 562** - Module __getattr__ and __dir__
Describes the "__getattr__" and "__dir__" functions on modules.
Implementing Descriptors
========================
The following methods only apply when an instance of the class
containing the method (a so-called *descriptor* class) appears in an
*owner* class (the descriptor must be in either the owner’s class
dictionary or in the class dictionary for one of its parents). In the
examples below, “the attribute” refers to the attribute whose name is
the key of the property in the owner class’ "__dict__".
object.__get__(self, instance, owner=None)
Called to get the attribute of the owner class (class attribute
access) or of an instance of that class (instance attribute
access). The optional *owner* argument is the owner class, while
*instance* is the instance that the attribute was accessed through,
or "None" when the attribute is accessed through the *owner*.
This method should return the computed attribute value or raise an
"AttributeError" exception.
**PEP 252** specifies that "__get__()" is callable with one or two
arguments. Python’s own built-in descriptors support this
specification; however, it is likely that some third-party tools
have descriptors that require both arguments. Python’s own
"__getattribute__()" implementation always passes in both arguments
whether they are required or not.
object.__set__(self, instance, value)
Called to set the attribute on an instance *instance* of the owner
class to a new value, *value*.
Note, adding "__set__()" or "__delete__()" changes the kind of
descriptor to a “data descriptor”. See Invoking Descriptors for
more details.
object.__delete__(self, instance)
Called to delete the attribute on an instance *instance* of the
owner class.
object.__set_name__(self, owner, name)
Called at the time the owning class *owner* is created. The
descriptor has been assigned to *name*.
Note:
"__set_name__()" is only called implicitly as part of the "type"
constructor, so it will need to be called explicitly with the
appropriate parameters when a descriptor is added to a class
after initial creation:
class A:
pass
descr = custom_descriptor()
A.attr = descr
descr.__set_name__(A, 'attr')
See Creating the class object for more details.
New in version 3.6.
The attribute "__objclass__" is interpreted by the "inspect" module as
specifying the class where this object was defined (setting this
appropriately can assist in runtime introspection of dynamic class
attributes). For callables, it may indicate that an instance of the
given type (or a subclass) is expected or required as the first
positional argument (for example, CPython sets this attribute for
unbound methods that are implemented in C).
Invoking Descriptors
====================
In general, a descriptor is an object attribute with “binding
behavior”, one whose attribute access has been overridden by methods
in the descriptor protocol: "__get__()", "__set__()", and
"__delete__()". If any of those methods are defined for an object, it
is said to be a descriptor.
The default behavior for attribute access is to get, set, or delete
the attribute from an object’s dictionary. For instance, "a.x" has a
lookup chain starting with "a.__dict__['x']", then
"type(a).__dict__['x']", and continuing through the base classes of
"type(a)" excluding metaclasses.
However, if the looked-up value is an object defining one of the
descriptor methods, then Python may override the default behavior and
invoke the descriptor method instead. Where this occurs in the
precedence chain depends on which descriptor methods were defined and
how they were called.
The starting point for descriptor invocation is a binding, "a.x". How
the arguments are assembled depends on "a":
Direct Call
The simplest and least common call is when user code directly
invokes a descriptor method: "x.__get__(a)".
Instance Binding
If binding to an object instance, "a.x" is transformed into the
call: "type(a).__dict__['x'].__get__(a, type(a))".
Class Binding
If binding to a class, "A.x" is transformed into the call:
"A.__dict__['x'].__get__(None, A)".
Super Binding
If "a" is an instance of "super", then the binding "super(B,
obj).m()" searches "obj.__class__.__mro__" for the base class "A"
immediately preceding "B" and then invokes the descriptor with the
call: "A.__dict__['m'].__get__(obj, obj.__class__)".
For instance bindings, the precedence of descriptor invocation depends
on which descriptor methods are defined. A descriptor can define any
combination of "__get__()", "__set__()" and "__delete__()". If it
does not define "__get__()", then accessing the attribute will return
the descriptor object itself unless there is a value in the object’s
instance dictionary. If the descriptor defines "__set__()" and/or
"__delete__()", it is a data descriptor; if it defines neither, it is
a non-data descriptor. Normally, data descriptors define both
"__get__()" and "__set__()", while non-data descriptors have just the
"__get__()" method. Data descriptors with "__set__()" and "__get__()"
defined always override a redefinition in an instance dictionary. In
contrast, non-data descriptors can be overridden by instances.
Python methods (including "staticmethod()" and "classmethod()") are
implemented as non-data descriptors. Accordingly, instances can
redefine and override methods. This allows individual instances to
acquire behaviors that differ from other instances of the same class.
The "property()" function is implemented as a data descriptor.
Accordingly, instances cannot override the behavior of a property.
__slots__
=========
*__slots__* allow us to explicitly declare data members (like
properties) and deny the creation of *__dict__* and *__weakref__*
(unless explicitly declared in *__slots__* or available in a parent.)
The space saved over using *__dict__* can be significant. Attribute
lookup speed can be significantly improved as well.
object.__slots__
This class variable can be assigned a string, iterable, or sequence
of strings with variable names used by instances. *__slots__*
reserves space for the declared variables and prevents the
automatic creation of *__dict__* and *__weakref__* for each
instance.
Notes on using *__slots__*
--------------------------
* When inheriting from a class without *__slots__*, the *__dict__* and
*__weakref__* attribute of the instances will always be accessible.
* Without a *__dict__* variable, instances cannot be assigned new
variables not listed in the *__slots__* definition. Attempts to
assign to an unlisted variable name raises "AttributeError". If
dynamic assignment of new variables is desired, then add
"'__dict__'" to the sequence of strings in the *__slots__*
declaration.
* Without a *__weakref__* variable for each instance, classes defining
*__slots__* do not support weak references to its instances. If weak
reference support is needed, then add "'__weakref__'" to the
sequence of strings in the *__slots__* declaration.
* *__slots__* are implemented at the class level by creating
descriptors (Implementing Descriptors) for each variable name. As a
result, class attributes cannot be used to set default values for
instance variables defined by *__slots__*; otherwise, the class
attribute would overwrite the descriptor assignment.
* The action of a *__slots__* declaration is not limited to the class
where it is defined. *__slots__* declared in parents are available
in child classes. However, child subclasses will get a *__dict__*
and *__weakref__* unless they also define *__slots__* (which should
only contain names of any *additional* slots).
* If a class defines a slot also defined in a base class, the instance
variable defined by the base class slot is inaccessible (except by
retrieving its descriptor directly from the base class). This
renders the meaning of the program undefined. In the future, a
check may be added to prevent this.
* Nonempty *__slots__* does not work for classes derived from
“variable-length” built-in types such as "int", "bytes" and "tuple".
* Any non-string iterable may be assigned to *__slots__*. Mappings may
also be used; however, in the future, special meaning may be
assigned to the values corresponding to each key.
* *__class__* assignment works only if both classes have the same
*__slots__*.
* Multiple inheritance with multiple slotted parent classes can be
used, but only one parent is allowed to have attributes created by
slots (the other bases must have empty slot layouts) - violations
raise "TypeError".
* If an iterator is used for *__slots__* then a descriptor is created
for each of the iterator’s values. However, the *__slots__*
attribute will be an empty iterator.
a� Attribute references
********************
An attribute reference is a primary followed by a period and a name:
attributeref ::= primary "." identifier
The primary must evaluate to an object of a type that supports
attribute references, which most objects do. This object is then
asked to produce the attribute whose name is the identifier. This
production can be customized by overriding the "__getattr__()" method.
If this attribute is not available, the exception "AttributeError" is
raised. Otherwise, the type and value of the object produced is
determined by the object. Multiple evaluations of the same attribute
reference may yield different objects.
a� Augmented assignment statements
*******************************
Augmented assignment is the combination, in a single statement, of a
binary operation and an assignment statement:
augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)
augtarget ::= identifier | attributeref | subscription | slicing
augop ::= "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="
| ">>=" | "<<=" | "&=" | "^=" | "|="
(See section Primaries for the syntax definitions of the last three
symbols.)
An augmented assignment evaluates the target (which, unlike normal
assignment statements, cannot be an unpacking) and the expression
list, performs the binary operation specific to the type of assignment
on the two operands, and assigns the result to the original target.
The target is only evaluated once.
An augmented assignment expression like "x += 1" can be rewritten as
"x = x + 1" to achieve a similar, but not exactly equal effect. In the
augmented version, "x" is only evaluated once. Also, when possible,
the actual operation is performed *in-place*, meaning that rather than
creating a new object and assigning that to the target, the old object
is modified instead.
Unlike normal assignments, augmented assignments evaluate the left-
hand side *before* evaluating the right-hand side. For example, "a[i]
+= f(x)" first looks-up "a[i]", then it evaluates "f(x)" and performs
the addition, and lastly, it writes the result back to "a[i]".
With the exception of assigning to tuples and multiple targets in a
single statement, the assignment done by augmented assignment
statements is handled the same way as normal assignments. Similarly,
with the exception of the possible *in-place* behavior, the binary
operation performed by augmented assignment is the same as the normal
binary operations.
For targets which are attribute references, the same caveat about
class and instance attributes applies as for regular assignments.
z�Await expression
****************
Suspend the execution of *coroutine* on an *awaitable* object. Can
only be used inside a *coroutine function*.
await_expr ::= "await" primary
New in version 3.5.
uj Binary arithmetic operations
****************************
The binary arithmetic operations have the conventional priority
levels. Note that some of these operations also apply to certain non-
numeric types. Apart from the power operator, there are only two
levels, one for multiplicative operators and one for additive
operators:
m_expr ::= u_expr | m_expr "*" u_expr | m_expr "@" m_expr |
m_expr "//" u_expr | m_expr "/" u_expr |
m_expr "%" u_expr
a_expr ::= m_expr | a_expr "+" m_expr | a_expr "-" m_expr
The "*" (multiplication) operator yields the product of its arguments.
The arguments must either both be numbers, or one argument must be an
integer and the other must be a sequence. In the former case, the
numbers are converted to a common type and then multiplied together.
In the latter case, sequence repetition is performed; a negative
repetition factor yields an empty sequence.
The "@" (at) operator is intended to be used for matrix
multiplication. No builtin Python types implement this operator.
New in version 3.5.
The "/" (division) and "//" (floor division) operators yield the
quotient of their arguments. The numeric arguments are first
converted to a common type. Division of integers yields a float, while
floor division of integers results in an integer; the result is that
of mathematical division with the ‘floor’ function applied to the
result. Division by zero raises the "ZeroDivisionError" exception.
The "%" (modulo) operator yields the remainder from the division of
the first argument by the second. The numeric arguments are first
converted to a common type. A zero right argument raises the
"ZeroDivisionError" exception. The arguments may be floating point
numbers, e.g., "3.14%0.7" equals "0.34" (since "3.14" equals "4*0.7 +
0.34".) The modulo operator always yields a result with the same sign
as its second operand (or zero); the absolute value of the result is
strictly smaller than the absolute value of the second operand [1].
The floor division and modulo operators are connected by the following
identity: "x == (x//y)*y + (x%y)". Floor division and modulo are also
connected with the built-in function "divmod()": "divmod(x, y) ==
(x//y, x%y)". [2].
In addition to performing the modulo operation on numbers, the "%"
operator is also overloaded by string objects to perform old-style
string formatting (also known as interpolation). The syntax for
string formatting is described in the Python Library Reference,
section printf-style String Formatting.
The floor division operator, the modulo operator, and the "divmod()"
function are not defined for complex numbers. Instead, convert to a
floating point number using the "abs()" function if appropriate.
The "+" (addition) operator yields the sum of its arguments. The
arguments must either both be numbers or both be sequences of the same
type. In the former case, the numbers are converted to a common type
and then added together. In the latter case, the sequences are
concatenated.
The "-" (subtraction) operator yields the difference of its arguments.
The numeric arguments are first converted to a common type.
a$ Binary bitwise operations
*************************
Each of the three bitwise operations has a different priority level:
and_expr ::= shift_expr | and_expr "&" shift_expr
xor_expr ::= and_expr | xor_expr "^" and_expr
or_expr ::= xor_expr | or_expr "|" xor_expr
The "&" operator yields the bitwise AND of its arguments, which must
be integers.
The "^" operator yields the bitwise XOR (exclusive OR) of its
arguments, which must be integers.
The "|" operator yields the bitwise (inclusive) OR of its arguments,
which must be integers.
u� Code Objects
************
Code objects are used by the implementation to represent “pseudo-
compiled” executable Python code such as a function body. They differ
from function objects because they don’t contain a reference to their
global execution environment. Code objects are returned by the built-
in "compile()" function and can be extracted from function objects
through their "__code__" attribute. See also the "code" module.
Accessing "__code__" raises an auditing event "object.__getattr__"
with arguments "obj" and ""__code__"".
A code object can be executed or evaluated by passing it (instead of a
source string) to the "exec()" or "eval()" built-in functions.
See The standard type hierarchy for more information.
a. The Ellipsis Object
*******************
This object is commonly used by slicing (see Slicings). It supports
no special operations. There is exactly one ellipsis object, named
"Ellipsis" (a built-in name). "type(Ellipsis)()" produces the
"Ellipsis" singleton.
It is written as "Ellipsis" or "...".
u The Null Object
***************
This object is returned by functions that don’t explicitly return a
value. It supports no special operations. There is exactly one null
object, named "None" (a built-in name). "type(None)()" produces the
same singleton.
It is written as "None".
u5 Type Objects
************
Type objects represent the various object types. An object’s type is
accessed by the built-in function "type()". There are no special
operations on types. The standard module "types" defines names for
all standard built-in types.
Types are written like this: "<class 'int'>".
a� Boolean operations
******************
or_test ::= and_test | or_test "or" and_test
and_test ::= not_test | and_test "and" not_test
not_test ::= comparison | "not" not_test
In the context of Boolean operations, and also when expressions are
used by control flow statements, the following values are interpreted
as false: "False", "None", numeric zero of all types, and empty
strings and containers (including strings, tuples, lists,
dictionaries, sets and frozensets). All other values are interpreted
as true. User-defined objects can customize their truth value by
providing a "__bool__()" method.
The operator "not" yields "True" if its argument is false, "False"
otherwise.
The expression "x and y" first evaluates *x*; if *x* is false, its
value is returned; otherwise, *y* is evaluated and the resulting value
is returned.
The expression "x or y" first evaluates *x*; if *x* is true, its value
is returned; otherwise, *y* is evaluated and the resulting value is
returned.
Note that neither "and" nor "or" restrict the value and type they
return to "False" and "True", but rather return the last evaluated
argument. This is sometimes useful, e.g., if "s" is a string that
should be replaced by a default value if it is empty, the expression
"s or 'foo'" yields the desired value. Because "not" has to create a
new value, it returns a boolean value regardless of the type of its
argument (for example, "not 'foo'" produces "False" rather than "''".)
a$ The "break" statement
*********************
break_stmt ::= "break"
"break" may only occur syntactically nested in a "for" or "while"
loop, but not nested in a function or class definition within that
loop.
It terminates the nearest enclosing loop, skipping the optional "else"
clause if the loop has one.
If a "for" loop is terminated by "break", the loop control target
keeps its current value.
When "break" passes control out of a "try" statement with a "finally"
clause, that "finally" clause is executed before really leaving the
loop.
u Emulating callable objects
**************************
object.__call__(self[, args...])
Called when the instance is “called” as a function; if this method
is defined, "x(arg1, arg2, ...)" roughly translates to
"type(x).__call__(x, arg1, ...)".
u� Calls
*****
A call calls a callable object (e.g., a *function*) with a possibly
empty series of *arguments*:
call ::= primary "(" [argument_list [","] | comprehension] ")"
argument_list ::= positional_arguments ["," starred_and_keywords]
["," keywords_arguments]
| starred_and_keywords ["," keywords_arguments]
| keywords_arguments
positional_arguments ::= positional_item ("," positional_item)*
positional_item ::= assignment_expression | "*" expression
starred_and_keywords ::= ("*" expression | keyword_item)
("," "*" expression | "," keyword_item)*
keywords_arguments ::= (keyword_item | "**" expression)
("," keyword_item | "," "**" expression)*
keyword_item ::= identifier "=" expression
An optional trailing comma may be present after the positional and
keyword arguments but does not affect the semantics.
The primary must evaluate to a callable object (user-defined
functions, built-in functions, methods of built-in objects, class
objects, methods of class instances, and all objects having a
"__call__()" method are callable). All argument expressions are
evaluated before the call is attempted. Please refer to section
Function definitions for the syntax of formal *parameter* lists.
If keyword arguments are present, they are first converted to
positional arguments, as follows. First, a list of unfilled slots is
created for the formal parameters. If there are N positional
arguments, they are placed in the first N slots. Next, for each
keyword argument, the identifier is used to determine the
corresponding slot (if the identifier is the same as the first formal
parameter name, the first slot is used, and so on). If the slot is
already filled, a "TypeError" exception is raised. Otherwise, the
value of the argument is placed in the slot, filling it (even if the
expression is "None", it fills the slot). When all arguments have
been processed, the slots that are still unfilled are filled with the
corresponding default value from the function definition. (Default
values are calculated, once, when the function is defined; thus, a
mutable object such as a list or dictionary used as default value will
be shared by all calls that don’t specify an argument value for the
corresponding slot; this should usually be avoided.) If there are any
unfilled slots for which no default value is specified, a "TypeError"
exception is raised. Otherwise, the list of filled slots is used as
the argument list for the call.
**CPython implementation detail:** An implementation may provide
built-in functions whose positional parameters do not have names, even
if they are ‘named’ for the purpose of documentation, and which
therefore cannot be supplied by keyword. In CPython, this is the case
for functions implemented in C that use "PyArg_ParseTuple()" to parse
their arguments.
If there are more positional arguments than there are formal parameter
slots, a "TypeError" exception is raised, unless a formal parameter
using the syntax "*identifier" is present; in this case, that formal
parameter receives a tuple containing the excess positional arguments
(or an empty tuple if there were no excess positional arguments).
If any keyword argument does not correspond to a formal parameter
name, a "TypeError" exception is raised, unless a formal parameter
using the syntax "**identifier" is present; in this case, that formal
parameter receives a dictionary containing the excess keyword
arguments (using the keywords as keys and the argument values as
corresponding values), or a (new) empty dictionary if there were no
excess keyword arguments.
If the syntax "*expression" appears in the function call, "expression"
must evaluate to an *iterable*. Elements from these iterables are
treated as if they were additional positional arguments. For the call
"f(x1, x2, *y, x3, x4)", if *y* evaluates to a sequence *y1*, …, *yM*,
this is equivalent to a call with M+4 positional arguments *x1*, *x2*,
*y1*, …, *yM*, *x3*, *x4*.
A consequence of this is that although the "*expression" syntax may
appear *after* explicit keyword arguments, it is processed *before*
the keyword arguments (and any "**expression" arguments – see below).
So:
>>> def f(a, b):
... print(a, b)
...
>>> f(b=1, *(2,))
2 1
>>> f(a=1, *(2,))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() got multiple values for keyword argument 'a'
>>> f(1, *(2,))
1 2
It is unusual for both keyword arguments and the "*expression" syntax
to be used in the same call, so in practice this confusion does not
arise.
If the syntax "**expression" appears in the function call,
"expression" must evaluate to a *mapping*, the contents of which are
treated as additional keyword arguments. If a keyword is already
present (as an explicit keyword argument, or from another unpacking),
a "TypeError" exception is raised.
Formal parameters using the syntax "*identifier" or "**identifier"
cannot be used as positional argument slots or as keyword argument
names.
Changed in version 3.5: Function calls accept any number of "*" and
"**" unpackings, positional arguments may follow iterable unpackings
("*"), and keyword arguments may follow dictionary unpackings ("**").
Originally proposed by **PEP 448**.
A call always returns some value, possibly "None", unless it raises an
exception. How this value is computed depends on the type of the
callable object.
If it is—
a user-defined function:
The code block for the function is executed, passing it the
argument list. The first thing the code block will do is bind the
formal parameters to the arguments; this is described in section
Function definitions. When the code block executes a "return"
statement, this specifies the return value of the function call.
a built-in function or method:
The result is up to the interpreter; see Built-in Functions for the
descriptions of built-in functions and methods.
a class object:
A new instance of that class is returned.
a class instance method:
The corresponding user-defined function is called, with an argument
list that is one longer than the argument list of the call: the
instance becomes the first argument.
a class instance:
The class must define a "__call__()" method; the effect is then the
same as if that method was called.
u Class definitions
*****************
A class definition defines a class object (see section The standard
type hierarchy):
classdef ::= [decorators] "class" classname [inheritance] ":" suite
inheritance ::= "(" [argument_list] ")"
classname ::= identifier
A class definition is an executable statement. The inheritance list
usually gives a list of base classes (see Metaclasses for more
advanced uses), so each item in the list should evaluate to a class
object which allows subclassing. Classes without an inheritance list
inherit, by default, from the base class "object"; hence,
class Foo:
pass
is equivalent to
class Foo(object):
pass
The class’s suite is then executed in a new execution frame (see
Naming and binding), using a newly created local namespace and the
original global namespace. (Usually, the suite contains mostly
function definitions.) When the class’s suite finishes execution, its
execution frame is discarded but its local namespace is saved. [3] A
class object is then created using the inheritance list for the base
classes and the saved local namespace for the attribute dictionary.
The class name is bound to this class object in the original local
namespace.
The order in which attributes are defined in the class body is
preserved in the new class’s "__dict__". Note that this is reliable
only right after the class is created and only for classes that were
defined using the definition syntax.
Class creation can be customized heavily using metaclasses.
Classes can also be decorated: just like when decorating functions,
@f1(arg)
@f2
class Foo: pass
is roughly equivalent to
class Foo: pass
Foo = f1(arg)(f2(Foo))
The evaluation rules for the decorator expressions are the same as for
function decorators. The result is then bound to the class name.
**Programmer’s note:** Variables defined in the class definition are
class attributes; they are shared by instances. Instance attributes
can be set in a method with "self.name = value". Both class and
instance attributes are accessible through the notation “"self.name"”,
and an instance attribute hides a class attribute with the same name
when accessed in this way. Class attributes can be used as defaults
for instance attributes, but using mutable values there can lead to
unexpected results. Descriptors can be used to create instance
variables with different implementation details.
See also:
**PEP 3115** - Metaclasses in Python 3000
The proposal that changed the declaration of metaclasses to the
current syntax, and the semantics for how classes with
metaclasses are constructed.
**PEP 3129** - Class Decorators
The proposal that added class decorators. Function and method
decorators were introduced in **PEP 318**.
u�'