# data[].attributes.attachment_caption
Lenguajes de programación. Características y tipos

# data[].attributes.attachment_caption
Paradigmas de programación - Wikipedia, la enciclopedia libre

# data[].attributes.attachment_link.title
Paradigma de programación - Wikipedia, la enciclopedia libre

# data[].attributes.attachment_link.description
Un paradigma de programación representa un enfoque particular o filosofía para diseñar soluciones. Los paradigmas difieren unos de otros, en los conceptos y la forma de abstraer los elementos involucrados en un problema, así como en los pasos que integran su solución del problema, en otras palabras, el cómputo.

# data[].attributes.attachment_link.title
¡TODOS los PARADIGMAS de PROGRAMACIÓN explicados en 6 minutos!

# data[].attributes.attachment_link.title
6 Proyectos de Python Básicos - Curso Completo Paso a Paso

# data[].attributes.attachment_link.readable_text
The following sections describe the standard types that are built into the interpreter.

The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions.

Some collection classes are mutable. The methods that add, subtract, or rearrange their members in place, and don't return a specific item, never return the collection instance itself but .

Some operations are supported by several object types; in particular, practically all objects can be compared for equality, tested for truth value, and converted to a string (with the function or the slightly different function). The latter function is implicitly used when an object is written by the function.

Comparisons

There are eight comparison operations in Python. They all have the same priority (which is higher than that of the Boolean operations). Comparisons can be chained arbitrarily; for example, is equivalent to , except that y is evaluated only once (but in both cases z is not evaluated at all when is found to be false).

This table summarizes the comparison operations:

Objects of different types, except different numeric types, never compare equal. The operator is always defined but for some object types (for example, class objects) is equivalent to . The , , and operators are only defined where they make sense; for example, they raise a exception when one of the arguments is a complex number.

Instances of a class cannot be ordered with respect to other instances of the same class, or other types of object, unless the class defines enough of the methods , , , and (in general, and are sufficient, if you want the conventional meanings of the comparison operators).

The behavior of the and operators cannot be customized; also they can be applied to any two objects and never raise an exception.

There are three distinct numeric types: integers, floating point numbers, and complex numbers. In addition, Booleans are a subtype of integers. Integers have unlimited precision. Floating point numbers are usually implemented using in C; information about the precision and internal representation of floating point numbers for the machine on which your program is running is available in . Complex numbers have a real and imaginary part, which are each a floating point number. To extract these parts from a complex number z, use and . (The standard library includes the additional numeric types , for rationals, and , for floating-point numbers with user-definable precision.)

Numbers are created by numeric literals or as the result of built-in functions and operators. Unadorned integer literals (including hex, octal and binary numbers) yield integers. Numeric literals containing a decimal point or an exponent sign yield floating point numbers. Appending or to a numeric literal yields an imaginary number (a complex number with a zero real part) which you can add to an integer or float to get a complex number with real and imaginary parts.

Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the "narrower" type is widened to that of the other, where integer is narrower than floating point, which is narrower than complex. A comparison between numbers of different types behaves as though the exact values of those numbers were being compared.

All numeric types (except complex) support the following operations (for priorities of the operations, see Operator precedence ):

Notes:

Bitwise Operations on Integer Types

Bitwise operations only make sense for integers. The result of bitwise operations is calculated as though carried out in two's complement with an infinite number of sign bits.

The priorities of the binary bitwise operations are all lower than the numeric operations and higher than the comparisons; the unary operation has the same priority as the other unary numeric operations ( and ).

This table lists the bitwise operations sorted in ascending priority:

Notes:

1. A left shift by n bits is equivalent to multiplication by .

2. A right shift by n bits is equivalent to floor division by .

3. Performing these calculations with at least one extra sign extension bit in a finite two's complement representation (a working bit-width of or more) is sufficient to get the same result as if there were an infinite number of sign bits.

Additional Methods on Integer Types

Return the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros:

Equivalent to:

Return the number of ones in the binary representation of the absolute value of the integer. This is also known as the population count. Example:

Equivalent to:

Return the integer represented by the given array of bytes.

The argument bytes must either be a bytes-like object or an iterable producing bytes.

The byteorder argument determines the byte order used to represent the integer, and defaults to . If byteorder is , the most significant byte is at the beginning of the byte array. If byteorder is , the most significant byte is at the end of the byte array. To request the native byte order of the host system, use as the byte order value.

The signed argument indicates whether two's complement is used to represent the integer.

Equivalent to:

Changed in version 3.11: Added default argument value for .

Return a pair of integers whose ratio is equal to the original integer and has a positive denominator. The integer ratio of integers (whole numbers) is always the integer as the numerator and as the denominator.

Additional Methods on Float

Two methods support conversion to and from hexadecimal strings. Since Python's floats are stored internally as binary numbers, converting a float to or from a decimal string usually involves a small rounding error. In contrast, hexadecimal strings allow exact representation and specification of floating-point numbers. This can be useful when debugging, and in numerical work.

A hexadecimal string takes the form:

where the optional may by either or , and are strings of hexadecimal digits, and is a decimal integer with an optional leading sign. Case is not significant, and there must be at least one hexadecimal digit in either the integer or the fraction. This syntax is similar to the syntax specified in section 6.4.4.2 of the C99 standard, and also to the syntax used in Java 1.5 onwards. In particular, the output of is usable as a hexadecimal floating-point literal in C or Java code, and hexadecimal strings produced by C's format character or Java's Double.toHexString are accepted by .

Note that the exponent is written in decimal rather than hexadecimal, and that it gives the power of 2 by which to multiply the coefficient. For example, the hexadecimal string represents the floating-point number , or :

Applying the reverse conversion to gives a different hexadecimal string representing the same number:

Booleans represent truth values. The type has exactly two constant instances: and .

The built-in function converts any value to a boolean, if the value can be interpreted as a truth value (see section Truth Value Testing above).

Deprecated since version 3.12: The use of the bitwise inversion operator is deprecated and will raise an error in Python 3.14.

is a subclass of (see Numeric Types - int, float, complex ). In many numeric contexts, and behave like the integers 0 and 1, respectively. However, relying on this is discouraged; explicitly convert using instead.

Iterator Types

Python supports a concept of iteration over containers. This is implemented using two distinct methods; these are used to allow user-defined classes to support iteration. Sequences, described below in more detail, always support the iteration methods.

One method needs to be defined for container objects to provide support:

Return an object. The object is required to support the iterator protocol described below. If a container supports different types of iteration, additional methods can be provided to specifically request iterators for those iteration types. (An example of an object supporting multiple forms of iteration would be a tree structure which supports both breadth-first and depth-first traversal.) This method corresponds to the slot of the type structure for Python objects in the Python/C API.

The iterator objects themselves are required to support the following two methods, which together form the iterator protocol:

Return the object itself. This is required to allow both containers and iterators to be used with the and statements. This method corresponds to the slot of the type structure for Python objects in the Python/C API.

Return the next item from the . If there are no further items, raise the exception. This method corresponds to the slot of the type structure for Python objects in the Python/C API.

Python defines several iterator objects to support iteration over general and specific sequence types, dictionaries, and other more specialized forms. The specific types are not important beyond their implementation of the iterator protocol.

Generator Types

Python's s provide a convenient way to implement the iterator protocol. If a container object's method is implemented as a generator, it will automatically return an iterator object (technically, a generator object) supplying the and methods. More information about generators can be found in the documentation for the yield expression .

There are three basic sequence types: lists, tuples, and range objects. Additional sequence types tailored for processing of binary data and text strings are described in dedicated sections.

Common Sequence Operations

This table lists the sequence operations sorted in ascending priority. In the table, s and t are sequences of the same type, n, i, j and k are integers and x is an arbitrary object that meets any type and value restrictions imposed by s.

The and operations have the same priorities as the comparison operations. The (concatenation) and (repetition) operations have the same priority as the corresponding numeric operations.

Sequences of the same type also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length. (For full details see Comparisons in the language reference.)

Notes:

1. While the and operations are used only for simple containment testing in the general case, some specialised sequences (such as , and ) also use them for subsequence testing:

2. Values of n less than are treated as (which yields an empty sequence of the same type as s). Note that items in the sequence s are not copied; they are referenced multiple times. This often haunts new Python programmers; consider:

What has happened is that is a one-element list containing an empty list, so all three elements of are references to this single empty list. Modifying any of the elements of modifies this single list. You can create a list of different lists this way:

Further explanation is available in the FAQ entry How do I create a multidimensional list? .

3. If i or j is negative, the index is relative to the end of sequence s: or is substituted. But note that is still .

4. The slice of s from i to j with step k is defined as the sequence of items with index such that . In other words, the indices are , , , and so on, stopping when j is reached (but never including j). When k is positive, i and j are reduced to if they are greater. When k is negative, i and j are reduced to if they are greater. If i or j are omitted or , they become "end" values (which end depends on the sign of k). Note, k cannot be zero. If k is , it is treated like .

5. Concatenating immutable sequences always results in a new object. This means that building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length. To get a linear runtime cost, you must switch to one of the alternatives below:

if concatenating objects, you can build a list and use at the end or else write to an instance and retrieve its value when complete

if concatenating objects, you can similarly use or , or you can do in-place concatenation with a object. objects are mutable and have an efficient overallocation mechanism

for other types, investigate the relevant class documentation

6. raises when x is not found in s. Not all implementations support passing the additional arguments i and j. These arguments allow efficient searching of subsections of the sequence. Passing the extra arguments is roughly equivalent to using , only without copying any data and with the returned index being relative to the start of the sequence rather than the start of the slice.

Mutable Sequence Types

In the table s is an instance of a mutable sequence type, t is any iterable object and x is an arbitrary object that meets any type and value restrictions imposed by s (for example, only accepts integers that meet the value restriction ).

Notes:

1. t must have the same length as the slice it is replacing.

2. The optional argument i defaults to , so that by default the last item is removed and returned.

3. and are included for consistency with the interfaces of mutable containers that don't support slicing operations (such as and ). is not part of the collections.abc.MutableSequence ABC, but most concrete mutable sequence classes provide it.

4. The value n is an integer, or an object implementing . Zero and negative values of n clear the sequence. Items in the sequence are not copied; they are referenced multiple times, as explained for under Common Sequence Operations .

Lists

Lists are mutable sequences, typically used to store collections of homogeneous items (where the precise degree of similarity will vary by application).

Lists may be constructed in several ways:

The constructor builds a list whose items are the same and in the same order as iterable's items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a list, a copy is made and returned, similar to . For example, returns and returns . If no argument is given, the constructor creates a new empty list, .

Lists implement all of the and sequence operations. Lists also provide the following additional method:

This method sorts the list in place, using only comparisons between items. Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state).

accepts two arguments that can only be passed by keyword ( keyword-only arguments ):

key specifies a function of one argument that is used to extract a comparison key from each list element (for example, key=str.lower ). The key corresponding to each item in the list is calculated once and then used for the entire sorting process. The default value of means that list items are sorted directly without calculating a separate key value.

The utility is available to convert a 2.x style cmp function to a key function.

reverse is a boolean value. If set to , then the list elements are sorted as if each comparison were reversed.

For sorting examples and a brief sorting tutorial, see Sorting Techniques .

CPython implementation detail: While a list is being sorted, the effect of attempting to mutate, or even inspect, the list is undefined. The C implementation of Python makes the list appear empty for the duration, and raises if it can detect that the list has been mutated during a sort.

Tuples

Tuples are immutable sequences, typically used to store collections of heterogeneous data (such as the 2-tuples produced by the built-in). Tuples are also used for cases where an immutable sequence of homogeneous data is needed (such as allowing storage in a or instance).

Tuples may be constructed in a number of ways:

The constructor builds a tuple whose items are the same and in the same order as iterable's items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a tuple, it is returned unchanged. For example, returns and returns . If no argument is given, the constructor creates a new empty tuple, .

Note that it is actually the comma which makes a tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity. For example, is a function call with three arguments, while is a function call with a 3-tuple as the sole argument.

Tuples implement all of the sequence operations.

Ranges

The arguments to the range constructor must be integers (either built-in or any object that implements the special method). If the step argument is omitted, it defaults to . If the start argument is omitted, it defaults to . If step is zero, is raised.

For a positive step, the contents of a range are determined by the formula where and .

For a negative step, the contents of the range are still determined by the formula , but the constraints are and .

A range object will be empty if does not meet the value constraint. Ranges do support negative indices, but these are interpreted as indexing from the end of the sequence determined by the positive indices.

Ranges containing absolute values larger than are permitted but some features (such as ) may raise .

Range examples:

Ranges implement all of the sequence operations except concatenation and repetition (due to the fact that range objects can only represent sequences that follow a strict pattern and repetition and concatenation will usually violate that pattern).

The value of the start parameter (or if the parameter was not supplied)

The value of the step parameter (or if the parameter was not supplied)

The advantage of the type over a regular or is that a object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the , and values, calculating individual items and subranges as needed).

Changed in version 3.2: Implement the Sequence ABC. Support slicing and negative indices. Test objects for membership in constant time instead of iterating through all items.

Changed in version 3.3: Define '==' and '!=' to compare range objects based on the sequence of values they define (instead of comparing based on object identity).

Textual data in Python is handled with objects, or strings. Strings are immutable of Unicode code points. String literals are written in a variety of ways:

Triple quoted strings may span multiple lines - all associated whitespace will be included in the string literal.

String literals that are part of a single expression and have only whitespace between them will be implicitly converted to a single string literal. That is, .

See String and Bytes literals for more about the various forms of string literal, including supported escape sequences , and the ("raw") prefix that disables most escape sequence processing.

Since there is no separate "character" type, indexing a string produces strings of length 1. That is, for a non-empty string s, .

Changed in version 3.3: For backwards compatibility with the Python 2 series, the prefix is once again permitted on string literals. It has no effect on the meaning of string literals and cannot be combined with the prefix.

Return a version of object. If object is not provided, returns the empty string. Otherwise, the behavior of depends on whether encoding or errors is given, as follows.

If neither encoding nor errors is given, returns , which is the "informal" or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a method, then falls back to returning .

If at least one of encoding or errors is given, object should be a bytes-like object (e.g. or ). In this case, if object is a (or ) object, then is equivalent to . Otherwise, the bytes object underlying the buffer object is obtained before calling . See Binary Sequence Types - bytes, bytearray, memoryview and Buffer Protocol for information on buffer objects.

Passing a object to without the encoding or errors arguments falls under the first case of returning the informal string representation (see also the command-line option to Python). For example:

For more information on the class and its methods, see Text Sequence Type - str and the String Methods section below. To output formatted strings, see the and Format String Syntax sections. In addition, see the Text Processing Services section.

String Methods

Strings implement all of the sequence operations, along with the additional methods described below.

Strings also support two styles of string formatting, one providing a large degree of flexibility and customization (see , Format String Syntax and Custom String Formatting ) and the other based on C style formatting that handles a narrower range of types and is slightly harder to use correctly, but is often faster for the cases it can handle ( printf-style String Formatting ).

The Text Processing Services section of the standard library covers a number of other modules that provide various text related utilities (including regular expression support in the module).

Return a copy of the string with its first character capitalized and the rest lowercased.

Changed in version 3.8: The first character is now put into titlecase rather than uppercase. This means that characters like digraphs will only have their first letter capitalized, instead of the full character.

Return a casefolded copy of the string. Casefolded strings may be used for caseless matching.

Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter is equivalent to . Since it is already lowercase, would do nothing to ; converts it to .

The casefolding algorithm is described in section 3.13 'Default Case Folding' of the Unicode Standard.

Return a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size. Tab positions occur every tabsize characters (default is 8, giving tab positions at columns 0, 8, 16 and so on). To expand the string, the current column is set to zero and the string is examined character by character. If the character is a tab (), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied.) If the character is a newline () or return (), it is copied and the current column is reset to zero. Any other character is copied unchanged and the current column is incremented by one regardless of how the character is represented when printed.

Return if all characters in the string are alphanumeric and there is at least one character, otherwise. A character is alphanumeric if one of the following returns : , c.isdecimal() , , or c.isnumeric() .

Return if the string is a valid identifier according to the language definition, section Identifiers and keywords .

Example:

Return if all cased characters in the string are lowercase and there is at least one cased character, otherwise.

Return if all characters in the string are printable or the string is empty, otherwise. Nonprintable characters are those characters defined in the Unicode character database as "Other" or "Separator", excepting the ASCII space (0x20) which is considered printable. (Note that printable characters in this context are those which should not be escaped when is invoked on a string. It has no bearing on the handling of strings written to or .)

Return if all cased characters in the string are uppercase and there is at least one cased character, otherwise.

Return a string which is the concatenation of the strings in iterable. A will be raised if there are any non-string values in iterable, including objects. The separator between elements is the string providing this method.

Return a copy of the string with all the cased characters converted to lowercase.

The lowercasing algorithm used is described in section 3.13 'Default Case Folding' of the Unicode Standard.

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or . Character keys will then be converted to ordinals.

If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to in the result.

Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.

If the string starts with the prefix string, return string[len(prefix):] . Otherwise, return a copy of the original string:

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)] . Otherwise, return a copy of the original string:

Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself.

Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

This method splits on the following line boundaries. In particular, the boundaries are a superset of universal newlines .

For example:

Unlike when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:

For comparison, gives:

Return a copy of the string with uppercase characters converted to lowercase and vice versa. Note that it is not necessarily true that .

Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.

For example:

The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:

Alternatively, a workaround for apostrophes can be constructed using regular expressions:

Return a copy of the string in which each character has been mapped through the given translation table. The table must be an object that implements indexing via , typically a or . When indexed by a Unicode ordinal (an integer), the table object can do any of the following: return a Unicode ordinal or a string, to map the character to one or more other characters; return , to delete the character from the return string; or raise a exception, to map the character to itself.

Return a copy of the string with all the cased characters converted to uppercase. Note that s.upper().isupper() might be if contains uncased characters or if the Unicode category of the resulting character(s) is not "Lu" (Letter, uppercase), but e.g. "Lt" (Letter, titlecase).

The uppercasing algorithm used is described in section 3.13 'Default Case Folding' of the Unicode Standard.

Return a copy of the string left filled with ASCII digits to make a string of length width. A leading sign prefix (/) is handled by inserting the padding after the sign character rather than before. The original string is returned if width is less than or equal to .

For example:

-style String Formatting

Note

The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals , the interface, or template strings may help avoid these errors. Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or extensibility.

String objects have one unique built-in operation: the operator (modulo). This is also known as the string formatting or interpolation operator. Given (where format is a string), conversion specifications in format are replaced with zero or more elements of values. The effect is similar to using the in the C language.

If format requires a single argument, values may be a single non-tuple object. Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary).

A conversion specifier contains two or more characters and has the following components, which must occur in this order:

1. Conversion flags (optional), which affect the result of some conversion types.

2. Minimum field width (optional). If specified as an (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.

3. Precision (optional), given as a (dot) followed by the precision. If specified as (an asterisk), the actual precision is read from the next element of the tuple in values, and the value to convert comes after the precision.

4. Length modifier (optional).

5. Conversion type.

When the right argument is a dictionary (or other mapping type), then the formats in the string must include a parenthesised mapping key into that dictionary inserted immediately after the character. The mapping key selects the value to be formatted from the mapping. For example:

In this case no specifiers may occur in a format (since they require a sequential parameter list).

The conversion flag characters are:

The conversion types are:

Notes:

1. The alternate form causes a leading or (depending on whether the or format was used) to be inserted before the first digit.

2. The alternate form causes the result to always contain a decimal point, even if no digits follow it.

The precision determines the number of digits after the decimal point and defaults to 6.

3. The alternate form causes the result to always contain a decimal point, and trailing zeroes are not removed as they would otherwise be.

The precision determines the number of significant digits before and after the decimal point and defaults to 6.

Since Python strings have an explicit length, conversions do not assume that is the end of the string.

Changed in version 3.1: conversions for numbers whose absolute value is over 1e50 are no longer replaced by conversions.

The core built-in types for manipulating binary data are and . They are supported by which uses the buffer protocol to access the memory of other binary objects without needing to make a copy.

Bytes Objects

Bytes objects are immutable sequences of single bytes. Since many major binary protocols are based on the ASCII text encoding, bytes objects offer several methods that are only valid when working with ASCII compatible data and are closely related to string objects in a variety of other ways.

Firstly, the syntax for bytes literals is largely the same as that for string literals, except that a prefix is added:

Only ASCII characters are permitted in bytes literals (regardless of the declared source code encoding). Any binary values over 127 must be entered into bytes literals using the appropriate escape sequence.

As with string literals, bytes literals may also use a prefix to disable processing of escape sequences. See String and Bytes literals for more about the various forms of bytes literal, including supported escape sequences.

While bytes literals and representations are based on ASCII text, bytes objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that (attempts to violate this restriction will trigger ). This is done deliberately to emphasise that while many binary formats include ASCII based elements and can be usefully manipulated with some text-oriented algorithms, this is not generally the case for arbitrary binary data (blindly applying text processing algorithms to binary data formats that are not ASCII compatible will usually lead to data corruption).

In addition to the literal forms, bytes objects can be created in a number of other ways:

Also see the built-in.

Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal numbers are a commonly used format for describing binary data. Accordingly, the bytes type has an additional class method to read data in that format:

A reverse conversion function exists to transform a bytes object into its hexadecimal representation.

Return a string object containing two hexadecimal digits for each byte in the instance.

If you want to make the hex string easier to read, you can specify a single character separator sep parameter to include in the output. By default, this separator will be included between each byte. A second optional bytes_per_sep parameter controls the spacing. Positive values calculate the separator position from the right, negative values from the left.

Changed in version 3.8: now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.

Since bytes objects are sequences of integers (akin to a tuple), for a bytes object b, will be an integer, while will be a bytes object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1)

The representation of bytes objects uses the literal format () since it is often more useful than e.g. . You can always convert a bytes object into a list of integers using .

Bytearray Objects

Since bytearray objects are sequences of integers (akin to a list), for a bytearray object b, will be an integer, while will be a bytearray object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1)

The representation of bytearray objects uses the bytes literal format ( bytearray(b'...') ) since it is often more useful than e.g. . You can always convert a bytearray object into a list of integers using .

Bytes and Bytearray Operations

Both bytes and bytearray objects support the sequence operations. They interoperate not just with operands of the same type, but with any bytes-like object . Due to this flexibility, they can be freely mixed in operations without causing errors. However, the return type of the result may depend on the order of operands.

Note

The methods on bytes and bytearray objects don't accept strings as their arguments, just as the methods on strings don't accept bytes as their arguments. For example, you have to write:

and:

Some bytes and bytearray operations assume the use of ASCII compatible binary formats, and hence should be avoided when working with arbitrary binary data. These restrictions are covered below.

Note

Using these ASCII based operations to manipulate binary data that is not stored in an ASCII based format may lead to data corruption.

The following methods on bytes and bytearray objects can be used with arbitrary binary data.

If the binary data starts with the prefix string, return bytes[len(prefix):] . Otherwise, return a copy of the original binary data:

The prefix may be any bytes-like object .

If the binary data ends with the suffix string and that suffix is not empty, return bytes[:-len(suffix)] . Otherwise, return a copy of the original binary data:

The suffix may be any bytes-like object .

This static method returns a translation table usable for that will map each character in from into the character at the same position in to; from and to must both be bytes-like objects and have the same length.

Return a copy of the bytes or bytearray object where all bytes occurring in the optional argument delete are removed, and the remaining bytes have been mapped through the given translation table, which must be a bytes object of length 256.

Set the table argument to for translations that only delete characters:

Changed in version 3.6: delete is now supported as a keyword argument.

The following methods on bytes and bytearray objects have default behaviours that assume the use of ASCII compatible binary formats, but can still be used with arbitrary binary data by passing appropriate arguments. Note that all of the bytearray methods in this section do not operate in place, and instead produce new objects.

The binary sequence of byte values to remove may be any bytes-like object . See for a method that will remove a single prefix string rather than all of a set of characters. For example:

The binary sequence of byte values to remove may be any bytes-like object . See for a method that will remove a single suffix string rather than all of a set of characters. For example:

The following methods on bytes and bytearray objects assume the use of ASCII compatible binary formats and should not be applied to arbitrary binary data. Note that all of the bytearray methods in this section do not operate in place, and instead produce new objects.

Return a copy of the sequence where all ASCII tab characters are replaced by one or more ASCII spaces, depending on the current column and the given tab size. Tab positions occur every tabsize bytes (default is 8, giving tab positions at columns 0, 8, 16 and so on). To expand the sequence, the current column is set to zero and the sequence is examined byte by byte. If the byte is an ASCII tab character (), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied.) If the current byte is an ASCII newline () or carriage return (), it is copied and the current column is reset to zero. Any other byte value is copied unchanged and the current column is incremented by one regardless of how the byte value is represented when printed:

Return a list of the lines in the binary sequence, breaking at ASCII line boundaries. This method uses the universal newlines approach to splitting lines. Line breaks are not included in the resulting list unless keepends is given and true.

For example:

Unlike when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:

-style Bytes Formatting

Note

The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). If the value being printed may be a tuple or dictionary, wrap it in a tuple.

Bytes objects (/) have one unique built-in operation: the operator (modulo). This is also known as the bytes formatting or interpolation operator. Given (where format is a bytes object), conversion specifications in format are replaced with zero or more elements of values. The effect is similar to using the in the C language.

If format requires a single argument, values may be a single non-tuple object. Otherwise, values must be a tuple with exactly the number of items specified by the format bytes object, or a single mapping object (for example, a dictionary).

A conversion specifier contains two or more characters and has the following components, which must occur in this order:

1. Conversion flags (optional), which affect the result of some conversion types.

2. Minimum field width (optional). If specified as an (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.

3. Precision (optional), given as a (dot) followed by the precision. If specified as (an asterisk), the actual precision is read from the next element of the tuple in values, and the value to convert comes after the precision.

4. Length modifier (optional).

5. Conversion type.

When the right argument is a dictionary (or other mapping type), then the formats in the bytes object must include a parenthesised mapping key into that dictionary inserted immediately after the character. The mapping key selects the value to be formatted from the mapping. For example:

In this case no specifiers may occur in a format (since they require a sequential parameter list).

The conversion flag characters are:

The conversion types are:

Notes:

1. The alternate form causes a leading or (depending on whether the or format was used) to be inserted before the first digit.

2. The alternate form causes the result to always contain a decimal point, even if no digits follow it.

The precision determines the number of digits after the decimal point and defaults to 6.

3. The alternate form causes the result to always contain a decimal point, and trailing zeroes are not removed as they would otherwise be.

The precision determines the number of significant digits before and after the decimal point and defaults to 6.

Note

The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.

See also

PEP 461 - Adding % formatting to bytes and bytearray

Memory Views

Create a that references object. object must support the buffer protocol. Built-in objects that support the buffer protocol include and .

A has the notion of an element, which is the atomic memory unit handled by the originating object. For many simple types such as and , an element is a single byte, but other types such as may have bigger elements.

is equal to the length of , which is the nested list representation of the view. If , this is equal to the number of elements in the view.

If is one of the native format specifiers from the module, indexing with an integer or a tuple of integers is also supported and returns a single element with the correct type. One-dimensional memoryviews can be indexed with an integer or a one-integer tuple. Multi-dimensional memoryviews can be indexed with tuples of exactly ndim integers where ndim is the number of dimensions. Zero-dimensional memoryviews can be indexed with the empty tuple.

Here is an example with a non-byte format:

If the underlying object is writable, the memoryview supports one-dimensional slice assignment. Resizing is not allowed:

One-dimensional memoryviews of (read-only) types with formats 'B', 'b' or 'c' are also hashable. The hash is defined as :

Changed in version 3.3: One-dimensional memoryviews can now be sliced. One-dimensional memoryviews with formats 'B', 'b' or 'c' are now .

Changed in version 3.5: memoryviews can now be indexed with tuple of integers.

A memoryview and a PEP 3118 exporter are equal if their shapes are equivalent and if all corresponding values are equal when the operands' respective format codes are interpreted using syntax.

Note that, as with floating point numbers, does not imply for memoryview objects.

Changed in version 3.3: Previous versions compared the raw memory disregarding the item format and the logical array structure.

Added in version 3.8: order can be {'C', 'F', 'A'}. When order is 'C' or 'F', the data of the original array is converted to C or Fortran order. For contiguous views, 'A' returns an exact copy of the physical memory. In particular, in-memory Fortran order is preserved. For non-contiguous views, the data is converted to C first. order=None is the same as order='C'.

Cast a memoryview to a new format or shape. shape defaults to[byte_length//new_itemsize] , which means that the result view will be one-dimensional. The return value is a new memoryview, but the buffer itself is not copied. Supported casts are 1D -> C- contiguous and C-contiguous -> 1D.

Cast 1D/long to 1D/unsigned bytes:

Cast 1D/unsigned bytes to 1D/char:

Cast 1D/bytes to 3D/ints to 1D/signed char:

Cast 1D/unsigned long to 2D/unsigned long:

Changed in version 3.5: The source format is no longer restricted when casting to a byte view.

There are also several readonly attributes available:

. This is the amount of space in bytes that the array would use in a contiguous representation. It is not necessarily equal to :

Multi-dimensional arrays:

A bool indicating whether the memory is read only.

An integer indicating how many dimensions of a multi-dimensional array the memory represents.

Used internally for PIL-style arrays. The value is informational only.

A set object is an unordered collection of distinct objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. (For other containers see the built-in , , and classes, and the module.)

Like other collections, sets support , , and . Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior.

There are currently two built-in set types, and . The type is mutable - the contents can be changed using methods like and . Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set. The type is immutable and - its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set.

Non-empty sets (not frozensets) can be created by placing a comma-separated list of elements within braces, for example: , in addition to the constructor.

The constructors for both classes work the same:

Return a new set or frozenset object whose elements are taken from iterable. The elements of a set must be . To represent sets of sets, the inner sets must be objects. If iterable is not specified, a new empty set is returned.

Sets can be created by several means:

Return if the set has no elements in common with other. Sets are disjoint if and only if their intersection is the empty set.

Note, the non-operator versions of , , , , , and methods will accept any iterable as an argument. In contrast, their operator based counterparts require their arguments to be sets. This precludes error-prone constructions like in favor of the more readable set('abc').intersection('cbs') .

Both and support set to set comparisons. Two sets are equal if and only if every element of each set is contained in the other (each is a subset of the other). A set is less than another set if and only if the first set is a proper subset of the second set (is a subset, but is not equal). A set is greater than another set if and only if the first set is a proper superset of the second set (is a superset, but is not equal).

Instances of are compared to instances of based on their members. For example, returns and so does .

The subset and equality comparisons do not generalize to a total ordering function. For example, any two nonempty disjoint sets are not equal and are not subsets of each other, so all of the following return : , , or .

Set elements, like dictionary keys, must be .

Binary operations that mix instances with return the type of the first operand. For example: returns an instance of .

The following table lists operations available for that do not apply to immutable instances of :

Remove element elem from the set if it is present.

Note, the non-operator versions of the , , , and symmetric_difference_update() methods will accept any iterable as an argument.

Note, the elem argument to the , , and methods may be a set. To support searching for an equivalent frozenset, a temporary one is created from elem.

A object maps values to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, the dictionary. (For other containers see the built-in , , and classes, and the module.)

A dictionary's keys are almost arbitrary values. Values that are not , that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys. Values that compare equal (such as , , and ) can be used interchangeably to index the same dictionary entry.

Return a new dictionary initialized from an optional positional argument and a possibly empty set of keyword arguments.

Dictionaries can be created by several means:

If no positional argument is given, an empty dictionary is created. If a positional argument is given and it is a mapping object, a dictionary is created with the same key-value pairs as the mapping object. Otherwise, the positional argument must be an object. Each item in the iterable must itself be an iterable with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value. If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary.

If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument. If a key being added is already present, the value from the keyword argument replaces the value from the positional argument.

To illustrate, the following examples all return a dictionary equal to :

Providing keyword arguments as in the first example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.

These are the operations that dictionaries support (and therefore, custom mapping types should support too):

If a subclass of dict defines a method and key is not present, the operation calls that method with the key key as argument. The operation then returns or raises whatever is returned or raised by the__missing__(key) call. No other operations or methods invoke . If is not defined, is raised. must be a method; it cannot be an instance variable:

The example above shows part of the implementation of . A different method is used by collections.defaultdict .

Return an iterator over the keys of the dictionary. This is a shortcut for .

Create a new dictionary with keys from iterable and values set to value.

is a class method that returns a new dictionary. value defaults to . All of the values refer to just a single instance, so it generally doesn't make sense for value to be a mutable object such as an empty list. To get distinct values, use a dict comprehension instead.

Return a new view of the dictionary's items ( pairs). See the documentation of view objects .

Return a new view of the dictionary's keys. See the documentation of view objects .

Remove and return a pair from the dictionary. Pairs are returned in LIFO order.

is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling raises a .

Changed in version 3.7: LIFO order is now guaranteed. In prior versions, would return an arbitrary key/value pair.

Return a reverse iterator over the keys of the dictionary. This is a shortcut for reversed(d.keys()) .

Update the dictionary with the key/value pairs from other, overwriting existing keys. Return .

accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: .

Return a new view of the dictionary's values. See the documentation of view objects .

An equality comparison between one dict.values() view and another will always return . This also applies when comparing dict.values() to itself:

Create a new dictionary with the merged keys and values of d and other, which must both be dictionaries. The values of other take priority when d and other share keys.

Update the dictionary d with keys and values from other, which may be either a or an of key/value pairs. The values of other take priority when d and other share keys.

Dictionaries compare equal if and only if they have the same pairs (regardless of ordering). Order comparisons ('<', '<=', '>=', '>') raise .

Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end.

Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.

Dictionaries and dictionary views are reversible.

Changed in version 3.8: Dictionaries are now reversible.

Dictionary view objects

The objects returned by , and are view objects. They provide a dynamic view on the dictionary's entries, which means that when the dictionary changes, the view reflects these changes.

Dictionary views can be iterated over to yield their respective data, and support membership tests:

Return the number of entries in the dictionary.

Return a reverse iterator over the keys, values or items of the dictionary. The view will be iterated in reverse order of the insertion.

Changed in version 3.8: Dictionary views are now reversible.

Keys views are set-like since their entries are unique and . Items views also have set-like operations since the (key, value) pairs are unique and the keys are hashable. If all values in an items view are hashable as well, then the items view can interoperate with other sets. (Values views are not treated as set-like since the entries are generally not unique.) For set-like views, all of the operations defined for the abstract base class are available (for example, , , or ). While using set operators, set-like views accept any iterable as the other operand, unlike sets which only accept sets as the input.

An example of dictionary view usage:

Context Manager Types

Enter the runtime context and return either this object or another object related to the runtime context. The value returned by this method is bound to the identifier in the clause of statements using this context manager.

An example of a context manager that returns itself is a file object . File objects return themselves from __enter__() to allow to be used as the context expression in a statement.

An example of a context manager that returns a related object is the one returned by . These managers set the active decimal context to a copy of the original decimal context and then return the copy. This allows changes to be made to the current decimal context in the body of the statement without affecting code outside the statement.

Exit the runtime context and return a Boolean flag indicating if any exception that occurred should be suppressed. If an exception occurred while executing the body of the statement, the arguments contain the exception type, value and traceback information. Otherwise, all three arguments are .

Returning a true value from this method will cause the statement to suppress the exception and continue execution with the statement immediately following the statement. Otherwise the exception continues propagating after this method has finished executing. Exceptions that occur during execution of this method will replace any exception that occurred in the body of the statement.

Python's s and the contextlib.contextmanager decorator provide a convenient way to implement these protocols. If a generator function is decorated with thecontextlib.contextmanager decorator, it will return a context manager implementing the necessary and methods, rather than the iterator produced by an undecorated generator function.

Note that there is no specific slot for any of these methods in the type structure for Python objects in the Python/C API. Extension types wanting to define these methods must provide them as a normal Python accessible method. Compared to the overhead of setting up the runtime context, the overhead of a single class dictionary lookup is negligible.

The core built-in types for type annotations are Generic Alias and .

Generic Alias Type

GenericAlias objects are generally created by subscripting a class. They are most often used with container classes , such as or . For example, is a GenericAlias object created by subscripting the class with the argument . GenericAlias objects are intended primarily for use with type annotations .

A GenericAlias object acts as a proxy for a generic type , implementing parameterized generics.

For a container class, the argument(s) supplied to a subscription of the class may indicate the type(s) of the elements an object contains. For example, can be used in type annotations to signify a in which all the elements are of type .

For a class which defines but is not a container, the argument(s) supplied to a subscription of the class will often indicate the return type(s) of one or more methods defined on an object. For example, can be used on both the data type and the data type:

GenericAlias objects are instances of the class , which can also be used to create GenericAlias objects directly.

The builtin functions and do not accept GenericAlias types for their second argument:

The Python runtime does not enforce type annotations . This extends to generic types and their type parameters. When creating a container object from a GenericAlias , the elements in the container are not checked against their type. For example, the following code is discouraged, but will run without errors:

Furthermore, parameterized generics erase type parameters during object creation:

The method of generic containers will raise an exception to disallow mistakes like dict[str][str] :

However, such expressions are valid when type variables are used. The index must have as many elements as there are type variable items in the GenericAlias object's .

Standard Generic Classes

The following standard library classes support parameterized generics. This list is non-exhaustive.

Special Attributes of GenericAlias objects

All parameterized generics implement special read-only attributes.

This attribute points at the non-parameterized generic class:

This attribute is a (possibly of length 1) of generic types passed to the original of the generic class:

This attribute is a lazily computed tuple (possibly empty) of unique type variables found in :

Note

A GenericAlias object with parameters may not have correct__parameters__ after substitution because is intended primarily for static type checking.

See also

Introducing Python's framework for type annotations.

PEP 585 - Type Hinting Generics In Standard Collections

Documentation on how to implement generic classes that can be parameterized at runtime and understood by static type-checkers.

Other Built-in Types

The interpreter supports several other kinds of objects. Most of these support only one or two operations.

Modules

The only special operation on a module is attribute access: , where m is a module and name accesses a name defined in m's symbol table. Module attributes can be assigned to. (Note that the statement is not, strictly speaking, an operation on a module object; does not require a module object named foo to exist, rather it requires an (external) definition for a module named foo somewhere.)

A special attribute of every module is . This is the dictionary containing the module's symbol table. Modifying this dictionary will actually change the module's symbol table, but direct assignment to the attribute is not possible (you can write , which defines to be , but you can't write ). Modifying directly is not recommended.

Modules built into the interpreter are written like this: . If loaded from a file, they are written as .

Classes and Class Instances

See Objects, values and types and Class definitions for these.

Functions

Function objects are created by function definitions. The only operation on a function object is to call it: func(argument-list) .

There are really two flavors of function objects: built-in functions and user-defined functions. Both support the same operation (to call the function), but the implementation is different, hence the different object types.

See Function definitions for more information.

Methods

Methods are functions that are called using the attribute notation. There are two flavors: built-in methods (such as on lists) and class instance method . Built-in methods are described with the types that support them.

If you access a method (a function defined in a class namespace) through an instance, you get a special object: a bound method (also called instance method ) object. When called, it will add the argument to the argument list. Bound methods have two special read-only attributes: is the object on which the method operates, and is the function implementing the method. Calling is completely equivalent to calling .

Like function objects , bound method objects support getting arbitrary attributes. However, since method attributes are actually stored on the underlying function object (), setting method attributes on bound methods is disallowed. Attempting to set an attribute on a method results in an being raised. In order to set a method attribute, you need to explicitly set it on the underlying function object:

See Instance methods for more information.

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 function and can be extracted from function objects through their attribute. See also the module.

See The standard type hierarchy for more information.

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 (a built-in name). produces the same singleton.

The Ellipsis Object

This object is commonly used by slicing (see ). It supports no special operations. There is exactly one ellipsis object, named (a built-in name). type(Ellipsis)() produces the singleton.

The NotImplemented Object

This object is returned from comparisons and binary operations when they are asked to operate on types they don't support. See Comparisons for more information. There is exactly one object. type(NotImplemented)() produces the singleton instance.

It is written as NotImplemented .

Internal Objects

See The standard type hierarchy for this information. It describes stack frame objects , traceback objects , and slice objects.

Special Attributes

The qualified name of the class, function, method, descriptor, or generator instance.

Each class keeps a list of weak references to its immediate subclasses. This method returns a list of all those references still alive. The list is in definition order. Example:

Integer string conversion length limitation

CPython has a global limit for converting between and to mitigate denial of service attacks. This limit only applies to decimal or other non-power-of-two number bases. Hexadecimal, octal, and binary conversions are unlimited. The limit can be configured.

The type in CPython is an arbitrary length number stored in binary form (commonly known as a "bignum"). There exists no algorithm that can convert a string to a binary integer or a binary integer to a string in linear time, unless the base is a power of 2. Even the best known algorithms for base 10 have sub-quadratic complexity. Converting a large value such as can take over a second on a fast CPU.

Limiting conversion size offers a practical way to avoid CVE-2020-10735.

The limit is applied to the number of digit characters in the input or output string when a non-linear conversion algorithm would be involved. Underscores and the sign are not counted towards the limit.

Verification:

Affected APIs

The limitations do not apply to functions with a linear algorithm:

Configuring the limit

Before Python starts up you can use an environment variable or an interpreter command line flag to configure the limit:

Caution

Setting a low limit can lead to problems. While rare, code exists that contains integer constants in decimal in their source that exceed the minimum threshold. A consequence of setting the limit is that Python source code containing decimal integer literals longer than the limit will encounter an error during parsing, usually at startup time or import time or even at installation time - anytime an up to date does not already exist for the code. A workaround for source that contains such large constants is to convert them to hexadecimal form as it has no limit.

Test your application thoroughly if you use a low limit. Ensure your tests run with the limit set early via the environment or flag so that it applies during startup and even during any installation step that may invoke Python to precompile sources to files.

Recommended configuration

Example:

If you need to disable it entirely, set it to .

Footnotes

# data[].attributes.attachment_link.description
The following sections describe the standard types that are built into the interpreter. The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Some colle...

# data[].attributes.attachment_link.readable_text
While The Python Language Reference describes the exact syntax and semantics of the Python language, this library reference manual describes the standard library that is distributed with Python. It also describes some of the optional components that are commonly included in Python distributions.

Python's standard library is very extensive, offering a wide range of facilities as indicated by the long table of contents listed below. The library contains built-in modules (written in C) that provide access to system functionality such as file I/O that would otherwise be inaccessible to Python programmers, as well as modules written in Python that provide standardized solutions for many problems that occur in everyday programming. Some of these modules are explicitly designed to encourage and enhance the portability of Python programs by abstracting away platform-specifics into platform-neutral APIs.

The Python installers for the Windows platform usually include the entire standard library and often also include many additional components. For Unix-like operating systems Python is normally provided as a collection of packages, so it may be necessary to use the packaging tools provided with the operating system to obtain some or all of the optional components.

In addition to the standard library, there is an active collection of hundreds of thousands of components (from individual programs and modules to packages and entire application development frameworks), available from the Python Package Index.

# data[].attributes.attachment_link.description
While The Python Language Reference describes the exact syntax and semantics of the Python language, this library reference manual describes the standard library that is distributed with Python. It...

# data[].attributes.attachment_link.readable_text
The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.

Return if all elements of the iterable are true (or if the iterable is empty). Equivalent to:

Return if any element of the iterable is true. If the iterable is empty, return . Equivalent to:

As , return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by using , , or escapes. This generates a string similar to that returned by in Python 2.

Convert an integer number to a binary string prefixed with "0b". The result is a valid Python expression. If x is not a Python object, it has to define an method that returns an integer. Some examples:

If the prefix "0b" is desired or not, you can use either of the following ways.

This function drops you into the debugger at the call site. Specifically, it calls , passing and straight through. By default, sys.breakpointhook() calls expecting no arguments. In this case, it is purely a convenience function so you don't have to explicitly import or type as much code to enter the debugger. However, can be set to some other function and will automatically call that, allowing you to drop into the debugger of choice. If is not accessible, this function will raise .

By default, the behavior of can be changed with the environment variable. See for usage details.

Raises an auditing event builtins.breakpoint with argument breakpointhook .

Return a new array of bytes. The class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types , as well as most methods that the type has, see Bytes and Bytearray Operations .

The optional source parameter can be used to initialize the array in a few different ways:

If it is a string, you must also give the encoding (and optionally, errors) parameters; then converts the string to bytes using .

If it is an integer, the array will have that size and will be initialized with null bytes.

If it is an object conforming to the buffer interface , a read-only buffer of the object will be used to initialize the bytes array.

If it is an iterable, it must be an iterable of integers in the range , which are used as the initial contents of the array.

Without an argument, an array of size 0 is created.

See also Binary Sequence Types - bytes, bytearray, memoryview and Bytearray Objects .

Return if the object argument appears callable, if not. If this returns , it is still possible that a call fails, but if it is , calling object will never succeed. Note that classes are callable (calling a class returns a new instance); instances are callable if their class has a method.

Added in version 3.2: This function was first removed in Python 3.0 and then brought back in Python 3.2.

Return the string representing a character whose Unicode code point is the integer i. For example, returns the string , while returns the string . This is the inverse of .

The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). will be raised if i is outside that range.

Transform a method into a class method.

A class method receives the class as an implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

The @classmethod form is a function - see Function definitions for details.

A class method can be called either on the class (such as ) or on an instance (such as ). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods. If you want those, see in this section. For more information on class methods, see The standard type hierarchy .

Compile the source into a code or AST object. Code objects can be executed by or . source can either be a normal string, a byte string, or an AST object. Refer to the module documentation for information on how to work with AST objects.

The filename argument should give the file from which the code was read; pass some recognizable value if it wasn't read from a file ( is commonly used).

The mode argument specifies what kind of code must be compiled; it can be if source consists of a sequence of statements, if it consists of a single expression, or if it consists of a single interactive statement (in the latter case, expression statements that evaluate to something other than will be printed).

The optional arguments flags and dont_inherit control which compiler options should be activated and which future features should be allowed. If neither is present (or both are zero) the code is compiled with the same flags that affect the code that is calling . If the flags argument is given and dont_inherit is not (or is zero) then the compiler options and the future statements specified by the flags argument are used in addition to those that would be used anyway. If dont_inherit is a non-zero integer then the flags argument is it - the flags (future features and compiler options) in the surrounding code are ignored.

Compiler options and future statements are specified by bits which can be bitwise ORed together to specify multiple options. The bitfield required to specify a given future feature can be found as the attribute on the instance in the module. Compiler flags can be found in module, with prefix.

The argument optimize specifies the optimization level of the compiler; the default value of selects the optimization level of the interpreter as given by options. Explicit levels are (no optimization; is true), (asserts are removed, is false) or (docstrings are removed too).

Raises an auditing event with arguments and . This event may also be raised by implicit compilation.

Note

When compiling a string with multi-line code in or mode, input must be terminated by at least one newline character. This is to facilitate detection of incomplete and complete statements in the module.

Warning

It is possible to crash the Python interpreter with a sufficiently large/complex string when compiling to an AST object due to stack depth limitations in Python's AST compiler.

Changed in version 3.2: Allowed use of Windows and Mac newlines. Also, input in mode does not have to end in a newline anymore. Added the optimize parameter.

Changed in version 3.5: Previously, was raised when null bytes were encountered in source.

Return a complex number with the value real + imag*1j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If imag is omitted, it defaults to zero and the constructor serves as a numeric conversion like and . If both arguments are omitted, returns .

The complex type is described in Numeric Types - int, float, complex .

Changed in version 3.6: Grouping digits with underscores as in code literals is allowed.

This is a relative of . The arguments are an object and a string. The string must be the name of one of the object's attributes. The function deletes the named attribute, provided the object allows it. For example, is equivalent to . name need not be a Python identifier (see ).

Take two (non-complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as . For floating point numbers the result is , where q is usually but may be 1 less than that. In any case is very close to a, if is non-zero it has the same sign as b, and .

Return an enumerate object. iterable must be a sequence, an , or some other object which supports iteration. The method of the iterator returned by returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.

Equivalent to:

The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. If the globals dictionary is present and does not contain a value for the key , a reference to the dictionary of the built-in module is inserted under that key before expression is parsed. That way you can control what builtins are available to the executed code by inserting your own dictionary into globals before passing it to . If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed with the globals and locals in the environment where is called. Note, eval() does not have access to the nested scopes (non-locals) in the enclosing environment.

Example:

This function can also be used to execute arbitrary code objects (such as those created by ). In this case, pass a code object instead of a string. If the code object has been compiled with as the mode argument, 's return value will be .

If the given source is a string, then leading and trailing spaces and tabs are stripped.

Raises an auditing event with the code object as the argument. Code compilation events may also be raised.

This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). If it is a code object, it is simply executed. In all cases, the code that's executed is expected to be valid as file input (see the section in the Reference Manual). Be aware that the , , and statements may not be used outside of function definitions even within the context of code passed to the function. The return value is .

In all cases, if the optional parts are omitted, the code is executed in the current scope. If only globals is provided, it must be a dictionary (and not a subclass of dictionary), which will be used for both the global and the local variables. If globals and locals are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at the module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.

If the globals dictionary does not contain a value for the key , a reference to the dictionary of the built-in module is inserted under that key. That way you can control what builtins are available to the executed code by inserting your own dictionary into globals before passing it to .

The closure argument specifies a closure-a tuple of cellvars. It's only valid when the object is a code object containing free variables. The length of the tuple must exactly match the number of free variables referenced by the code object.

Raises an auditing event with the code object as the argument. Code compilation events may also be raised.

Note

The built-in functions and return the current global and local dictionary, respectively, which may be useful to pass around for use as the second and third argument to .

Note

The default locals act as described for function below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function returns.

Construct an iterator from those elements of iterable for which function is true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is , the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to the generator expression if function is not and if function is .

See itertools.filterfalse() for the complementary function that returns elements of iterable for which function is false.

Return a floating point number constructed from a number or string x.

If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be or ; a sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or positive or negative infinity. More precisely, the input must conform to the floatvalue production rule in the following grammar, after leading and trailing whitespace characters are removed:

Case is not significant, so, for example, "inf", "Inf", "INFINITY", and "iNfINity" are all acceptable spellings for positive infinity.

If no argument is given, is returned.

Examples:

The float type is described in Numeric Types - int, float, complex .

Changed in version 3.6: Grouping digits with underscores as in code literals is allowed.

Convert a value to a "formatted" representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument; however, there is a standard formatting syntax that is used by most built-in types: Format Specification Mini-Language .

The default format_spec is an empty string which usually gives the same effect as calling .

A call to format(value, format_spec) is translated to type(value).__format__(value, format_spec) which bypasses the instance dictionary when searching for the value's method. A exception is raised if the method search reaches and the format_spec is non-empty, or if either the format_spec or the return value are not strings.

Changed in version 3.4: object().__format__(format_spec) raises if format_spec is not an empty string.

Return a new object, optionally with elements taken from iterable. is a built-in class. See and Set Types - set, frozenset for documentation about this class.

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object's attributes, the result is the value of that attribute. For example, is equivalent to . If the named attribute does not exist, default is returned if provided, otherwise is raised. name need not be a Python identifier (see ).

Note

Since private name mangling happens at compilation time, one must manually mangle a private attribute's (attributes with two leading underscores) name in order to retrieve it with .

Return the dictionary implementing the current module namespace. For code within functions, this is set when the function is defined and remains the same regardless of where the function is called.

The arguments are an object and a string. The result is if the string is the name of one of the object's attributes, if not. (This is implemented by calling and seeing whether it raises an or not.)

Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).

Note

For objects with custom methods, note that truncates the return value based on the bit width of the host machine.

Convert an integer number to a lowercase hexadecimal string prefixed with "0x". If x is not a Python object, it has to define an method that returns an integer. Some examples:

If you want to convert an integer number to an uppercase or lower hexadecimal string with prefix or not, you can use either of the following ways:

Note

To obtain a hexadecimal string representation for a float, use the method.

If x is not a number or if base is given, then x must be a string, , or instance representing an integer in radix base. Optionally, the string can be preceded by or (with no space in between), have leading zeros, be surrounded by whitespace, and have single underscores interspersed between digits.

A base-n integer string contains digits, each representing a value from 0 to n-1. The values 0-9 can be represented by any Unicode decimal digit. The values 10-35 can be represented by to (or to ). The default base is 10. The allowed bases are 0 and 2-36. Base-2, -8, and -16 strings can be optionally prefixed with /, /, or /, as with integer literals in code. For base 0, the string is interpreted in a similar way to an integer literal in code , in that the actual base is 2, 8, 10, or 16 as determined by the prefix. Base 0 also disallows leading zeros: is not legal, while and are.

The integer type is described in Numeric Types - int, float, complex .

Changed in version 3.4: If base is not an instance of and the base object has a method, that method is called to obtain an integer for the base. Previous versions used instead of .

Changed in version 3.6: Grouping digits with underscores as in code literals is allowed.

Changed in version 3.11: The delegation to is deprecated.

Changed in version 3.11: string inputs and string representations can be limited to help avoid denial of service attacks. A is raised when the limit is exceeded while converting a string x to an or when converting an into a string would exceed the limit. See the integer string conversion length limitation documentation.

Return if the object argument is an instance of the classinfo argument, or of a (direct, indirect, or ) subclass thereof. If object is not an object of the given type, the function always returns . If classinfo is a tuple of type objects (or recursively, other such tuples) or a of multiple types, return if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a exception is raised. may not be raised for an invalid type if an earlier check succeeds.

Return if class is a subclass (direct, indirect, or ) of classinfo. A class is considered a subclass of itself. classinfo may be a tuple of class objects (or recursively, other such tuples) or a , in which case return if class is a subclass of any entry in classinfo. In any other case, a exception is raised.

Return an object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, object must be a collection object which supports the protocol (the method), or it must support the sequence protocol (the method with integer arguments starting at ). If it does not support either of those protocols, is raised. If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its method; if the value returned is equal to sentinel, will be raised, otherwise the value will be returned.

See also Iterator Types .

Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

Note

The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

Return an iterator that applies function to every item of iterable, yielding the results. If additional iterables arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see .

Return a "memory view" object created from the given argument. See Memory Views for more information.

Convert an integer number to an octal string prefixed with "0o". The result is a valid Python expression. If x is not a Python object, it has to define an method that returns an integer. For example:

If you want to convert an integer number to an octal string either with the prefix "0o" or not, you can use either of the following ways.

Open file and return a corresponding file object . If the file cannot be opened, an is raised. See Reading and Writing Files for more examples of how to use this function.

file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed unless closefd is set to .)

mode is an optional string that specifies the mode in which the file is opened. It defaults to which means open for reading in text mode. Other common values are for writing (truncating the file if it already exists), for exclusive creation, and for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform-dependent: is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are:

As mentioned in the , Python distinguishes between binary and text I/O. Files opened in binary mode (including in the mode argument) return contents as objects without any decoding. In text mode (the default, or when is included in the mode argument), the contents of the file are returned as , the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.

Note

Python doesn't depend on the underlying operating system's notion of text files; all the processing is done by Python itself, and is therefore platform-independent.

buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable when writing in text mode), and an integer > 1 to indicate the size in bytes of a fixed-size chunk buffer. Note that specifying a buffer size this way applies for binary buffered I/O, but TextIOWrapper (i.e., files opened with ) would have another buffering. To disable buffering in TextIOWrapper , consider using the write_through flag forio.TextIOWrapper.reconfigure() . When no buffering argument is given, the default buffering policy works as follows:

Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device's "block size" and falling back on . On many systems, the buffer will typically be 4096 or 8192 bytes long.

"Interactive" text files (files for which returns ) use line buffering. Other text files use the policy described above for binary files.

encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever returns), but any text encoding supported by Python can be used. See the module for the list of supported encodings.

errors is an optional string that specifies how encoding and decoding errors are to be handled-this cannot be used in binary mode. A variety of standard error handlers are available (listed under Error Handlers ), though any error handling name that has been registered with is also valid. The standard names include:

to raise a exception if there is an encoding error. The default value of has the same effect.

ignores errors. Note that ignoring encoding errors can lead to data loss.

causes a replacement marker (such as ) to be inserted where there is malformed data.

'surrogateescape' will represent any incorrect bytes as low surrogate code units ranging from U+DC80 to U+DCFF. These surrogate code units will then be turned back into the same bytes when the surrogateescape error handler is used when writing data. This is useful for processing files in an unknown encoding.

'xmlcharrefreplace' is only supported when writing to a file. Characters not supported by the encoding are replaced with the appropriate XML character reference .

'backslashreplace' replaces malformed data by Python's backslashed escape sequences.

'namereplace' (also only supported when writing) replaces unsupported characters with escape sequences.

When reading input from the stream, if newline is , universal newlines mode is enabled. Lines in the input can end in , , or , and these are translated into before being returned to the caller. If it is , universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.

When writing output to the stream, if newline is , any characters written are translated to the system default line separator, . If newline is or , no translation takes place. If newline is any of the other legal values, any characters written are translated to the given string.

If closefd is and a file descriptor rather than a filename was given, the underlying file descriptor will be kept open when the file is closed. If a filename is given closefd must be (the default); otherwise, an error will be raised.

A custom opener can be used by passing a callable as opener. The underlying file descriptor for the file object is then obtained by calling opener with ( file, flags). opener must return an open file descriptor (passing as opener results in functionality similar to passing ).

The newly created file is non-inheritable .

The following example uses the parameter of the function to open a file relative to a given directory:

The type of file object returned by the function depends on the mode. When is used to open a file in a text mode (, , , , etc.), it returns a subclass of (specifically ). When used to open a file in a binary mode with buffering, the returned class is a subclass of . The exact class varies: in read binary mode, it returns an ; in write binary and append binary modes, it returns an , and in read/write mode, it returns an . When buffering is disabled, the raw stream, a subclass of , , is returned.

The and arguments may have been modified or inferred from the original call.

Changed in version 3.5:

If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an exception (see PEP 475 for the rationale).

The 'namereplace' error handler was added.

Changed in version 3.11: The mode has been removed.

Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, returns the integer and (Euro sign) returns . This is the inverse of .

Print objects to the text stream file, separated by sep and followed by end. sep, end, file, and flush, if present, must be given as keyword arguments.

All non-keyword arguments are converted to strings like does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be , which means to use the default values. If no objects are given, will just write end.

The file argument must be an object with a write(string) method; if it is not present or , will be used. Since printed arguments are converted to text strings, cannot be used with binary mode file objects. For these, use instead.

Output buffering is usually determined by file. However, if flush is true, the stream is forcibly flushed.

Return a property attribute.

fget is a function for getting an attribute value. fset is a function for setting an attribute value. fdel is a function for deleting an attribute value. And doc creates a docstring for the attribute.

A typical use is to define a managed attribute :

If c is an instance of C, will invoke the getter, will invoke the setter, and the deleter.

If given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget 's docstring (if it exists). This makes it possible to create read-only properties easily using as a :

The decorator turns the method into a "getter" for a read-only attribute with the same name, and it sets the docstring for voltage to "Get the current voltage."

A property object has , , and methods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function. This is best explained with an example:

This code is exactly equivalent to the first example. Be sure to give the additional functions the same name as the original property ( in this case.)

The returned property object also has the attributes , , and corresponding to the constructor arguments.

Changed in version 3.5: The docstrings of property objects are now writeable.

Rather than being a function, is actually an immutable sequence type, as documented in and Sequence Types - list, tuple, range .

Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to ; otherwise, the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a method. If is not accessible, this function will raise .

This class has a custom representation that can be evaluated:

Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is , it returns the nearest integer to its input.

For the built-in types supporting , values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both and are , and is ). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if ndigits is omitted or . Otherwise, the return value has the same type as number.

Note

The behavior of for floats can be surprising: for example, gives instead of the expected . This is not a bug: it's a result of the fact that most decimal fractions can't be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

This is the counterpart of . The arguments are an object, a string, and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, is equivalent to .

name need not be a Python identifier as defined in Identifiers and keywords unless the object chooses to enforce that, for example in a custom or via . An attribute whose name is not an identifier will not be accessible using the dot notation, but is accessible through etc..

Note

Since private name mangling happens at compilation time, one must manually mangle a private attribute's (attributes with two leading underscores) name in order to set it with .

Return a new sorted list from the items in iterable.

Has two optional arguments which must be specified as keyword arguments.

key specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower ). The default value is (compare the elements directly).

reverse is a boolean value. If set to , then the list elements are sorted as if each comparison were reversed.

Use to convert an old-style cmp function to a key function.

The sort algorithm uses only comparisons between items. While defining an method will suffice for sorting, PEP 8 recommends that all six rich comparisons be implemented. This will help avoid bugs when using the same data with other ordering tools such as that rely on a different underlying method. Implementing all six comparisons also helps avoid confusion for mixed type comparisons which can call reflected the method.

For sorting examples and a brief sorting tutorial, see Sorting Techniques .

Transform a method into a static method.

A static method does not receive an implicit first argument. To declare a static method, use this idiom:

The @staticmethod form is a function - see Function definitions for details.

A static method can be called either on the class (such as ) or on an instance (such as ). Moreover, the static method descriptor is also callable, so it can be used in the class definition (such as ).

Like all decorators, it is also possible to call staticmethod as a regular function and do something with its result. This is needed in some cases where you need a reference to a function from a class body and you want to avoid the automatic transformation to instance method. For these cases, use this idiom:

For more information on static methods, see The standard type hierarchy .

Changed in version 3.10: Static methods now inherit the method attributes (, , , and __annotations__ ), have a new attribute, and are now callable as regular functions.

Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class.

The object_or_type determines the method resolution order to be searched. The search starts from the class right after the type.

The attribute of the object_or_type lists the method resolution search order used by both and . The attribute is dynamic and can change whenever the inheritance hierarchy is updated.

If the second argument is omitted, the super object returned is unbound. If the second argument is an object, must be true. If the second argument is a type, must be true (this is useful for classmethods).

There are two typical use cases for super. In a class hierarchy with single inheritance, super can be used to refer to parent classes without naming them explicitly, thus making the code more maintainable. This use closely parallels the use of super in other programming languages.

The second use case is to support cooperative multiple inheritance in a dynamic execution environment. This use case is unique to Python and is not found in statically compiled languages or languages that only support single inheritance. This makes it possible to implement "diamond diagrams" where multiple base classes implement the same method. Good design dictates that such implementations have the same calling signature in every case (because the order of calls is determined at runtime, because that order adapts to changes in the class hierarchy, and because that order can include sibling classes that are unknown prior to runtime).

For both use cases, a typical superclass call looks like this:

In addition to method lookups, also works for attribute lookups. One possible use case for this is calling descriptors in a parent or sibling class.

Note that is implemented as part of the binding process for explicit dotted attribute lookups such as super().__getitem__(name) . It does so by implementing its own method for searching classes in a predictable order that supports cooperative multiple inheritance. Accordingly, is undefined for implicit lookups using statements or operators such as .

For practical suggestions on how to design cooperative classes using , see guide to using super().

With one argument, return the type of an object. The return value is a type object and generally the same object as returned by .

With three arguments, return a new type object. This is essentially a dynamic form of the statement. The name string is the class name and becomes the attribute. The bases tuple contains the base classes and becomes the attribute; if empty, , the ultimate base of all classes, is added. The dict dictionary contains attribute and method definitions for the class body; it may be copied or wrapped before becoming the attribute. The following two statements create identical objects:

Keyword arguments provided to the three argument form are passed to the appropriate metaclass machinery (usually ) in the same way that keywords in a class definition (besides metaclass) would.

See also Customizing class creation .

Changed in version 3.6: Subclasses of which don't override may no longer use the one-argument form to get the type of an object.

Iterate over several iterables in parallel, producing tuples with an item from each one.

Example:

More formally: returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument iterables.

Another way to think of is that it turns rows into columns, and columns into rows. This is similar to transposing a matrix.

is lazy: The elements won't be processed until the iterable is iterated on, e.g. by a loop or by wrapping in a .

By default, stops when the shortest iterable is exhausted. It will ignore the remaining items in the longer iterables, cutting off the result to the length of the shortest iterable:

is often used in cases where the iterables are assumed to be of equal length. In such cases, it's recommended to use the strict=True option. Its output is the same as regular :

Unlike the default behavior, it raises a if one iterable is exhausted before the others:

Without the strict=True argument, any bug that results in iterables of different lengths will be silenced, possibly manifesting as a hard-to-find bug in another part of the program.

Shorter iterables can be padded with a constant value to make all the iterables have the same length. This is done by .

Tips and tricks:

The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using . This repeats the same iterator times so that each output tuple has the result of calls to the iterator. This has the effect of dividing the input into n-length chunks.

Changed in version 3.10: Added the argument.

This function is invoked by the statement. It can be replaced (by importing the module and assigning to builtins.__import__ ) in order to change semantics of the statement, but doing so is strongly discouraged as it is usually simpler to use import hooks (seePEP 302) to attain the same goals and does not cause issues with code which assumes the default import implementation is in use. Direct use of is also discouraged in favor ofimportlib.import_module() .

The function imports the module name, potentially using the given globals and locals to determine how to interpret the name in a package context. The fromlist gives the names of objects or submodules that should be imported from the module given by name. The standard implementation does not use its locals argument at all and uses its globals only to determine the package context of the statement.

level specifies whether to use absolute or relative imports. (the default) means only perform absolute imports. Positive values for level indicate the number of parent directories to search relative to the directory of the module calling (seePEP 328 for the details).

When the name variable is of the form package.module , normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned.

For example, the statement results in bytecode resembling the following code:

The statement results in this call:

On the other hand, the statement results in

Here, the module is returned from . From this object, the names to import are retrieved and assigned to their respective names.

Footnotes

# data[].attributes.attachment_link.description
The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.,,,, Built-in Functions,,, A, abs(), aiter(), all(), a...

# data[].attributes.body
Guía Completa de Python

# data[].attributes.attachment_link.readable_text
Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python's elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.

The Python interpreter and the extensive standard library are freely available in source or binary form for all major platforms from the Python web site, https://www.python.org/, and may be freely distributed. The same site also contains distributions of and pointers to many free third party Python modules, programs and tools, and additional documentation.

The Python interpreter is easily extended with new functions and data types implemented in C or C++ (or other languages callable from C). Python is also suitable as an extension language for customizable applications.

This tutorial introduces the reader informally to the basic concepts and features of the Python language and system. It helps to have a Python interpreter handy for hands-on experience, but all examples are self-contained, so the tutorial can be read off-line as well.

For a description of standard objects and modules, see The Python Standard Library . The Python Language Reference gives a more formal definition of the language. To write extensions in C or C++, read Extending and Embedding the Python Interpreter and Python/C API Reference Manual . There are also several books covering Python in depth.

This tutorial does not attempt to be comprehensive and cover every single feature, or even every commonly used feature. Instead, it introduces many of Python's most noteworthy features, and will give you a good idea of the language's flavor and style. After reading it, you will be able to read and write Python modules and programs, and you will be ready to learn more about the various Python library modules described in The Python Standard Library .

The is also worth going through.

# data[].attributes.attachment_link.description
Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python's elegant syntax an...

# data[].attributes.attachment_link.title
Diferencias entre Lenguajes Compilados y Lenguajes Interpretados

# data[].attributes.attachment_link.readable_text
Un programa informático (programa) es una secuencia de acciones (instrucciones) que manipulan un conjunto de objetos (datos).

Existen dos partes o bloques que componen un programa:

1. Bloque de declaraciones: en este se detallan todos los datos que utiliza el programa (constantes, variables, archivos, etc).

2. Bloque de instrucciones: conjunto de acciones u operaciones que se han de llevar a cabo para conseguir los resultados esperados.

El bloque de instrucciones está compuesto a su vez por tres partes, aunque en ocasiones no están perfectamente delimitadas, y aparecerán entremezcladas en la secuencia del programa, podemos localizarlas según su función. Estas son:

1. Entrada de datos: instrucciones que almacenan en la memoria interna datos procedentes de un dispositivo externo (teclado, ratón,...)

2. Proceso o algoritmo: instrucciones que modifican los objetos de entrada y, en ocasiones, creando otros nuevos.

3. Salida de resultados: conjunto de instrucciones que toman los datos finales de la memoria interna y los envían a los dispositivos externos (pantallas o dispositivos de almacenamiento).

En la siguiente tabla detallamos la estructura básica de un programa informático:

Cabecera

A modo de comentarios se suele especificar:

Nombre del programa

Datos de entrada

Datos de salida

Funciones

Definición de funciones propias creadas por el programador para usarlas en varias ocasiones

Asignaciones
Valores iniciales de los datos declarados previamente

Entradas
Instrucciones para almacenar en memoria los valores de algunos datos iniciales

Control

Instrucciones de control de flujo del programa. Pueden ser:

Secuenciales

De selección

Iterativas

Salidas

Instrucciones para devolver los resultados obtenidos

# data[].attributes.attachment_link.description
Un programa informático (programa) es una secuencia de acciones (instrucciones) que manipulan un conjunto de objetos (datos). Existen dos partes o bloques que componen un programa: Bloque de declaraciones: en este se detallan todos los datos que utiliza el programa (constantes, variables, archivos, etc).

# data[].attributes.body
Guía de estilo para código Python

# data[].attributes.attachment_link.readable_text
This document gives coding conventions for the Python code comprising the standard library in the main Python distribution. Please see the companion informational PEP describing style guidelines for the C code in the C implementation of Python.

This document and PEP 257 (Docstring Conventions) were adapted from Guido's original Python Style Guide essay, with some additions from Barry's style guide[2].

This style guide evolves over time as additional conventions are identified and past conventions are rendered obsolete by changes in the language itself.

Many projects have their own coding style guidelines. In the event of any conflicts, such project-specific guides take precedence for that project.

One of Guido's key insights is that code is read much more often than it is written. The guidelines provided here are intended to improve the readability of code and make it consistent across the wide spectrum of Python code. As PEP 20 says, "Readability counts".

A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is the most important.

However, know when to be inconsistent - sometimes style guide recommendations just aren't applicable. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don't hesitate to ask!

In particular: do not break backwards compatibility just to comply with this PEP!

Some other good reasons to ignore a particular guideline:

1. When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this PEP.

2. To be consistent with surrounding code that also breaks it (maybe for historic reasons) - although this is also an opportunity to clean up someone else's mess (in true XP style).

3. Because the code in question predates the introduction of the guideline and there is no other reason to be modifying that code.

4. When the code needs to remain compatible with older versions of Python that don't support the feature recommended by the style guide.

Use 4 spaces per indentation level.

Continuation lines should align wrapped elements either vertically using Python's implicit line joining inside parentheses, brackets and braces, or using a hanging indent [1]. When using a hanging indent the following should be considered; there should be no arguments on the first line and further indentation should be used to clearly distinguish itself as a continuation line:

The 4-space rule is optional for continuation lines.

Optional:

When the conditional part of an -statement is long enough to require that it be written across multiple lines, it's worth noting that the combination of a two character keyword (i.e. ), plus a single space, plus an opening parenthesis creates a natural 4-space indent for the subsequent lines of the multiline conditional. This can produce a visual conflict with the indented suite of code nested inside the -statement, which would also naturally be indented to 4 spaces. This PEP takes no explicit position on how (or whether) to further visually distinguish such conditional lines from the nested suite inside the -statement. Acceptable options in this situation include, but are not limited to:

(Also see the discussion of whether to break before or after binary operators below.)

The closing brace/bracket/parenthesis on multiline constructs may either line up under the first non-whitespace character of the last line of list, as in:

or it may be lined up under the first character of the line that starts the multiline construct, as in:

Spaces are the preferred indentation method.

Tabs should be used solely to remain consistent with code that is already indented with tabs.

Python disallows mixing tabs and spaces for indentation.

Limit all lines to a maximum of 79 characters.

For flowing long blocks of text with fewer structural restrictions (docstrings or comments), the line length should be limited to 72 characters.

Limiting the required editor window width makes it possible to have several files open side by side, and works well when using code review tools that present the two versions in adjacent columns.

The default wrapping in most tools disrupts the visual structure of the code, making it more difficult to understand. The limits are chosen to avoid wrapping in editors with the window width set to 80, even if the tool places a marker glyph in the final column when wrapping lines. Some web based tools may not offer dynamic line wrapping at all.

Some teams strongly prefer a longer line length. For code maintained exclusively or primarily by a team that can reach agreement on this issue, it is okay to increase the line length limit up to 99 characters, provided that comments and docstrings are still wrapped at 72 characters.

The Python standard library is conservative and requires limiting lines to 79 characters (and docstrings/comments to 72).

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

Backslashes may still be appropriate at times. For example, long, multiple -statements could not use implicit continuation before Python 3.10, so backslashes were acceptable for that case:

(See the previous discussion on multiline if-statements for further thoughts on the indentation of such multiline -statements.)

Another such case is with statements.

Make sure to indent the continued line appropriately.

For decades the recommended style was to break after binary operators. But this can hurt readability in two ways: the operators tend to get scattered across different columns on the screen, and each operator is moved away from its operand and onto the previous line. Here, the eye has to do extra work to tell which items are added and which are subtracted:

To solve this readability problem, mathematicians and their publishers follow the opposite convention. Donald Knuth explains the traditional rule in his Computers and Typesetting series: "Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations"[3].

Following the tradition from mathematics usually results in more readable code:

In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth's style is suggested.

Surround top-level function and class definitions with two blank lines.

Method definitions inside a class are surrounded by a single blank line.

Extra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).

Use blank lines in functions, sparingly, to indicate logical sections.

Python accepts the control-L (i.e. ^L) form feed character as whitespace; many tools treat these characters as page separators, so you may use them to separate pages of related sections of your file. Note, some editors and web-based code viewers may not recognize control-L as a form feed and will show another glyph in its place.

Code in the core Python distribution should always use UTF-8, and should not have an encoding declaration.

In the standard library, non-UTF-8 encodings should be used only for test purposes. Use non-ASCII characters sparingly, preferably only to denote places and human names. If using non-ASCII characters as data, avoid noisy Unicode characters like z̯̯͡a̧͎̺l̡͓̫g̹̲o̡̼̘ and byte order marks.

All identifiers in the Python standard library MUST use ASCII-only identifiers, and SHOULD use English words wherever feasible (in many cases, abbreviations and technical terms are used which aren't English).

Open source projects with a global audience are encouraged to adopt a similar policy.

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.
Imports should be grouped in the following order:

1. Standard library imports.

2. Related third party imports.

3. Local application/library specific imports.

You should put a blank line between each group of imports.

Absolute imports are recommended, as they are usually more readable and tend to be better behaved (or at least give better error messages) if the import system is incorrectly configured (such as when a directory inside a package ends up on ):
However, explicit relative imports are an acceptable alternative to absolute imports, especially when dealing with complex package layouts where using absolute imports would be unnecessarily verbose:

Standard library code should avoid complex package layouts and always use absolute imports.

When importing a class from a class-containing module, it's usually okay to spell this:
If this spelling causes local name clashes, then spell them explicitly:

and use "myclass.MyClass" and "foo.bar.yourclass.YourClass".

Wildcard imports () should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools. There is one defensible use case for a wildcard import, which is to republish an internal interface as part of a public API (for example, overwriting a pure Python implementation of an interface with the definitions from an optional accelerator module and exactly which definitions will be overwritten isn't known in advance).
When republishing names this way, the guidelines below regarding public and internal interfaces still apply.

Module level "dunders" (i.e. names with two leading and two trailing underscores) such as , , , etc. should be placed after the module docstring but before any import statements except imports. Python mandates that future-imports must appear in the module before any other code except docstrings:

In Python, single-quoted strings and double-quoted strings are the same. This PEP does not make a recommendation for this. Pick a rule and stick to it. When a string contains single or double quote characters, however, use the other one to avoid backslashes in the string. It improves readability.

For triple-quoted strings, always use double quote characters to be consistent with the docstring convention in PEP 257.

Avoid extraneous whitespace in the following situations:

Between a trailing comma and a following close parenthesis:

Immediately before the open parenthesis that starts the argument list of a function call:

Trailing commas are usually optional, except they are mandatory when making a tuple of one element. For clarity, it is recommended to surround the latter in (technically redundant) parentheses:

When trailing commas are redundant, they are often helpful when a version control system is used, when a list of values, arguments or imported items is expected to be extended over time. The pattern is to put each value (etc.) on a line by itself, always adding a trailing comma, and add the close parenthesis/bracket/brace on the next line. However it does not make sense to have a trailing comma on the same line as the closing delimiter (except in the above case of singleton tuples):

The naming conventions of Python's library are a bit of a mess, so we'll never get this completely consistent - nevertheless, here are the currently recommended naming standards. New modules and packages (including third party frameworks) should be written to these standards, but where an existing library has a different style, internal consistency is preferred.

Names that are visible to the user as public parts of the API should follow conventions that reflect usage rather than implementation.

There are a lot of different naming styles. It helps to be able to recognize what naming style is being used, independently from what they are used for.

The following naming styles are commonly distinguished:

There's also the style of using a short unique prefix to group related names together. This is not used much in Python, but it is mentioned for completeness. For example, the function returns a tuple whose items traditionally have names like , , and so on. (This is done to emphasize the correspondence with the fields of the POSIX system call struct, which helps programmers familiar with that.)

The X11 library uses a leading X for all its public functions. In Python, this style is generally deemed unnecessary because attribute and method names are prefixed with an object, and function names are prefixed with a module name.

In addition, the following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention):

_single_leading_underscore : weak "internal use" indicator. E.g. does not import objects whose names start with an underscore.

single_trailing_underscore_ : used by convention to avoid conflicts with Python keyword, e.g.

__double_leading_underscore : when naming a class attribute, invokes name mangling (inside class FooBar, becomes ; see below).

__double_leading_and_trailing_underscore__ : "magic" objects or attributes that live in user-controlled namespaces. E.g. , or . Never invent such names; only use them as documented.

Never use the characters 'l' (lowercase letter el), 'O' (uppercase letter oh), or 'I' (uppercase letter eye) as single character variable names.

In some fonts, these characters are indistinguishable from the numerals one and zero. When tempted to use 'l', use 'L' instead.

Identifiers used in the standard library must be ASCII compatible as described in the policy section of PEP 3131.

Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.

When an extension module written in C or C++ has an accompanying Python module that provides a higher level (e.g. more object oriented) interface, the C/C++ module has a leading underscore (e.g. ).

Class names should normally use the CapWords convention.

The naming convention for functions may be used instead in cases where the interface is documented and used primarily as a callable.

Note that there is a separate convention for builtin names: most builtin names are single words (or two words run together), with the CapWords convention used only for exception names and builtin constants.

Names of type variables introduced in PEP 484 should normally use CapWords preferring short names: , , . It is recommended to add suffixes or to the variables used to declare covariant or contravariant behavior correspondingly:

Because exceptions should be classes, the class naming convention applies here. However, you should use the suffix "Error" on your exception names (if the exception actually is an error).

(Let's hope that these variables are meant for use inside one module only.) The conventions are about the same as those for functions.

Modules that are designed for use via should use the mechanism to prevent exporting globals, or use the older convention of prefixing such globals with an underscore (which you might want to do to indicate these globals are "module non-public").

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

Variable names follow the same convention as function names.

mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.

Always use for the first argument to instance methods.

Always use for the first argument to class methods.

If a function argument's name clashes with a reserved keyword, it is generally better to append a single trailing underscore rather than use an abbreviation or spelling corruption. Thus is better than . (Perhaps better is to avoid such clashes by using a synonym.)

Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.

Use one leading underscore only for non-public methods and instance variables.

To avoid name clashes with subclasses, use two leading underscores to invoke Python's name mangling rules.

Python mangles these names with the class name: if class Foo has an attribute named , it cannot be accessed by . (An insistent user could still gain access by calling .) Generally, double leading underscores should be used only to avoid name conflicts with attributes in classes designed to be subclassed.

Note: there is some controversy about the use of __names (see below).

Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and .

Always decide whether a class's methods and instance variables (collectively: "attributes") should be public or non-public. If in doubt, choose non-public; it's easier to make it public later than to make a public attribute non-public.

Public attributes are those that you expect unrelated clients of your class to use, with your commitment to avoid backwards incompatible changes. Non-public attributes are those that are not intended to be used by third parties; you make no guarantees that non-public attributes won't change or even be removed.

We don't use the term "private" here, since no attribute is really private in Python (without a generally unnecessary amount of work).

Another category of attributes are those that are part of the "subclass API" (often called "protected" in other languages). Some classes are designed to be inherited from, either to extend or modify aspects of the class's behavior. When designing such a class, take care to make explicit decisions about which attributes are public, which are part of the subclass API, and which are truly only to be used by your base class.

With this in mind, here are the Pythonic guidelines:

Public attributes should have no leading underscores.

If your public attribute name collides with a reserved keyword, append a single trailing underscore to your attribute name. This is preferable to an abbreviation or corrupted spelling. (However, notwithstanding this rule, 'cls' is the preferred spelling for any variable or argument which is known to be a class, especially the first argument to a class method.)
Note 1: See the argument name recommendation above for class methods.

For simple public data attributes, it is best to expose just the attribute name, without complicated accessor/mutator methods. Keep in mind that Python provides an easy path to future enhancement, should you find that a simple data attribute needs to grow functional behavior. In that case, use properties to hide functional implementation behind simple data attribute access syntax.
Note 1: Try to keep the functional behavior side-effect free, although side-effects such as caching are generally fine.

Note 2: Avoid using properties for computationally expensive operations; the attribute notation makes the caller believe that access is (relatively) cheap.

If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores. This invokes Python's name mangling algorithm, where the name of the class is mangled into the attribute name. This helps avoid attribute name collisions should subclasses inadvertently contain attributes with the same name.
Note 1: Note that only the simple class name is used in the mangled name, so if a subclass chooses both the same class name and attribute name, you can still get name collisions.

Note 2: Name mangling can make certain uses, such as debugging and , less convenient. However the name mangling algorithm is well documented and easy to perform manually.

Note 3: Not everyone likes name mangling. Try to balance the need to avoid accidental name clashes with potential use by advanced callers.

Any backwards compatibility guarantees apply only to public interfaces. Accordingly, it is important that users be able to clearly distinguish between public and internal interfaces.

Documented interfaces are considered public, unless the documentation explicitly declares them to be provisional or internal interfaces exempt from the usual backwards compatibility guarantees. All undocumented interfaces should be assumed to be internal.

To better support introspection, modules should explicitly declare the names in their public API using the attribute. Setting to an empty list indicates that the module has no public API.

Even with set appropriately, internal interfaces (packages, modules, classes, functions, attributes or other names) should still be prefixed with a single leading underscore.

An interface is also considered internal if any containing namespace (package, module or class) is considered internal.

Imported names should always be considered an implementation detail. Other modules must not rely on indirect access to such imported names unless they are an explicitly documented part of the containing module's API, such as or a package's module that exposes functionality from submodules.

Code should be written in a way that does not disadvantage other implementations of Python (PyPy, Jython, IronPython, Cython, Psyco, and such).
For example, do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form or . This optimization is fragile even in CPython (it only works for some types) and isn't present at all in implementations that don't use refcounting. In performance sensitive parts of the library, the form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.

Comparisons to singletons like None should always be done with or , never the equality operators.
Also, beware of writing when you really mean - e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!

When implementing ordering operations with rich comparisons, it is best to implement all six operations (, , , , , ) rather than relying on other code to only exercise a particular comparison.
To minimize the effort involved, the functools.total_ordering() decorator provides a tool to generate missing comparison methods.

PEP 207 indicates that reflexivity rules are assumed by Python. Thus, the interpreter may swap with , with , and may swap the arguments of and . The and operations are guaranteed to use the operator and the function uses the operator. However, it is best to implement all six operations so that confusion doesn't arise in other contexts.

Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier:
The first form means that the name of the resulting function object is specifically 'f' instead of the generic '<lambda>'. This is more useful for tracebacks and string representations in general. The use of the assignment statement eliminates the sole benefit a lambda expression can offer over an explicit def statement (i.e. that it can be embedded inside a larger expression)

Derive exceptions from rather than BaseException . Direct inheritance fromBaseException is reserved for exceptions where catching them is almost always the wrong thing to do.
Design exception hierarchies based on the distinctions that code catching the exceptions is likely to need, rather than the locations where the exceptions are raised. Aim to answer the question "What went wrong?" programmatically, rather than only stating that "A problem occurred" (see PEP 3151 for an example of this lesson being learned for the builtin exception hierarchy)

Class naming conventions apply here, although you should add the suffix "Error" to your exception classes if the exception is an error. Non-error exceptions that are used for non-local flow control or other forms of signaling need no special suffix.

Use exception chaining appropriately. should be used to indicate explicit replacement without losing the original traceback.
When deliberately replacing an inner exception (using ), ensure that relevant details are transferred to the new exception (such as preserving the attribute name when converting KeyError to AttributeError, or embedding the text of the original exception in the new exception message).

When catching exceptions, mention specific exceptions whenever possible instead of using a bare clause:
A bare clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use (bare except is equivalent to ).

A good rule of thumb is to limit use of bare 'except' clauses to two cases:

1. If the exception handler will be printing out or logging the traceback; at least the user will be aware that an error has occurred.

2. If the code needs to do some cleanup work, but then lets the exception propagate upwards with . try...finally can be a better way to handle this case.

When catching operating system errors, prefer the explicit exception hierarchy introduced in Python 3.3 over introspection of values.

Additionally, for all try/except clauses, limit the clause to the absolute minimum amount of code necessary. Again, this avoids masking bugs:

When a resource is local to a particular section of code, use a statement to ensure it is cleaned up promptly and reliably after use. A try/finally statement is also acceptable.

Context managers should be invoked through separate functions or methods whenever they do something other than acquire and release resources:
The latter example doesn't provide any information to indicate that the and methods are doing something other than closing the connection after a transaction. Being explicit is important in this case.

Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as , and an explicit return statement should be present at the end of the function (if reachable):

Object type comparisons should always use isinstance() instead of comparing types directly:

For sequences, (strings, lists, tuples), use the fact that empty sequences are false:

Don't write string literals that rely on significant trailing whitespace. Such trailing whitespace is visually indistinguishable and some editors (or more recently, reindent.py) will trim them.

Use of the flow control statements // within the finally suite of a try...finally , where the flow control statement would jump outside the finally suite, is discouraged. This is because such statements will implicitly cancel any active exception that is propagating through the finally suite:

With the acceptance of PEP 484, the style rules for function annotations have changed.

PEP 526 introduced variable annotations. The style recommendations for them are similar to those on function annotations described above:

Annotations for module level variables, class and instance variables, and local variables should have a single space after the colon.

There should be no space before the colon.

Although the PEP 526 is accepted for Python 3.6, the variable annotation syntax is the preferred syntax for stub files on all versions of Python (seePEP 484 for details).

Footnotes

Last modified: 2023-10-11 12:05:51 GMT

# data[].attributes.body
Manual Visual Studio Code

# data[].attributes.attachment_link.readable_text
Visual Studio Code is a lightweight but powerful source code editor which runs on your desktop and is available for Windows, macOS and Linux. It comes with built-in support for JavaScript, TypeScript and Node.js and has a rich ecosystem of extensions for other languages and runtimes (such as C++, C#, Java, Python, PHP, Go, .NET). Begin your journey with VS Code with these introductory videos.

Visual Studio Code in Action

Top Extensions

Enable additional languages, themes, debuggers, commands, and more. VS Code's growing community shares their secret sauce to improve your workflow.

See more in the Marketplace

First Steps

To get the most out of Visual Studio Code, start by reviewing a few introductory topics:

Intro Videos - Begin your journey with VS Code through these introductory videos.

Setup - Install VS Code for your platform and configure the tool set for your development needs.

User Interface - Introduction to the basic UI, commands, and features of the VS Code editor.

Settings - Customize VS Code for how you like to work.

Languages - Learn about VS Code's support for your favorite programming languages.

Node.js - This tutorial gets you quickly running and debugging a Node.js web app.

Tips and Tricks - Jump right in with Tips and Tricks to become a VS Code power user.

Azure - VS Code is great for deploying your web applications to the cloud.

Extension API - Learn how to write a VS Code extension.

Why VS Code? - Read about the design philosophy and architecture of VS Code.

Keyboard Shortcuts

Increase your productivity with VS Code's keyboard shortcuts.

Downloads

Download VS Code - Quickly find the appropriate install for your platform (Windows, macOS and Linux)

Privacy

By default, VS Code auto-updates to new versions, and collects usage data and crash report information. You may opt out of these defaults by disabling them as instructed below:

# data[].attributes.attachment_link.description
Find out how to set-up and get the most from Visual Studio Code. Optimized for building and debugging modern web and cloud applications. Visual Studio Code is free and available on your favorite platform - Linux, macOS, and Windows.