An integer representing the set of SSL options enabled on this context. The default value is OP_ALL, but you can specify other options such as OP_NO_SSLv2 by ORing them together.
Note
With versions of OpenSSL older than 0.9.8m, it is only possible to set options, not to clear them. Attempting to clear an option (by resetting the corresponding bits) will raise a ValueError.
Changed in version 3.6: SSLContext.options returns Options flags:


Enable TLS 1.3 post-handshake client authentication. Post-handshake auth is disabled by default and a server can only request a TLS client certificate during the initial handshake. When enabled, a server may request a TLS client certificate at any time after the handshake.
When enabled on client-side sockets, the client signals the server that it supports post-handshake authentication.
When enabled on server-side sockets, SSLContext.verify_mode must be set to CERT_OPTIONAL or CERT_REQUIRED, too. The actual client cert exchange is delayed until SSLSocket.verify_client_post_handshake() is called and some I/O is performed.
Note
Only available with OpenSSL 1.1.1 and TLS 1.3 enabled. Without TLS 1.3 support, the property value is None and can’t be modified
New in version 3.8.


The protocol version chosen when constructing the context. This attribute is read-only.


Get statistics about the SSL sessions created or managed by this context. A dictionary is returned which maps the names of each piece of information to their numeric values. For example, here is the total number of hits and misses in the session cache since the context was created:


Specify which protocols the socket should advertise during the SSL/TLS handshake. It should be a list of ASCII strings, like ['http/1.1',
'spdy/2'], ordered by preference. The selection of a protocol will happen during the handshake, and will play out according to RFC 7301. After a successful handshake, the SSLSocket.selected_alpn_protocol() method will return the agreed-upon protocol.
This method will raise NotImplementedError if HAS_ALPN is False.
OpenSSL 1.1.0 to 1.1.0e will abort the handshake and raise SSLError when both sides support ALPN but cannot agree on a protocol. 1.1.0f+ behaves like 1.0.2, SSLSocket.selected_alpn_protocol() returns None.
New in version 3.5.


Set the available ciphers for sockets created with this context. It should be a string in the OpenSSL cipher list format. If no cipher can be selected (because compile-time options or other configuration forbids use of all the specified ciphers), an SSLError will be raised.
Note
when connected, the SSLSocket.cipher() method of SSL sockets will give the currently selected cipher.
OpenSSL 1.1.1 has TLS 1.3 cipher suites enabled by default. The suites cannot be disabled with set_ciphers().


Load a set of default “certification authority” (CA) certificates from a filesystem path defined when building the OpenSSL library. Unfortunately, there’s no easy way to know whether this method succeeds: no error is returned if no certificates are to be found. When the OpenSSL library is provided as part of the operating system, though, it is likely to be configured properly.


Set the curve name for Elliptic Curve-based Diffie-Hellman (ECDH) key exchange. ECDH is significantly faster than regular DH while arguably as secure. The curve_name parameter should be a string describing a well-known elliptic curve, for example prime256v1 for a widely supported curve.
This setting doesn’t apply to client sockets. You can also use the OP_SINGLE_ECDH_USE option to further improve security.
This method is not available if HAS_ECDH is False.
New in version 3.3.
See also
Vincent Bernat.


Specify which protocols the socket should advertise during the SSL/TLS handshake. It should be a list of strings, like ['http/1.1', 'spdy/2'], ordered by preference. The selection of a protocol will happen during the handshake, and will play out according to the Application Layer Protocol Negotiation. After a successful handshake, the SSLSocket.selected_npn_protocol() method will return the agreed-upon protocol.
This method will raise NotImplementedError if HAS_NPN is False.
New in version 3.3.


This is a legacy API retained for backwards compatibility. When possible, you should use sni_callback instead. The given server_name_callback is similar to sni_callback, except that when the server hostname is an IDN-encoded internationalized domain name, the server_name_callback receives a decoded U-label ("pythön.org").
If there is an decoding error on the server name, the TLS connection will terminate with an ALERT_DESCRIPTION_INTERNAL_ERROR fatal TLS alert message to the client.
New in version 3.4.


Register a callback function that will be called after the TLS Client Hello handshake message has been received by the SSL/TLS server when the TLS client specifies a server name indication. The server name indication mechanism is specified in RFC 6066 section 3 - Server Name Indication.
Only one callback can be set per SSLContext. If sni_callback is set to None then the callback is disabled. Calling this function a subsequent time will disable the previously registered callback.
The callback function will be called with three arguments; the first being the ssl.SSLSocket, the second is a string that represents the server name that the client is intending to communicate (or None if the TLS Client Hello does not contain a server name) and the third argument is the original SSLContext. The server name argument is text. For internationalized domain name, the server name is an IDN A-label ("xn--pythn-mua.org").
A typical use of this callback is to change the ssl.SSLSocket’s SSLSocket.context attribute to a new object of type SSLContext representing a certificate chain that matches the server name.
Due to the early negotiation phase of the TLS connection, only limited methods and attributes are usable like SSLSocket.selected_alpn_protocol() and SSLSocket.context. SSLSocket.getpeercert(), SSLSocket.getpeercert(), SSLSocket.cipher() and SSLSocket.compress() methods require that the TLS connection has progressed beyond the TLS Client Hello and therefore will not contain return meaningful values nor can they be called safely.
The sni_callback function must return None to allow the TLS negotiation to continue. If a TLS failure is required, a constant ALERT_DESCRIPTION_* can be returned. Other return values will result in a TLS fatal error with ALERT_DESCRIPTION_INTERNAL_ERROR.
If an exception is raised from the sni_callback function the TLS connection will terminate with a fatal TLS alert message ALERT_DESCRIPTION_HANDSHAKE_FAILURE.
This method will raise NotImplementedError if the OpenSSL library had OPENSSL_NO_TLSEXT defined when it was built.
New in version 3.7.


The return type of SSLContext.wrap_bio(), defaults to SSLObject. The attribute can be overridden on instance of class in order to return a custom subclass of SSLObject.
New in version 3.7.


The return type of SSLContext.wrap_socket(), defaults to SSLSocket. The attribute can be overridden on instance of class in order to return a custom subclass of SSLSocket.
New in version 3.7.


The flags for certificate verification operations. You can set flags like VERIFY_CRL_CHECK_LEAF by ORing them together. By default OpenSSL does neither require nor verify certificate revocation lists (CRLs). Available only with openssl version 0.9.8+.
New in version 3.4.
Changed in version 3.6: SSLContext.verify_flags returns VerifyFlags flags:


Whether to try to verify other peers’ certificates and how to behave if verification fails. This attribute must be one of CERT_NONE, CERT_OPTIONAL or CERT_REQUIRED.
Changed in version 3.6: SSLContext.verify_mode returns VerifyMode enum:


Wrap the BIO objects incoming and outgoing and return an instance of SSLContext.sslobject_class (default SSLObject). The SSL routines will read input data from the incoming BIO and write data to the outgoing BIO.
The server_side, server_hostname and session parameters have the same meaning as in SSLContext.wrap_socket().
Changed in version 3.6: session argument was added.
Changed in version 3.7: The method returns on instance of SSLContext.sslobject_class instead of hard-coded SSLObject.


Wrap an existing Python socket sock and return an instance of SSLContext.sslsocket_class (default SSLSocket). The returned SSL socket is tied to the context, its settings and certificates. sock must be a SOCK_STREAM socket; other socket types are unsupported.
The parameter server_side is a boolean which identifies whether server-side or client-side behavior is desired from this socket.
For client-side sockets, the context construction is lazy; if the underlying socket isn’t connected yet, the context construction will be performed after connect() is called on the socket. For server-side sockets, if the socket has no remote peer, it is assumed to be a listening socket, and the server-side SSL wrapping is automatically performed on client connections accepted via the accept() method. The method may raise SSLError.
On client connections, the optional parameter server_hostname specifies the hostname of the service which we are connecting to. This allows a single server to host multiple SSL-based services with distinct certificates, quite similarly to HTTP virtual hosts. Specifying server_hostname will raise a ValueError if server_side is true.
The parameter do_handshake_on_connect specifies whether to do the SSL handshake automatically after doing a socket.connect(), or whether the application program will call it explicitly, by invoking the SSLSocket.do_handshake() method. Calling SSLSocket.do_handshake() explicitly gives the program control over the blocking behavior of the socket I/O involved in the handshake.
The parameter suppress_ragged_eofs specifies how the SSLSocket.recv() method should signal unexpected EOF from the other end of the connection. If specified as True (the default), it returns a normal EOF (an empty bytes object) in response to unexpected EOF errors raised from the underlying socket; if False, it will raise the exceptions back to the caller.
session, see session.
Changed in version 3.5: Always allow a server_hostname to be passed, even if OpenSSL does not have SNI.
Changed in version 3.6: session argument was added.
Changed in version 3.7: The method returns on instance of SSLContext.sslsocket_class instead of hard-coded SSLSocket.


A subclass of SSLError raised when the SSL connection has been terminated abruptly. Generally, you shouldn’t try to reuse the underlying transport when this error is encountered.
New in version 3.3.


Raised to signal an error from the underlying SSL implementation (currently provided by the OpenSSL library). This signifies some problem in the higher-level encryption and authentication layer that’s superimposed on the underlying network connection. This error is a subtype of OSError. The error code and message of SSLError instances are provided by the OpenSSL library.
Changed in version 3.3: SSLError used to be a subtype of socket.error.
A string mnemonic designating the OpenSSL submodule in which the error occurred, such as SSL, PEM or X509. The range of possible values depends on the OpenSSL version.
New in version 3.3.
A string mnemonic designating the reason this error occurred, for example CERTIFICATE_VERIFY_FAILED. The range of possible values depends on the OpenSSL version.
New in version 3.3.


A string mnemonic designating the OpenSSL submodule in which the error occurred, such as SSL, PEM or X509. The range of possible values depends on the OpenSSL version.
New in version 3.3.


A string mnemonic designating the reason this error occurred, for example CERTIFICATE_VERIFY_FAILED. The range of possible values depends on the OpenSSL version.
New in version 3.3.


enum.IntEnum collection of SSL_ERROR_* constants.
New in version 3.6.


A reduced-scope variant of SSLSocket representing an SSL protocol instance that does not contain any network IO methods. This class is typically used by framework authors that want to implement asynchronous IO for SSL through memory buffers.
This class implements an interface on top of a low-level SSL object as implemented by OpenSSL. This object captures the state of an SSL connection but does not provide any network IO itself. IO needs to be performed through separate “BIO” objects which are OpenSSL’s IO abstraction layer.
This class has no public constructor. An SSLObject instance must be created using the wrap_bio() method. This method will create the SSLObject instance and bind it to a pair of BIOs. The incoming BIO is used to pass data from Python to the SSL protocol instance, while the outgoing BIO is used to pass data the other way around.
The following methods are available:
When compared to SSLSocket, this object lacks the following features:
Some notes related to the use of SSLObject:
Changed in version 3.7: SSLObject instances must to created with wrap_bio(). In earlier versions, it was possible to create instances directly. This was never documented or officially supported.


SSL sockets provide the following methods of Socket Objects:
However, since the SSL (and TLS) protocol has its own framing atop of TCP, the SSL sockets abstraction can, in certain respects, diverge from the specification of normal, OS-level sockets. See especially the notes on non-blocking sockets.
Instances of SSLSocket must be created using the SSLContext.wrap_socket() method.
Changed in version 3.5: The sendfile() method was added.
Changed in version 3.5: The shutdown() does not reset the socket timeout each time bytes are received or sent. The socket timeout is now to maximum total duration of the shutdown.
Deprecated since version 3.6: It is deprecated to create a SSLSocket instance directly, use SSLContext.wrap_socket() to wrap a socket.
Changed in version 3.7: SSLSocket instances must to created with wrap_socket(). In earlier versions, it was possible to create instances directly. This was never documented or officially supported.


Returns a three-value tuple containing the name of the cipher being used, the version of the SSL protocol that defines its use, and the number of secret bits being used. If no connection has been established, returns None.


Return the compression algorithm being used as a string, or None if the connection isn’t compressed.
If the higher-level protocol supports its own compression mechanism, you can use OP_NO_COMPRESSION to disable SSL-level compression.
New in version 3.3.


The SSLContext object this SSL socket is tied to. If the SSL socket was created using the deprecated wrap_socket() function (rather than SSLContext.wrap_socket()), this is a custom context object created for this SSL socket.
New in version 3.2.


Perform the SSL setup handshake.
Changed in version 3.4: The handshake method also performs match_hostname() when the check_hostname attribute of the socket’s context is true.
Changed in version 3.5: The socket timeout is no more reset each time bytes are received or sent. The socket timeout is now to maximum total duration of the handshake.
Changed in version 3.7: Hostname or IP address is matched by OpenSSL during handshake. The function match_hostname() is no longer used. In case OpenSSL refuses a hostname or IP address, the handshake is aborted early and a TLS alert message is send to the peer.


If there is no certificate for the peer on the other end of the connection, return None. If the SSL handshake hasn’t been done yet, raise ValueError.
If the binary_form parameter is False, and a certificate was received from the peer, this method returns a dict instance. If the certificate was not validated, the dict is empty. If the certificate was validated, it returns a dict with several keys, amongst them subject (the principal for which the certificate was issued) and issuer (the principal issuing the certificate). If a certificate contains an instance of the Subject Alternative Name extension (see RFC 3280), there will also be a subjectAltName key in the dictionary.
The subject and issuer fields are tuples containing the sequence of relative distinguished names (RDNs) given in the certificate’s data structure for the respective fields, and each RDN is a sequence of name-value pairs. Here is a real-world example:
Note
To validate a certificate for a particular service, you can use the match_hostname() function.
If the binary_form parameter is True, and a certificate was provided, this method returns the DER-encoded form of the entire certificate as a sequence of bytes, or None if the peer did not provide a certificate. Whether the peer provides a certificate depends on the SSL socket’s role:
Changed in version 3.2: The returned dictionary includes additional items such as issuer and notBefore.
Changed in version 3.4: ValueError is raised when the handshake isn’t done. The returned dictionary includes additional X509v3 extension items such as crlDistributionPoints, caIssuers and OCSP URIs.
Changed in version 3.9: IPv6 address strings no longer have a trailing new line.


Get channel binding data for current connection, as a bytes object. Returns None if not connected or the handshake has not been completed.
The cb_type parameter allow selection of the desired channel binding type. Valid channel binding types are listed in the CHANNEL_BINDING_TYPES list. Currently only the ‘tls-unique’ channel binding, defined by RFC 5929, is supported. ValueError will be raised if an unsupported channel binding type is requested.
New in version 3.3.


Returns the number of already decrypted bytes available for read, pending on the connection.


Read up to len bytes of data from the SSL socket and return the result as a bytes instance. If buffer is specified, then read into the buffer instead, and return the number of bytes read.
Raise SSLWantReadError or SSLWantWriteError if the socket is non-blocking and the read would block.
As at any time a re-negotiation is possible, a call to read() can also cause write operations.
Changed in version 3.5: The socket timeout is no more reset each time bytes are received or sent. The socket timeout is now to maximum total duration to read up to len bytes.
Deprecated since version 3.6: Use recv() instead of read().


Return the protocol that was selected during the TLS handshake. If SSLContext.set_alpn_protocols() was not called, if the other party does not support ALPN, if this socket does not support any of the client’s proposed protocols, or if the handshake has not happened yet, None is returned.
New in version 3.5.


Return the higher-level protocol that was selected during the TLS/SSL handshake. If SSLContext.set_npn_protocols() was not called, or if the other party does not support NPN, or if the handshake has not yet happened, this will return None.
New in version 3.3.


Hostname of the server: str type, or None for server-side socket or if the hostname was not specified in the constructor.
New in version 3.2.
Changed in version 3.7: The attribute is now always ASCII text. When server_hostname is an internationalized domain name (IDN), this attribute now stores the A-label form ("xn--pythn-mua.org"), rather than the U-label form ("pythön.org").


A boolean which is True for server-side sockets and False for client-side sockets.
New in version 3.2.


The SSLSession for this SSL connection. The session is available for client and server side sockets after the TLS handshake has been performed. For client sockets the session can be set before do_handshake() has been called to reuse a session.
New in version 3.6.


Return the list of ciphers shared by the client during the handshake. Each entry of the returned list is a three-value tuple containing the name of the cipher, the version of the SSL protocol that defines its use, and the number of secret bits the cipher uses. shared_ciphers() returns None if no connection has been established or the socket is a client socket.
New in version 3.5.


Performs the SSL shutdown handshake, which removes the TLS layer from the underlying socket, and returns the underlying socket object. This can be used to go from encrypted operation over a connection to unencrypted. The returned socket should always be used for further communication with the other side of the connection, rather than the original socket.


Requests post-handshake authentication (PHA) from a TLS 1.3 client. PHA can only be initiated for a TLS 1.3 connection from a server-side socket, after the initial TLS handshake and with PHA enabled on both sides, see SSLContext.post_handshake_auth.
The method does not perform a cert exchange immediately. The server-side sends a CertificateRequest during the next write event and expects the client to respond with a certificate on the next read event.
If any precondition isn’t met (e.g. not TLS 1.3, PHA not enabled), an SSLError is raised.
Note
Only available with OpenSSL 1.1.1 and TLS 1.3 enabled. Without TLS 1.3 support, the method raises NotImplementedError.
New in version 3.8.


Return the actual SSL protocol version negotiated by the connection as a string, or None is no secure connection is established. As of this writing, possible return values include "SSLv2", "SSLv3", "TLSv1", "TLSv1.1" and "TLSv1.2". Recent OpenSSL versions may define more return values.
New in version 3.5.


Write buf to the SSL socket and return the number of bytes written. The buf argument must be an object supporting the buffer interface.
Raise SSLWantReadError or SSLWantWriteError if the socket is non-blocking and the write would block.
As at any time a re-negotiation is possible, a call to write() can also cause read operations.
Changed in version 3.5: The socket timeout is no more reset each time bytes are received or sent. The socket timeout is now to maximum total duration to write buf.
Deprecated since version 3.6: Use send() instead of write().


A subclass of SSLError raised when a system error was encountered while trying to fulfill an operation on a SSL socket. Unfortunately, there is no easy way to inspect the original errno number.
New in version 3.3.


A subclass of SSLError raised by a non-blocking SSL socket when trying to read or write data, but more data needs to be received on the underlying TCP transport before the request can be fulfilled.
New in version 3.3.


A subclass of SSLError raised by a non-blocking SSL socket when trying to read or write data, but more data needs to be sent on the underlying TCP transport before the request can be fulfilled.
New in version 3.3.


A subclass of SSLError raised when trying to read or write and the SSL connection has been closed cleanly. Note that this doesn’t mean that the underlying transport (read TCP) has been closed.
New in version 3.3.


enum.IntEnum collection of SSL and TLS versions for SSLContext.maximum_version and SSLContext.minimum_version.
New in version 3.7.


The minimum or maximum supported SSL or TLS version. These are magic constants. Their values don’t reflect the lowest and highest available TLS/SSL versions.


enum.IntFlag collection of VERIFY_* constants.
New in version 3.6.


enum.IntEnum collection of CERT_* constants.
New in version 3.6.


Possible value for SSLContext.verify_flags. In this mode, CRLs of all certificates in the peer cert chain are checked.
New in version 3.4.


Possible value for SSLContext.verify_flags. In this mode, only the peer cert is checked but none of the intermediate CA certificates. The mode requires a valid CRL that is signed by the peer cert’s issuer (its direct ancestor CA). If no proper CRL has been loaded with SSLContext.load_verify_locations, validation will fail.
New in version 3.4.


Possible value for SSLContext.verify_flags. In this mode, certificate revocation lists (CRLs) are not checked. By default OpenSSL does neither require nor verify CRLs.
New in version 3.4.


Possible value for SSLContext.verify_flags to disable workarounds for broken X.509 certificates.
New in version 3.4.


Possible value for SSLContext.verify_flags. It instructs OpenSSL to prefer trusted certificates when building the trust chain to validate a certificate. This flag is enabled by default.
New in version 3.4.4.


Takes an instance sock of socket.socket, and returns an instance of ssl.SSLSocket, a subtype of socket.socket, which wraps the underlying socket in an SSL context. sock must be a SOCK_STREAM socket; other socket types are unsupported.
Internally, function creates a SSLContext with protocol ssl_version and SSLContext.options set to cert_reqs. If parameters keyfile, certfile, ca_certs or ciphers are set, then the values are passed to SSLContext.load_cert_chain(), SSLContext.load_verify_locations(), and SSLContext.set_ciphers().
The arguments server_side, do_handshake_on_connect, and suppress_ragged_eofs have the same meaning as SSLContext.wrap_socket().
Deprecated since version 3.7: Since Python 3.2 and 2.7.9, it is recommended to use the SSLContext.wrap_socket() instead of wrap_socket(). The top-level function is limited and creates an insecure client socket without server name indication or hostname matching.


Source code: Lib/stat.py
The stat module defines constants and functions for interpreting the results of os.stat(), os.fstat() and os.lstat() (if they exist). For complete details about the stat(), fstat() and lstat() calls, consult the documentation for your system.
Changed in version 3.4: The stat module is backed by a C implementation.
The stat module defines the following functions to test for specific file types:
Return non-zero if the mode is from a directory.
Return non-zero if the mode is from a character special device file.
Return non-zero if the mode is from a block special device file.
Return non-zero if the mode is from a regular file.
Return non-zero if the mode is from a FIFO (named pipe).
Return non-zero if the mode is from a symbolic link.
Return non-zero if the mode is from a socket.
Return non-zero if the mode is from a door.
New in version 3.4.
Return non-zero if the mode is from an event port.
New in version 3.4.
Return non-zero if the mode is from a whiteout.
New in version 3.4.
Two additional functions are defined for more general manipulation of the file’s mode:
Return the portion of the file’s mode that can be set by os.chmod()—that is, the file’s permission bits, plus the sticky bit, set-group-id, and set-user-id bits (on systems that support them).
Return the portion of the file’s mode that describes the file type (used by the S_IS*() functions above).
Normally, you would use the os.path.is*() functions for testing the type of a file; the functions here are useful when you are doing multiple tests of the same file and wish to avoid the overhead of the stat() system call for each test. These are also useful when checking for information about a file that isn’t handled by os.path, like the tests for block and character devices.
Example:
An additional utility function is provided to convert a file’s mode in a human readable string:
Convert a file’s mode to a string of the form ‘-rwxrwxrwx’.
New in version 3.3.
Changed in version 3.4: The function supports S_IFDOOR, S_IFPORT and S_IFWHT.
All the variables below are simply symbolic indexes into the 10-tuple returned by os.stat(), os.fstat() or os.lstat().
Inode protection mode.
Inode number.
Device inode resides on.
Number of links to the inode.
User id of the owner.
Group id of the owner.
Size in bytes of a plain file; amount of data waiting on some special files.
Time of last access.
Time of last modification.
The “ctime” as reported by the operating system. On some systems (like Unix) is the time of the last metadata change, and, on others (like Windows), is the creation time (see platform documentation for details).
The interpretation of “file size” changes according to the file type. For plain files this is the size of the file in bytes. For FIFOs and sockets under most flavors of Unix (including Linux in particular), the “size” is the number of bytes waiting to be read at the time of the call to os.stat(), os.fstat(), or os.lstat(); this can sometimes be useful, especially for polling one of these special files after a non-blocking open. The meaning of the size field for other character and block devices varies more, depending on the implementation of the underlying system call.
The variables below define the flags used in the ST_MODE field.
Use of the functions above is more portable than use of the first set of flags:
Socket.
Symbolic link.
Regular file.
Block device.
Directory.
Character device.
FIFO.
Door.
New in version 3.4.
Event port.
New in version 3.4.
Whiteout.
New in version 3.4.
Note
S_IFDOOR, S_IFPORT or S_IFWHT are defined as 0 when the platform does not have support for the file types.
The following flags can also be used in the mode argument of os.chmod():
Set UID bit.
Set-group-ID bit. This bit has several special uses. For a directory it indicates that BSD semantics is to be used for that directory: files created there inherit their group ID from the directory, not from the effective group ID of the creating process, and directories created there will also get the S_ISGID bit set. For a file that does not have the group execution bit (S_IXGRP) set, the set-group-ID bit indicates mandatory file/record locking (see also S_ENFMT).
Sticky bit. When this bit is set on a directory it means that a file in that directory can be renamed or deleted only by the owner of the file, by the owner of the directory, or by a privileged process.
Mask for file owner permissions.
Owner has read permission.
Owner has write permission.
Owner has execute permission.
Mask for group permissions.
Group has read permission.
Group has write permission.
Group has execute permission.
Mask for permissions for others (not in group).
Others have read permission.
Others have write permission.
Others have execute permission.
System V file locking enforcement. This flag is shared with S_ISGID: file/record locking is enforced on files that do not have the group execution bit (S_IXGRP) set.
Unix V7 synonym for S_IRUSR.
Unix V7 synonym for S_IWUSR.
Unix V7 synonym for S_IXUSR.
The following flags can be used in the flags argument of os.chflags():
Do not dump the file.
The file may not be changed.
The file may only be appended to.
The directory is opaque when viewed through a union stack.
The file may not be renamed or deleted.
The file is stored compressed (Mac OS X 10.6+).
The file should not be displayed in a GUI (Mac OS X 10.5+).
The file may be archived.
The file may not be changed.
The file may only be appended to.
The file may not be renamed or deleted.
The file is a snapshot file.
See the *BSD or Mac OS systems man page chflags(2) for more information.
On Windows, the following file attribute constants are available for use when testing bits in the st_file_attributes member returned by os.stat(). See the Windows API documentation for more detail on the meaning of these constants.
New in version 3.5.
On Windows, the following constants are available for comparing against the st_reparse_tag member returned by os.lstat(). These are well-known constants, but are not an exhaustive list.
New in version 3.8.


Convert a file’s mode to a string of the form ‘-rwxrwxrwx’.
New in version 3.3.
Changed in version 3.4: The function supports S_IFDOOR, S_IFPORT and S_IFWHT.


The “ctime” as reported by the operating system. On some systems (like Unix) is the time of the last metadata change, and, on others (like Windows), is the creation time (see platform documentation for details).


Size in bytes of a plain file; amount of data waiting on some special files.


System V file locking enforcement. This flag is shared with S_ISGID: file/record locking is enforced on files that do not have the group execution bit (S_IXGRP) set.


Return the portion of the file’s mode that describes the file type (used by the S_IS*() functions above).


Return the portion of the file’s mode that can be set by os.chmod()—that is, the file’s permission bits, plus the sticky bit, set-group-id, and set-user-id bits (on systems that support them).


Mask for permissions for others (not in group).


Return non-zero if the mode is from a block special device file.


Return non-zero if the mode is from a character special device file.


Return non-zero if the mode is from a directory.


Return non-zero if the mode is from a door.
New in version 3.4.


Return non-zero if the mode is from a FIFO (named pipe).


Set-group-ID bit. This bit has several special uses. For a directory it indicates that BSD semantics is to be used for that directory: files created there inherit their group ID from the directory, not from the effective group ID of the creating process, and directories created there will also get the S_ISGID bit set. For a file that does not have the group execution bit (S_IXGRP) set, the set-group-ID bit indicates mandatory file/record locking (see also S_ENFMT).


Return non-zero if the mode is from a symbolic link.


Return non-zero if the mode is from an event port.
New in version 3.4.


Return non-zero if the mode is from a regular file.


Return non-zero if the mode is from a socket.


Sticky bit. When this bit is set on a directory it means that a file in that directory can be renamed or deleted only by the owner of the file, by the owner of the directory, or by a privileged process.


Return non-zero if the mode is from a whiteout.
New in version 3.4.


The file is stored compressed (Mac OS X 10.6+).


The file should not be displayed in a GUI (Mac OS X 10.5+).


The directory is opaque when viewed through a union stack.


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 decorator – see Function definitions for details.
A static method can be called either on the class (such as C.f()) or on an instance (such as C().f()).
Static methods in Python are similar to those found in Java or C++. Also see classmethod() for a variant that is useful for creating alternate class constructors.
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.


New in version 3.4.
Source code: Lib/statistics.py
This module provides functions for calculating mathematical statistics of numeric (Real-valued) data.
The module is not intended to be a competitor to third-party libraries such as NumPy, SciPy, or proprietary full-featured statistics packages aimed at professional statisticians such as Minitab, SAS and Matlab. It is aimed at the level of graphing and scientific calculators.
Unless explicitly noted, these functions support int, float, Decimal and Fraction. Behaviour with other types (whether in the numeric tower or not) is currently unsupported. Collections with a mix of types are also undefined and implementation-dependent. If your input data consists of mixed types, you may be able to use map() to ensure a consistent result, for example: map(float, input_data).
These functions calculate an average or typical value from a population or sample.
mean()
Arithmetic mean (“average”) of data.
fmean()
Fast, floating point arithmetic mean.
geometric_mean()
Geometric mean of data.
harmonic_mean()
Harmonic mean of data.
median()
Median (middle value) of data.
median_low()
Low median of data.
median_high()
High median of data.
median_grouped()
Median, or 50th percentile, of grouped data.
mode()
Single mode (most common value) of discrete or nominal data.
multimode()
List of modes (most common values) of discrete or nomimal data.
quantiles()
Divide data into intervals with equal probability.
These functions calculate a measure of how much the population or sample tends to deviate from the typical or average values.
pstdev()
Population standard deviation of data.
pvariance()
Population variance of data.
stdev()
Sample standard deviation of data.
variance()
Sample variance of data.
Note: The functions do not require the data given to them to be sorted. However, for reading convenience, most of the examples show sorted sequences.
Return the sample arithmetic mean of data which can be a sequence or iterable.
The arithmetic mean is the sum of the data divided by the number of data points. It is commonly called “the average”, although it is only one of many different mathematical averages. It is a measure of the central location of the data.
If data is empty, StatisticsError will be raised.
Some examples of use:
Note
The mean is strongly affected by outliers and is not a robust estimator for central location: the mean is not necessarily a typical example of the data points. For more robust measures of central location, see median() and mode().
The sample mean gives an unbiased estimate of the true population mean, so that when taken on average over all the possible samples, mean(sample) converges on the true mean of the entire population. If data represents the entire population rather than a sample, then mean(data) is equivalent to calculating the true population mean μ.
Convert data to floats and compute the arithmetic mean.
This runs faster than the mean() function and it always returns a float. The data may be a sequence or iterable. If the input dataset is empty, raises a StatisticsError.
New in version 3.8.
Convert data to floats and compute the geometric mean.
The geometric mean indicates the central tendency or typical value of the data using the product of the values (as opposed to the arithmetic mean which uses their sum).
Raises a StatisticsError if the input dataset is empty, if it contains a zero, or if it contains a negative value. The data may be a sequence or iterable.
No special efforts are made to achieve exact results. (However, this may change in the future.)
New in version 3.8.
Return the harmonic mean of data, a sequence or iterable of real-valued numbers.
The harmonic mean, sometimes called the subcontrary mean, is the reciprocal of the arithmetic mean() of the reciprocals of the data. For example, the harmonic mean of three values a, b and c will be equivalent to 3/(1/a + 1/b + 1/c). If one of the values is zero, the result will be zero.
The harmonic mean is a type of average, a measure of the central location of the data. It is often appropriate when averaging rates or ratios, for example speeds.
Suppose a car travels 10 km at 40 km/hr, then another 10 km at 60 km/hr. What is the average speed?
Suppose an investor purchases an equal value of shares in each of three companies, with P/E (price/earning) ratios of 2.5, 3 and 10. What is the average P/E ratio for the investor’s portfolio?
StatisticsError is raised if data is empty, or any element is less than zero.
The current algorithm has an early-out when it encounters a zero in the input. This means that the subsequent inputs are not tested for validity. (This behavior may change in the future.)
New in version 3.6.
Return the median (middle value) of numeric data, using the common “mean of middle two” method. If data is empty, StatisticsError is raised. data can be a sequence or iterable.
The median is a robust measure of central location and is less affected by the presence of outliers. When the number of data points is odd, the middle data point is returned:
When the number of data points is even, the median is interpolated by taking the average of the two middle values:
This is suited for when your data is discrete, and you don’t mind that the median may not be an actual data point.
If the data is ordinal (supports order operations) but not numeric (doesn’t support addition), consider using median_low() or median_high() instead.
Return the low median of numeric data. If data is empty, StatisticsError is raised. data can be a sequence or iterable.
The low median is always a member of the data set. When the number of data points is odd, the middle value is returned. When it is even, the smaller of the two middle values is returned.
Use the low median when your data are discrete and you prefer the median to be an actual data point rather than interpolated.
Return the high median of data. If data is empty, StatisticsError is raised. data can be a sequence or iterable.
The high median is always a member of the data set. When the number of data points is odd, the middle value is returned. When it is even, the larger of the two middle values is returned.
Use the high median when your data are discrete and you prefer the median to be an actual data point rather than interpolated.
Return the median of grouped continuous data, calculated as the 50th percentile, using interpolation. If data is empty, StatisticsError is raised. data can be a sequence or iterable.
In the following example, the data are rounded, so that each value represents the midpoint of data classes, e.g. 1 is the midpoint of the class 0.5–1.5, 2 is the midpoint of 1.5–2.5, 3 is the midpoint of 2.5–3.5, etc. With the data given, the middle value falls somewhere in the class 3.5–4.5, and interpolation is used to estimate it:
Optional argument interval represents the class interval, and defaults to 1. Changing the class interval naturally will change the interpolation:
This function does not check whether the data points are at least interval apart.
CPython implementation detail: Under some circumstances, median_grouped() may coerce data points to floats. This behaviour is likely to change in the future.
See also
Return the single most common data point from discrete or nominal data. The mode (when it exists) is the most typical value and serves as a measure of central location.
If there are multiple modes with the same frequency, returns the first one encountered in the data. If the smallest or largest of those is desired instead, use min(multimode(data)) or max(multimode(data)). If the input data is empty, StatisticsError is raised.
mode assumes discrete data and returns a single value. This is the standard treatment of the mode as commonly taught in schools:
The mode is unique in that it is the only statistic in this package that also applies to nominal (non-numeric) data:
Changed in version 3.8: Now handles multimodal datasets by returning the first mode encountered. Formerly, it raised StatisticsError when more than one mode was found.
Return a list of the most frequently occurring values in the order they were first encountered in the data. Will return more than one result if there are multiple modes or an empty list if the data is empty:
New in version 3.8.
Return the population standard deviation (the square root of the population variance). See pvariance() for arguments and other details.
Return the population variance of data, a non-empty sequence or iterable of real-valued numbers. Variance, or second moment about the mean, is a measure of the variability (spread or dispersion) of data. A large variance indicates that the data is spread out; a small variance indicates it is clustered closely around the mean.
If the optional second argument mu is given, it is typically the mean of the data. It can also be used to compute the second moment around a point that is not the mean. If it is missing or None (the default), the arithmetic mean is automatically calculated.
Use this function to calculate the variance from the entire population. To estimate the variance from a sample, the variance() function is usually a better choice.
Raises StatisticsError if data is empty.
Examples:
If you have already calculated the mean of your data, you can pass it as the optional second argument mu to avoid recalculation:
Decimals and Fractions are supported:
Note
When called with the entire population, this gives the population variance σ². When called on a sample instead, this is the biased sample variance s², also known as variance with N degrees of freedom.
If you somehow know the true population mean μ, you may use this function to calculate the variance of a sample, giving the known population mean as the second argument. Provided the data points are a random sample of the population, the result will be an unbiased estimate of the population variance.
Return the sample standard deviation (the square root of the sample variance). See variance() for arguments and other details.
Return the sample variance of data, an iterable of at least two real-valued numbers. Variance, or second moment about the mean, is a measure of the variability (spread or dispersion) of data. A large variance indicates that the data is spread out; a small variance indicates it is clustered closely around the mean.
If the optional second argument xbar is given, it should be the mean of data. If it is missing or None (the default), the mean is automatically calculated.
Use this function when your data is a sample from a population. To calculate the variance from the entire population, see pvariance().
Raises StatisticsError if data has fewer than two values.
Examples:
If you have already calculated the mean of your data, you can pass it as the optional second argument xbar to avoid recalculation:
This function does not attempt to verify that you have passed the actual mean as xbar. Using arbitrary values for xbar can lead to invalid or impossible results.
Decimal and Fraction values are supported:
Note
This is the sample variance s² with Bessel’s correction, also known as variance with N-1 degrees of freedom. Provided that the data points are representative (e.g. independent and identically distributed), the result should be an unbiased estimate of the true population variance.
If you somehow know the actual population mean μ you should pass it to the pvariance() function as the mu parameter to get the variance of a sample.
Divide data into n continuous intervals with equal probability. Returns a list of n - 1 cut points separating the intervals.
Set n to 4 for quartiles (the default). Set n to 10 for deciles. Set n to 100 for percentiles which gives the 99 cuts points that separate data into 100 equal sized groups. Raises StatisticsError if n is not least 1.
The data can be any iterable containing sample data. For meaningful results, the number of data points in data should be larger than n. Raises StatisticsError if there are not at least two data points.
The cut points are linearly interpolated from the two nearest data points. For example, if a cut point falls one-third of the distance between two sample values, 100 and 112, the cut-point will evaluate to 104.
The method for computing quantiles can be varied depending on whether the data includes or excludes the lowest and highest possible values from the population.
The default method is “exclusive” and is used for data sampled from a population that can have more extreme values than found in the samples. The portion of the population falling below the i-th of m sorted data points is computed as i / (m + 1). Given nine sample values, the method sorts them and assigns the following percentiles: 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90%.
Setting the method to “inclusive” is used for describing population data or for samples that are known to include the most extreme values from the population. The minimum value in data is treated as the 0th percentile and the maximum value is treated as the 100th percentile. The portion of the population falling below the i-th of m sorted data points is computed as (i - 1) / (m - 1). Given 11 sample values, the method sorts them and assigns the following percentiles: 0%, 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90%, 100%.
New in version 3.8.
A single exception is defined:
Subclass of ValueError for statistics-related exceptions.
NormalDist is a tool for creating and manipulating normal distributions of a random variable. It is a class that treats the mean and standard deviation of data measurements as a single entity.
Normal distributions arise from the Central Limit Theorem and have a wide range of applications in statistics.
Returns a new NormalDist object where mu represents the arithmetic mean and sigma represents the standard deviation.
If sigma is negative, raises StatisticsError.
A read-only property for the arithmetic mean of a normal distribution.
A read-only property for the median of a normal distribution.
A read-only property for the mode of a normal distribution.
A read-only property for the standard deviation of a normal distribution.
A read-only property for the variance of a normal distribution. Equal to the square of the standard deviation.
Makes a normal distribution instance with mu and sigma parameters estimated from the data using fmean() and stdev().
The data can be any iterable and should consist of values that can be converted to type float. If data does not contain at least two elements, raises StatisticsError because it takes at least one point to estimate a central value and at least two points to estimate dispersion.
Generates n random samples for a given mean and standard deviation. Returns a list of float values.
If seed is given, creates a new instance of the underlying random number generator. This is useful for creating reproducible results, even in a multi-threading context.
Using a probability density function (pdf), compute the relative likelihood that a random variable X will be near the given value x. Mathematically, it is the limit of the ratio P(x <=
X < x+dx) / dx as dx approaches zero.
The relative likelihood is computed as the probability of a sample occurring in a narrow range divided by the width of the range (hence the word “density”). Since the likelihood is relative to other points, its value can be greater than 1.0.
Using a cumulative distribution function (cdf), compute the probability that a random variable X will be less than or equal to x. Mathematically, it is written P(X <= x).
Compute the inverse cumulative distribution function, also known as the quantile function or the percent-point function. Mathematically, it is written x : P(X <= x) = p.
Finds the value x of the random variable X such that the probability of the variable being less than or equal to that value equals the given probability p.
Measures the agreement between two normal probability distributions. Returns a value between 0.0 and 1.0 giving the overlapping area for the two probability density functions.
Divide the normal distribution into n continuous intervals with equal probability. Returns a list of (n - 1) cut points separating the intervals.
Set n to 4 for quartiles (the default). Set n to 10 for deciles. Set n to 100 for percentiles which gives the 99 cuts points that separate the normal distribution into 100 equal sized groups.
Compute the Standard Score describing x in terms of the number of standard deviations above or below the mean of the normal distribution: (x - mean) / stdev.
New in version 3.9.
Instances of NormalDist support addition, subtraction, multiplication and division by a constant. These operations are used for translation and scaling. For example:
Dividing a constant by an instance of NormalDist is not supported because the result wouldn’t be normally distributed.
Since normal distributions arise from additive effects of independent variables, it is possible to add and subtract two independent normally distributed random variables represented as instances of NormalDist. For example:
New in version 3.8.
NormalDist readily solves classic probability problems.
For example, given historical data for SAT exams showing that scores are normally distributed with a mean of 1060 and a standard deviation of 195, determine the percentage of students with test scores between 1100 and 1200, after rounding to the nearest whole number:
Find the quartiles and deciles for the SAT scores:
To estimate the distribution for a model than isn’t easy to solve analytically, NormalDist can generate input samples for a Monte Carlo simulation:
Normal distributions can be used to approximate Binomial distributions when the sample size is large and when the probability of a successful trial is near 50%.
For example, an open source conference has 750 attendees and two rooms with a 500 person capacity. There is a talk about Python and another about Ruby. In previous conferences, 65% of the attendees preferred to listen to Python talks. Assuming the population preferences haven’t changed, what is the probability that the Python room will stay within its capacity limits?
Normal distributions commonly arise in machine learning problems.
Wikipedia has a nice example of a Naive Bayesian Classifier. The challenge is to predict a person’s gender from measurements of normally distributed features including height, weight, and foot size.
We’re given a training dataset with measurements for eight people. The measurements are assumed to be normally distributed, so we summarize the data with NormalDist:
Next, we encounter a new person whose feature measurements are known but whose gender is unknown:
Starting with a 50% prior probability of being male or female, we compute the posterior as the prior times the product of likelihoods for the feature measurements given the gender:
The final prediction goes to the largest posterior. This is known as the maximum a posteriori or MAP:


Convert data to floats and compute the arithmetic mean.
This runs faster than the mean() function and it always returns a float. The data may be a sequence or iterable. If the input dataset is empty, raises a StatisticsError.
New in version 3.8.


Convert data to floats and compute the geometric mean.
The geometric mean indicates the central tendency or typical value of the data using the product of the values (as opposed to the arithmetic mean which uses their sum).
Raises a StatisticsError if the input dataset is empty, if it contains a zero, or if it contains a negative value. The data may be a sequence or iterable.
No special efforts are made to achieve exact results. (However, this may change in the future.)
New in version 3.8.


Return the harmonic mean of data, a sequence or iterable of real-valued numbers.
The harmonic mean, sometimes called the subcontrary mean, is the reciprocal of the arithmetic mean() of the reciprocals of the data. For example, the harmonic mean of three values a, b and c will be equivalent to 3/(1/a + 1/b + 1/c). If one of the values is zero, the result will be zero.
The harmonic mean is a type of average, a measure of the central location of the data. It is often appropriate when averaging rates or ratios, for example speeds.
Suppose a car travels 10 km at 40 km/hr, then another 10 km at 60 km/hr. What is the average speed?
Suppose an investor purchases an equal value of shares in each of three companies, with P/E (price/earning) ratios of 2.5, 3 and 10. What is the average P/E ratio for the investor’s portfolio?
StatisticsError is raised if data is empty, or any element is less than zero.
The current algorithm has an early-out when it encounters a zero in the input. This means that the subsequent inputs are not tested for validity. (This behavior may change in the future.)
New in version 3.6.


Return the sample arithmetic mean of data which can be a sequence or iterable.
The arithmetic mean is the sum of the data divided by the number of data points. It is commonly called “the average”, although it is only one of many different mathematical averages. It is a measure of the central location of the data.
If data is empty, StatisticsError will be raised.
Some examples of use:
Note
The mean is strongly affected by outliers and is not a robust estimator for central location: the mean is not necessarily a typical example of the data points. For more robust measures of central location, see median() and mode().
The sample mean gives an unbiased estimate of the true population mean, so that when taken on average over all the possible samples, mean(sample) converges on the true mean of the entire population. If data represents the entire population rather than a sample, then mean(data) is equivalent to calculating the true population mean μ.


Return the median (middle value) of numeric data, using the common “mean of middle two” method. If data is empty, StatisticsError is raised. data can be a sequence or iterable.
The median is a robust measure of central location and is less affected by the presence of outliers. When the number of data points is odd, the middle data point is returned:
When the number of data points is even, the median is interpolated by taking the average of the two middle values:
This is suited for when your data is discrete, and you don’t mind that the median may not be an actual data point.
If the data is ordinal (supports order operations) but not numeric (doesn’t support addition), consider using median_low() or median_high() instead.


Return the median of grouped continuous data, calculated as the 50th percentile, using interpolation. If data is empty, StatisticsError is raised. data can be a sequence or iterable.
In the following example, the data are rounded, so that each value represents the midpoint of data classes, e.g. 1 is the midpoint of the class 0.5–1.5, 2 is the midpoint of 1.5–2.5, 3 is the midpoint of 2.5–3.5, etc. With the data given, the middle value falls somewhere in the class 3.5–4.5, and interpolation is used to estimate it:
Optional argument interval represents the class interval, and defaults to 1. Changing the class interval naturally will change the interpolation:
This function does not check whether the data points are at least interval apart.
CPython implementation detail: Under some circumstances, median_grouped() may coerce data points to floats. This behaviour is likely to change in the future.
See also


Return the high median of data. If data is empty, StatisticsError is raised. data can be a sequence or iterable.
The high median is always a member of the data set. When the number of data points is odd, the middle value is returned. When it is even, the larger of the two middle values is returned.
Use the high median when your data are discrete and you prefer the median to be an actual data point rather than interpolated.


Return the low median of numeric data. If data is empty, StatisticsError is raised. data can be a sequence or iterable.
The low median is always a member of the data set. When the number of data points is odd, the middle value is returned. When it is even, the smaller of the two middle values is returned.
Use the low median when your data are discrete and you prefer the median to be an actual data point rather than interpolated.


Return the single most common data point from discrete or nominal data. The mode (when it exists) is the most typical value and serves as a measure of central location.
If there are multiple modes with the same frequency, returns the first one encountered in the data. If the smallest or largest of those is desired instead, use min(multimode(data)) or max(multimode(data)). If the input data is empty, StatisticsError is raised.
mode assumes discrete data and returns a single value. This is the standard treatment of the mode as commonly taught in schools:
The mode is unique in that it is the only statistic in this package that also applies to nominal (non-numeric) data:
Changed in version 3.8: Now handles multimodal datasets by returning the first mode encountered. Formerly, it raised StatisticsError when more than one mode was found.


Return a list of the most frequently occurring values in the order they were first encountered in the data. Will return more than one result if there are multiple modes or an empty list if the data is empty:
New in version 3.8.


Returns a new NormalDist object where mu represents the arithmetic mean and sigma represents the standard deviation.
If sigma is negative, raises StatisticsError.
A read-only property for the arithmetic mean of a normal distribution.
A read-only property for the median of a normal distribution.
A read-only property for the mode of a normal distribution.
A read-only property for the standard deviation of a normal distribution.
A read-only property for the variance of a normal distribution. Equal to the square of the standard deviation.
Makes a normal distribution instance with mu and sigma parameters estimated from the data using fmean() and stdev().
The data can be any iterable and should consist of values that can be converted to type float. If data does not contain at least two elements, raises StatisticsError because it takes at least one point to estimate a central value and at least two points to estimate dispersion.
Generates n random samples for a given mean and standard deviation. Returns a list of float values.
If seed is given, creates a new instance of the underlying random number generator. This is useful for creating reproducible results, even in a multi-threading context.
Using a probability density function (pdf), compute the relative likelihood that a random variable X will be near the given value x. Mathematically, it is the limit of the ratio P(x <=
X < x+dx) / dx as dx approaches zero.
The relative likelihood is computed as the probability of a sample occurring in a narrow range divided by the width of the range (hence the word “density”). Since the likelihood is relative to other points, its value can be greater than 1.0.
Using a cumulative distribution function (cdf), compute the probability that a random variable X will be less than or equal to x. Mathematically, it is written P(X <= x).
Compute the inverse cumulative distribution function, also known as the quantile function or the percent-point function. Mathematically, it is written x : P(X <= x) = p.
Finds the value x of the random variable X such that the probability of the variable being less than or equal to that value equals the given probability p.
Measures the agreement between two normal probability distributions. Returns a value between 0.0 and 1.0 giving the overlapping area for the two probability density functions.
Divide the normal distribution into n continuous intervals with equal probability. Returns a list of (n - 1) cut points separating the intervals.
Set n to 4 for quartiles (the default). Set n to 10 for deciles. Set n to 100 for percentiles which gives the 99 cuts points that separate the normal distribution into 100 equal sized groups.
Compute the Standard Score describing x in terms of the number of standard deviations above or below the mean of the normal distribution: (x - mean) / stdev.
New in version 3.9.
Instances of NormalDist support addition, subtraction, multiplication and division by a constant. These operations are used for translation and scaling. For example:
Dividing a constant by an instance of NormalDist is not supported because the result wouldn’t be normally distributed.
Since normal distributions arise from additive effects of independent variables, it is possible to add and subtract two independent normally distributed random variables represented as instances of NormalDist. For example:
New in version 3.8.


Using a cumulative distribution function (cdf), compute the probability that a random variable X will be less than or equal to x. Mathematically, it is written P(X <= x).


Makes a normal distribution instance with mu and sigma parameters estimated from the data using fmean() and stdev().
The data can be any iterable and should consist of values that can be converted to type float. If data does not contain at least two elements, raises StatisticsError because it takes at least one point to estimate a central value and at least two points to estimate dispersion.


Compute the inverse cumulative distribution function, also known as the quantile function or the percent-point function. Mathematically, it is written x : P(X <= x) = p.
Finds the value x of the random variable X such that the probability of the variable being less than or equal to that value equals the given probability p.


A read-only property for the arithmetic mean of a normal distribution.


A read-only property for the median of a normal distribution.


A read-only property for the mode of a normal distribution.


Measures the agreement between two normal probability distributions. Returns a value between 0.0 and 1.0 giving the overlapping area for the two probability density functions.


Using a probability density function (pdf), compute the relative likelihood that a random variable X will be near the given value x. Mathematically, it is the limit of the ratio P(x <=
X < x+dx) / dx as dx approaches zero.
The relative likelihood is computed as the probability of a sample occurring in a narrow range divided by the width of the range (hence the word “density”). Since the likelihood is relative to other points, its value can be greater than 1.0.


Divide the normal distribution into n continuous intervals with equal probability. Returns a list of (n - 1) cut points separating the intervals.
Set n to 4 for quartiles (the default). Set n to 10 for deciles. Set n to 100 for percentiles which gives the 99 cuts points that separate the normal distribution into 100 equal sized groups.


Generates n random samples for a given mean and standard deviation. Returns a list of float values.
If seed is given, creates a new instance of the underlying random number generator. This is useful for creating reproducible results, even in a multi-threading context.


A read-only property for the standard deviation of a normal distribution.


A read-only property for the variance of a normal distribution. Equal to the square of the standard deviation.


Compute the Standard Score describing x in terms of the number of standard deviations above or below the mean of the normal distribution: (x - mean) / stdev.
New in version 3.9.


Return the population standard deviation (the square root of the population variance). See pvariance() for arguments and other details.


Return the population variance of data, a non-empty sequence or iterable of real-valued numbers. Variance, or second moment about the mean, is a measure of the variability (spread or dispersion) of data. A large variance indicates that the data is spread out; a small variance indicates it is clustered closely around the mean.
If the optional second argument mu is given, it is typically the mean of the data. It can also be used to compute the second moment around a point that is not the mean. If it is missing or None (the default), the arithmetic mean is automatically calculated.
Use this function to calculate the variance from the entire population. To estimate the variance from a sample, the variance() function is usually a better choice.
Raises StatisticsError if data is empty.
Examples:
If you have already calculated the mean of your data, you can pass it as the optional second argument mu to avoid recalculation:
Decimals and Fractions are supported:
Note
When called with the entire population, this gives the population variance σ². When called on a sample instead, this is the biased sample variance s², also known as variance with N degrees of freedom.
If you somehow know the true population mean μ, you may use this function to calculate the variance of a sample, giving the known population mean as the second argument. Provided the data points are a random sample of the population, the result will be an unbiased estimate of the population variance.


Divide data into n continuous intervals with equal probability. Returns a list of n - 1 cut points separating the intervals.
Set n to 4 for quartiles (the default). Set n to 10 for deciles. Set n to 100 for percentiles which gives the 99 cuts points that separate data into 100 equal sized groups. Raises StatisticsError if n is not least 1.
The data can be any iterable containing sample data. For meaningful results, the number of data points in data should be larger than n. Raises StatisticsError if there are not at least two data points.
The cut points are linearly interpolated from the two nearest data points. For example, if a cut point falls one-third of the distance between two sample values, 100 and 112, the cut-point will evaluate to 104.
The method for computing quantiles can be varied depending on whether the data includes or excludes the lowest and highest possible values from the population.
The default method is “exclusive” and is used for data sampled from a population that can have more extreme values than found in the samples. The portion of the population falling below the i-th of m sorted data points is computed as i / (m + 1). Given nine sample values, the method sorts them and assigns the following percentiles: 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90%.
Setting the method to “inclusive” is used for describing population data or for samples that are known to include the most extreme values from the population. The minimum value in data is treated as the 0th percentile and the maximum value is treated as the 100th percentile. The portion of the population falling below the i-th of m sorted data points is computed as (i - 1) / (m - 1). Given 11 sample values, the method sorts them and assigns the following percentiles: 0%, 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90%, 100%.
New in version 3.8.


Subclass of ValueError for statistics-related exceptions.


Return the sample standard deviation (the square root of the sample variance). See variance() for arguments and other details.


Return the sample variance of data, an iterable of at least two real-valued numbers. Variance, or second moment about the mean, is a measure of the variability (spread or dispersion) of data. A large variance indicates that the data is spread out; a small variance indicates it is clustered closely around the mean.
If the optional second argument xbar is given, it should be the mean of data. If it is missing or None (the default), the mean is automatically calculated.
Use this function when your data is a sample from a population. To calculate the variance from the entire population, see pvariance().
Raises StatisticsError if data has fewer than two values.
Examples:
If you have already calculated the mean of your data, you can pass it as the optional second argument xbar to avoid recalculation:
This function does not attempt to verify that you have passed the actual mean as xbar. Using arbitrary values for xbar can lead to invalid or impossible results.
Decimal and Fraction values are supported:
Note
This is the sample variance s² with Bessel’s correction, also known as variance with N-1 degrees of freedom. Provided that the data points are representative (e.g. independent and identically distributed), the result should be an unbiased estimate of the true population variance.
If you somehow know the actual population mean μ you should pass it to the pvariance() function as the mu parameter to get the variance of a sample.


Must be raised by __anext__() method of an asynchronous iterator object to stop the iteration.
New in version 3.5.


Raised by built-in function next() and an iterator’s __next__() method to signal that there are no further items produced by the iterator.
The exception object has a single attribute value, which is given as an argument when constructing the exception, and defaults to None.
When a generator or coroutine function returns, a new StopIteration instance is raised, and the value returned by the function is used as the value parameter to the constructor of the exception.
If a generator code directly or indirectly raises StopIteration, it is converted into a RuntimeError (retaining the StopIteration as the new exception’s cause).
Changed in version 3.3: Added value attribute and the ability for generator functions to use it to return a value.
Changed in version 3.5: Introduced the RuntimeError transformation via from __future__ import generator_stop, see PEP 479.
Changed in version 3.7: Enable PEP 479 for all code by default: a StopIteration error raised in a generator is transformed into a RuntimeError.


Return a str version of object. See str() for details.
str is the built-in string class. For general information about strings, see Text Sequence Type — str.


Return a string version of object. If object is not provided, returns the empty string. Otherwise, the behavior of str() depends on whether encoding or errors is given, as follows.
If neither encoding nor errors is given, str(object) returns object.__str__(), 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 __str__() method, then str() falls back to returning repr(object).
If at least one of encoding or errors is given, object should be a bytes-like object (e.g. bytes or bytearray). In this case, if object is a bytes (or bytearray) object, then str(bytes, encoding, errors) is equivalent to bytes.decode(encoding, errors). Otherwise, the bytes object underlying the buffer object is obtained before calling bytes.decode(). See Binary Sequence Types — bytes, bytearray, memoryview and Buffer Protocol for information on buffer objects.
Passing a bytes object to str() without the encoding or errors arguments falls under the first case of returning the informal string representation (see also the -b command-line option to Python). For example:
For more information on the str class and its methods, see Text Sequence Type — str and the String Methods section below. To output formatted strings, see the Formatted string literals and Format String Syntax sections. In addition, see the Text Processing Services section.


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 "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss".
The casefolding algorithm is described in section 3.13 of the Unicode Standard.
New in version 3.3.


Return centered in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).


Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.


Return an encoded version of the string as a bytes object. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings.
By default, the errors argument is not checked for best performances, but only used at the first encoding error. Enable the Python Development Mode, or use a debug build to check errors.
Changed in version 3.1: Support for keyword arguments added.
Changed in version 3.9: The errors is now checked in development mode and in debug mode.


Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.


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 (\t), 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 (\n) or return (\r), 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 the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.
Note
The find() method should be used only if you need to know the position of sub. To check if sub is a substring or not, use the in operator:


Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.
See Format String Syntax for a description of the various formatting options that can be specified in format strings.
Note
When formatting a number (int, float, complex, decimal.Decimal and subclasses) with the n type (ex: '{:n}'.format(1234)), the function temporarily sets the LC_CTYPE locale to the LC_NUMERIC locale to decode decimal_point and thousands_sep fields of localeconv() if they are non-ASCII or longer than 1 byte, and the LC_NUMERIC locale is different than the LC_CTYPE locale. This temporary change affects other threads.
Changed in version 3.7: When formatting a number with the n type, the function sets temporarily the LC_CTYPE locale to the LC_NUMERIC locale in some cases.


Similar to str.format(**mapping), except that mapping is used directly and not copied to a dict. This is useful if for example mapping is a dict subclass:
New in version 3.2.


Like find(), but raise ValueError when the substring is not found.


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


Return True if all characters in the string are alphabetic and there is at least one character, False otherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i.e., those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the “Alphabetic” property defined in the Unicode Standard.


Return True if the string is empty or all characters in the string are ASCII, False otherwise. ASCII characters have code points in the range U+0000-U+007F.
New in version 3.7.


Return True if all characters in the string are decimal characters and there is at least one character, False otherwise. Decimal characters are those that can be used to form numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category “Nd”.


Return True if all characters in the string are digits and there is at least one character, False otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.


Return True if the string is a valid identifier according to the language definition, section Identifiers and keywords.
Call keyword.iskeyword() to test whether string s is a reserved identifier, such as def and class.
Example:


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


Return True if all characters in the string are numeric characters, and there is at least one character, False otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.


Return True if all characters in the string are printable or the string is empty, False 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 repr() is invoked on a string. It has no bearing on the handling of strings written to sys.stdout or sys.stderr.)


Return True if there are only whitespace characters in the string and there is at least one character, False otherwise.
A character is whitespace if in the Unicode character database (see unicodedata), either its general category is Zs (“Separator, space”), or its bidirectional class is one of WS, B, or S.


Return True if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise.


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


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


Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).


Return a copy of the string with all the cased characters 4 converted to lowercase.
The lowercasing algorithm used is described in section 3.13 of the Unicode Standard.


Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped:
See str.removeprefix() for a method that will remove a single prefix string rather than all of a set of characters. For example:


This static method returns a translation table usable for str.translate().
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 None. 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 None 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:
New in version 3.9.


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:
New in version 3.9.


Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.


Return the highest index in the string where substring sub is found, such that sub is contained within s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.


Like rfind() but raises ValueError when the substring sub is not found.


Return the string right justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).


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 words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any whitespace string is a separator. Except for splitting from the right, rsplit() behaves like split() which is described in detail below.


Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped:
See str.removesuffix() for a method that will remove a single suffix string rather than all of a set of characters. For example:


Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).
If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns [''].
For example:
If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].
For example:


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.
Representation
Description
\n
Line Feed
\r
Carriage Return
\r\n
Carriage Return + Line Feed
\v or \x0b
Line Tabulation
\f or \x0c
Form Feed
\x1c
File Separator
\x1d
Group Separator
\x1e
Record Separator
\x85
Next Line (C1 Control Code)
\u2028
Line Separator
\u2029
Paragraph Separator
Changed in version 3.2: \v and \f added to list of line boundaries.
For example:
Unlike split() 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, split('\n') gives:


Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.


Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:
The outermost leading and trailing chars argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in chars. A similar action takes place on the trailing end. For example:


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


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:
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 __getitem__(), typically a mapping or sequence. 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 None, to delete the character from the return string; or raise a LookupError exception, to map the character to itself.
You can use str.maketrans() to create a translation map from character-to-character mappings in different formats.
See also the codecs module for a more flexible approach to custom character mappings.


Return a copy of the string with all the cased characters 4 converted to uppercase. Note that s.upper().isupper() might be False if s 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 of the Unicode Standard.


Return a copy of the string left filled with ASCII '0' 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 len(s).
For example:


Source code: Lib/asyncio/streams.py
Streams are high-level async/await-ready primitives to work with network connections. Streams allow sending and receiving data without using callbacks or low-level protocols and transports.
Here is an example of a TCP echo client written using asyncio streams:
See also the Examples section below.
The following top-level asyncio functions can be used to create and work with streams:
Establish a network connection and return a pair of (reader, writer) objects.
The returned reader and writer objects are instances of StreamReader and StreamWriter classes.
The loop argument is optional and can always be determined automatically when this function is awaited from a coroutine.
limit determines the buffer size limit used by the returned StreamReader instance. By default the limit is set to 64 KiB.
The rest of the arguments are passed directly to loop.create_connection().
New in version 3.7: The ssl_handshake_timeout parameter.
Start a socket server.
The client_connected_cb callback is called whenever a new client connection is established. It receives a (reader, writer) pair as two arguments, instances of the StreamReader and StreamWriter classes.
client_connected_cb can be a plain callable or a coroutine function; if it is a coroutine function, it will be automatically scheduled as a Task.
The loop argument is optional and can always be determined automatically when this method is awaited from a coroutine.
limit determines the buffer size limit used by the returned StreamReader instance. By default the limit is set to 64 KiB.
The rest of the arguments are passed directly to loop.create_server().
New in version 3.7: The ssl_handshake_timeout and start_serving parameters.
Establish a Unix socket connection and return a pair of (reader, writer).
Similar to open_connection() but operates on Unix sockets.
See also the documentation of loop.create_unix_connection().
Availability: Unix.
New in version 3.7: The ssl_handshake_timeout parameter.
Changed in version 3.7: The path parameter can now be a path-like object
Start a Unix socket server.
Similar to start_server() but works with Unix sockets.
See also the documentation of loop.create_unix_server().
Availability: Unix.
New in version 3.7: The ssl_handshake_timeout and start_serving parameters.
Changed in version 3.7: The path parameter can now be a path-like object.
Represents a reader object that provides APIs to read data from the IO stream.
It is not recommended to instantiate StreamReader objects directly; use open_connection() and start_server() instead.
Read up to n bytes. If n is not provided, or set to -1, read until EOF and return all read bytes.
If EOF was received and the internal buffer is empty, return an empty bytes object.
Read one line, where “line” is a sequence of bytes ending with \n.
If EOF is received and \n was not found, the method returns partially read data.
If EOF is received and the internal buffer is empty, return an empty bytes object.
Read exactly n bytes.
Raise an IncompleteReadError if EOF is reached before n can be read. Use the IncompleteReadError.partial attribute to get the partially read data.
Read data from the stream until separator is found.
On success, the data and separator will be removed from the internal buffer (consumed). Returned data will include the separator at the end.
If the amount of data read exceeds the configured stream limit, a LimitOverrunError exception is raised, and the data is left in the internal buffer and can be read again.
If EOF is reached before the complete separator is found, an IncompleteReadError exception is raised, and the internal buffer is reset. The IncompleteReadError.partial attribute may contain a portion of the separator.
New in version 3.5.2.
Return True if the buffer is empty and feed_eof() was called.
Represents a writer object that provides APIs to write data to the IO stream.
It is not recommended to instantiate StreamWriter objects directly; use open_connection() and start_server() instead.
The method attempts to write the data to the underlying socket immediately. If that fails, the data is queued in an internal write buffer until it can be sent.
The method should be used along with the drain() method:
The method writes a list (or any iterable) of bytes to the underlying socket immediately. If that fails, the data is queued in an internal write buffer until it can be sent.
The method should be used along with the drain() method:
The method closes the stream and the underlying socket.
The method should be used along with the wait_closed() method:
Return True if the underlying transport supports the write_eof() method, False otherwise.
Close the write end of the stream after the buffered write data is flushed.
Return the underlying asyncio transport.
Access optional transport information; see BaseTransport.get_extra_info() for details.
Wait until it is appropriate to resume writing to the stream. Example:
This is a flow control method that interacts with the underlying IO write buffer. When the size of the buffer reaches the high watermark, drain() blocks until the size of the buffer is drained down to the low watermark and writing can be resumed. When there is nothing to wait for, the drain() returns immediately.
Return True if the stream is closed or in the process of being closed.
New in version 3.7.
Wait until the stream is closed.
Should be called after close() to wait until the underlying connection is closed.
New in version 3.7.
TCP echo client using the asyncio.open_connection() function:
See also
The TCP echo client protocol example uses the low-level loop.create_connection() method.
TCP echo server using the asyncio.start_server() function:
See also
The TCP echo server protocol example uses the loop.create_server() method.
Simple example querying HTTP headers of the URL passed on the command line:
Usage:
or with HTTPS:
Coroutine waiting until a socket receives data using the open_connection() function:
See also
The register an open socket to wait for data using a protocol example uses a low-level protocol and the loop.create_connection() method.
The watch a file descriptor for read events example uses the low-level loop.add_reader() method to watch a file descriptor.