_id
stringlengths
5
9
text
stringlengths
5
385k
title
stringclasses
1 value
doc_1300
Raises an AssertionError if two objects are not equal up to desired precision. Note It is recommended to use one of assert_allclose, assert_array_almost_equal_nulp or assert_array_max_ulp instead of this function for more consistent floating point comparisons. The test verifies identical shapes and that the elements of actual and desired satisfy. abs(desired-actual) < 1.5 * 10**(-decimal) That is a looser test than originally documented, but agrees with what the actual implementation did up to rounding vagaries. An exception is raised at shape mismatch or conflicting values. In contrast to the standard usage in numpy, NaNs are compared like numbers, no assertion is raised if both objects have NaNs in the same positions. Parameters xarray_like The actual object to check. yarray_like The desired, expected object. decimalint, optional Desired precision, default is 6. err_msgstr, optional The error message to be printed in case of failure. verbosebool, optional If True, the conflicting values are appended to the error message. Raises AssertionError If actual and desired are not equal up to specified precision. See also assert_allclose Compare two array_like objects for equality with desired relative and/or absolute precision. assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal Examples the first assert does not raise an exception >>> np.testing.assert_array_almost_equal([1.0,2.333,np.nan], ... [1.0,2.333,np.nan]) >>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan], ... [1.0,2.33339,np.nan], decimal=5) Traceback (most recent call last): ... AssertionError: Arrays are not almost equal to 5 decimals Mismatched elements: 1 / 3 (33.3%) Max absolute difference: 6.e-05 Max relative difference: 2.57136612e-05 x: array([1. , 2.33333, nan]) y: array([1. , 2.33339, nan]) >>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan], ... [1.0,2.33333, 5], decimal=5) Traceback (most recent call last): ... AssertionError: Arrays are not almost equal to 5 decimals x and y nan location mismatch: x: array([1. , 2.33333, nan]) y: array([1. , 2.33333, 5. ])
doc_1301
Returns the digit value assigned to the character chr as integer. If no such value is defined, default is returned, or, if not given, ValueError is raised.
doc_1302
os.O_WRONLY os.O_RDWR os.O_APPEND os.O_CREAT os.O_EXCL os.O_TRUNC The above constants are available on Unix and Windows.
doc_1303
See Migration guide for more details. tf.compat.v1.raw_ops.ScatterUpdate tf.raw_ops.ScatterUpdate( ref, indices, updates, use_locking=True, name=None ) This operation computes # Scalar indices ref[indices, ...] = updates[...] # Vector indices (for each i) ref[indices[i], ...] = updates[i, ...] # High rank indices (for each i, ..., j) ref[indices[i, ..., j], ...] = updates[i, ..., j, ...] This operation outputs ref after the update is done. This makes it easier to chain operations that need to use the reset value. If values in ref is to be updated more than once, because there are duplicate entries in indices, the order at which the updates happen for each value is undefined. Requires updates.shape = indices.shape + ref.shape[1:] or updates.shape = []. See also tf.batch_scatter_update and tf.scatter_nd_update. Args ref A mutable Tensor. Should be from a Variable node. indices A Tensor. Must be one of the following types: int32, int64. A tensor of indices into the first dimension of ref. updates A Tensor. Must have the same type as ref. A tensor of updated values to store in ref. use_locking An optional bool. Defaults to True. If True, the assignment will be protected by a lock; otherwise the behavior is undefined, but may exhibit less contention. name A name for the operation (optional). Returns A mutable Tensor. Has the same type as ref.
doc_1304
Takes an arbitrary Python function and returns a NumPy ufunc. Can be used, for example, to add broadcasting to a built-in Python function (see Examples section). Parameters funcPython function object An arbitrary Python function. ninint The number of input arguments. noutint The number of objects returned by func. identityobject, optional The value to use for the identity attribute of the resulting object. If specified, this is equivalent to setting the underlying C identity field to PyUFunc_IdentityValue. If omitted, the identity is set to PyUFunc_None. Note that this is _not_ equivalent to setting the identity to None, which implies the operation is reorderable. Returns outufunc Returns a NumPy universal function (ufunc) object. See also vectorize Evaluates pyfunc over input arrays using broadcasting rules of numpy. Notes The returned ufunc always returns PyObject arrays. Examples Use frompyfunc to add broadcasting to the Python function oct: >>> oct_array = np.frompyfunc(oct, 1, 1) >>> oct_array(np.array((10, 30, 100))) array(['0o12', '0o36', '0o144'], dtype=object) >>> np.array((oct(10), oct(30), oct(100))) # for comparison array(['0o12', '0o36', '0o144'], dtype='<U5')
doc_1305
Set the yaxis' tick locations and optionally labels. If necessary, the view limits of the Axis are expanded so that all given ticks are visible. Parameters tickslist of floats List of tick locations. labelslist of str, optional List of tick labels. If not set, the labels show the data value. minorbool, default: False If False, set the major ticks; if True, the minor ticks. **kwargs Text properties for the labels. These take effect only if you pass labels. In other cases, please use tick_params. Notes The mandatory expansion of the view limits is an intentional design choice to prevent the surprise of a non-visible tick. If you need other limits, you should set the limits explicitly after setting the ticks. Examples using matplotlib.axes.Axes.set_yticks Bar Label Demo Horizontal bar chart Broken Barh Psd Demo Creating annotated heatmaps Rendering math equations using TeX Programmatically controlling subplot adjustment Make Room For Ylabel Using Axesgrid Scatter Histogram (Locatable Axes) Ticklabel alignment Ticklabel direction Bachelor's degrees by gender Integral as the area under a curve Shaded & power normalized rendering XKCD Rain simulation MATPLOTLIB UNCHAINED Frontpage 3D example Frontpage contour example Frontpage histogram example Frontpage plot example Create 2D bar graphs in different planes MRI With EEG SkewT-logP diagram: using transforms and custom projections Custom spine bounds
doc_1306
Initialize the artist inspector with an Artist or an iterable of Artists. If an iterable is used, we assume it is a homogeneous sequence (all Artists are of the same type) and it is your responsibility to make sure this is so.
doc_1307
Return the group id.
doc_1308
Returns the diagonal of the kernel k(X, X). The result of this method is identical to np.diag(self(X)); however, it can be evaluated more efficiently since only the diagonal is evaluated. Parameters Xndarray of shape (n_samples_X, n_features) Left argument of the returned kernel k(X, Y). Returns K_diagndarray of shape (n_samples_X,) Diagonal of kernel k(X, X).
doc_1309
The Last-Modified entity-header field indicates the date and time at which the origin server believes the variant was last modified. Changed in version 2.0: The datetime object is timezone-aware.
doc_1310
Is True if gradients need to be computed for this Tensor, False otherwise. Note The fact that gradients need to be computed for a Tensor do not mean that the grad attribute will be populated, see is_leaf for more details.
doc_1311
Set the host and the port for HTTP Connect Tunnelling. This allows running the connection through a proxy server. The host and port arguments specify the endpoint of the tunneled connection (i.e. the address included in the CONNECT request, not the address of the proxy server). The headers argument should be a mapping of extra HTTP headers to send with the CONNECT request. For example, to tunnel through a HTTPS proxy server running locally on port 8080, we would pass the address of the proxy to the HTTPSConnection constructor, and the address of the host that we eventually want to reach to the set_tunnel() method: >>> import http.client >>> conn = http.client.HTTPSConnection("localhost", 8080) >>> conn.set_tunnel("www.python.org") >>> conn.request("HEAD","/index.html") New in version 3.2.
doc_1312
Return whether units are set on any axis.
doc_1313
Create an ellipoid kernel for restoration.rolling_ball. Parameters shapearraylike Length of the principal axis of the ellipsoid (excluding the intensity axis). The kernel needs to have the same dimensionality as the image it will be applied to. intensityint Length of the intensity axis of the ellipsoid. Returns kernelndarray The kernel containing the surface intensity of the top half of the ellipsoid. See also rolling_ball
doc_1314
Initialize the internal data structures. If given, files must be a sequence of file names which should be used to augment the default type map. If omitted, the file names to use are taken from knownfiles; on Windows, the current registry settings are loaded. Each file named in files or knownfiles takes precedence over those named before it. Calling init() repeatedly is allowed. Specifying an empty list for files will prevent the system defaults from being applied: only the well-known values will be present from a built-in list. If files is None the internal data structure is completely rebuilt to its initial default value. This is a stable operation and will produce the same results when called multiple times. Changed in version 3.2: Previously, Windows registry settings were ignored.
doc_1315
Check if the Index only consists of booleans. Returns bool Whether or not the Index only consists of booleans. See also is_integer Check if the Index only consists of integers. is_floating Check if the Index is a floating type. is_numeric Check if the Index only consists of numeric data. is_object Check if the Index is of the object dtype. is_categorical Check if the Index holds categorical data. is_interval Check if the Index holds Interval objects. is_mixed Check if the Index holds data with mixed data types. Examples >>> idx = pd.Index([True, False, True]) >>> idx.is_boolean() True >>> idx = pd.Index(["True", "False", "True"]) >>> idx.is_boolean() False >>> idx = pd.Index([True, False, "True"]) >>> idx.is_boolean() False
doc_1316
See Migration guide for more details. tf.compat.v1.keras.layers.DepthwiseConv2D tf.keras.layers.DepthwiseConv2D( kernel_size, strides=(1, 1), padding='valid', depth_multiplier=1, data_format=None, dilation_rate=(1, 1), activation=None, use_bias=True, depthwise_initializer='glorot_uniform', bias_initializer='zeros', depthwise_regularizer=None, bias_regularizer=None, activity_regularizer=None, depthwise_constraint=None, bias_constraint=None, **kwargs ) Depthwise Separable convolutions consist of performing just the first step in a depthwise spatial convolution (which acts on each input channel separately). The depth_multiplier argument controls how many output channels are generated per input channel in the depthwise step. Arguments kernel_size An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides An integer or tuple/list of 2 integers, specifying the strides of the convolution along the height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any dilation_rate value != 1. padding one of 'valid' or 'same' (case-insensitive). "valid" means no padding. "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. depth_multiplier The number of depthwise convolution output channels for each input channel. The total number of depthwise convolution output channels will be equal to filters_in * depth_multiplier. data_format A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height, width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be 'channels_last'. dilation_rate An integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Currently, specifying any dilation_rate value != 1 is incompatible with specifying any strides value != 1. activation Activation function to use. If you don't specify anything, no activation is applied ( see keras.activations). use_bias Boolean, whether the layer uses a bias vector. depthwise_initializer Initializer for the depthwise kernel matrix ( see keras.initializers). bias_initializer Initializer for the bias vector ( see keras.initializers). depthwise_regularizer Regularizer function applied to the depthwise kernel matrix (see keras.regularizers). bias_regularizer Regularizer function applied to the bias vector ( see keras.regularizers). activity_regularizer Regularizer function applied to the output of the layer (its 'activation') ( see keras.regularizers). depthwise_constraint Constraint function applied to the depthwise kernel matrix ( see keras.constraints). bias_constraint Constraint function applied to the bias vector ( see keras.constraints). Input shape: 4D tensor with shape: [batch_size, channels, rows, cols] if data_format='channels_first' or 4D tensor with shape: [batch_size, rows, cols, channels] if data_format='channels_last'. Output shape: 4D tensor with shape: [batch_size, filters, new_rows, new_cols] if data_format='channels_first' or 4D tensor with shape: [batch_size, new_rows, new_cols, filters] if data_format='channels_last'. rows and cols values might have changed due to padding. Returns A tensor of rank 4 representing activation(depthwiseconv2d(inputs, kernel) + bias). Raises ValueError if padding is "causal". ValueError when both strides > 1 and dilation_rate > 1.
doc_1317
pygame module for audio cdrom control The cdrom module manages the CD and DVD drives on a computer. It can also control the playback of audio CDs. This module needs to be initialized before it can do anything. Each CD object you create represents a cdrom drive and must also be initialized individually before it can do most things. pygame.cdrom.init() initialize the cdrom module init() -> None Initialize the cdrom module. This will scan the system for all CD devices. The module must be initialized before any other functions will work. This automatically happens when you call pygame.init(). It is safe to call this function more than once. pygame.cdrom.quit() uninitialize the cdrom module quit() -> None Uninitialize the cdrom module. After you call this any existing CD objects will no longer work. It is safe to call this function more than once. pygame.cdrom.get_init() true if the cdrom module is initialized get_init() -> bool Test if the cdrom module is initialized or not. This is different than the CD.init() since each drive must also be initialized individually. pygame.cdrom.get_count() number of cd drives on the system get_count() -> count Return the number of cd drives on the system. When you create CD objects you need to pass an integer id that must be lower than this count. The count will be 0 if there are no drives on the system. pygame.cdrom.CD class to manage a cdrom drive CD(id) -> CD You can create a CD object for each cdrom on the system. Use pygame.cdrom.get_count() to determine how many drives actually exist. The id argument is an integer of the drive, starting at zero. The CD object is not initialized, you can only call CD.get_id() and CD.get_name() on an uninitialized drive. It is safe to create multiple CD objects for the same drive, they will all cooperate normally. init() initialize a cdrom drive for use init() -> None Initialize the cdrom drive for use. The drive must be initialized for most CD methods to work. Even if the rest of pygame has been initialized. There may be a brief pause while the drive is initialized. Avoid CD.init() if the program should not stop for a second or two. quit() uninitialize a cdrom drive for use quit() -> None Uninitialize a drive for use. Call this when your program will not be accessing the drive for awhile. get_init() true if this cd device initialized get_init() -> bool Test if this CDROM device is initialized. This is different than the pygame.cdrom.init() since each drive must also be initialized individually. play() start playing audio play(track, start=None, end=None) -> None Playback audio from an audio cdrom in the drive. Besides the track number argument, you can also pass a starting and ending time for playback. The start and end time are in seconds, and can limit the section of an audio track played. If you pass a start time but no end, the audio will play to the end of the track. If you pass a start time and 'None' for the end time, the audio will play to the end of the entire disc. See the CD.get_numtracks() and CD.get_track_audio() to find tracks to playback. Note, track 0 is the first track on the CD. Track numbers start at zero. stop() stop audio playback stop() -> None Stops playback of audio from the cdrom. This will also lose the current playback position. This method does nothing if the drive isn't already playing audio. pause() temporarily stop audio playback pause() -> None Temporarily stop audio playback on the CD. The playback can be resumed at the same point with the CD.resume() method. If the CD is not playing this method does nothing. Note, track 0 is the first track on the CD. Track numbers start at zero. resume() unpause audio playback resume() -> None Unpause a paused CD. If the CD is not paused or already playing, this method does nothing. eject() eject or open the cdrom drive eject() -> None This will open the cdrom drive and eject the cdrom. If the drive is playing or paused it will be stopped. get_id() the index of the cdrom drive get_id() -> id Returns the integer id that was used to create the CD instance. This method can work on an uninitialized CD. get_name() the system name of the cdrom drive get_name() -> name Return the string name of the drive. This is the system name used to represent the drive. It is often the drive letter or device name. This method can work on an uninitialized CD. get_busy() true if the drive is playing audio get_busy() -> bool Returns True if the drive busy playing back audio. get_paused() true if the drive is paused get_paused() -> bool Returns True if the drive is currently paused. get_current() the current audio playback position get_current() -> track, seconds Returns both the current track and time of that track. This method works when the drive is either playing or paused. Note, track 0 is the first track on the CD. Track numbers start at zero. get_empty() False if a cdrom is in the drive get_empty() -> bool Return False if there is a cdrom currently in the drive. If the drive is empty this will return True. get_numtracks() the number of tracks on the cdrom get_numtracks() -> count Return the number of tracks on the cdrom in the drive. This will return zero of the drive is empty or has no tracks. get_track_audio() true if the cdrom track has audio data get_track_audio(track) -> bool Determine if a track on a cdrom contains audio data. You can also call CD.num_tracks() and CD.get_all() to determine more information about the cdrom. Note, track 0 is the first track on the CD. Track numbers start at zero. get_all() get all track information get_all() -> [(audio, start, end, length), ...] Return a list with information for every track on the cdrom. The information consists of a tuple with four values. The audio value is True if the track contains audio data. The start, end, and length values are floating point numbers in seconds. Start and end represent absolute times on the entire disc. get_track_start() start time of a cdrom track get_track_start(track) -> seconds Return the absolute time in seconds where at start of the cdrom track. Note, track 0 is the first track on the CD. Track numbers start at zero. get_track_length() length of a cdrom track get_track_length(track) -> seconds Return a floating point value in seconds of the length of the cdrom track. Note, track 0 is the first track on the CD. Track numbers start at zero.
doc_1318
Chan-Vese segmentation algorithm. Active contour model by evolving a level set. Can be used to segment objects without clearly defined boundaries. Parameters image(M, N) ndarray Grayscale image to be segmented. mufloat, optional ‘edge length’ weight parameter. Higher mu values will produce a ‘round’ edge, while values closer to zero will detect smaller objects. lambda1float, optional ‘difference from average’ weight parameter for the output region with value ‘True’. If it is lower than lambda2, this region will have a larger range of values than the other. lambda2float, optional ‘difference from average’ weight parameter for the output region with value ‘False’. If it is lower than lambda1, this region will have a larger range of values than the other. tolfloat, positive, optional Level set variation tolerance between iterations. If the L2 norm difference between the level sets of successive iterations normalized by the area of the image is below this value, the algorithm will assume that the solution was reached. max_iteruint, optional Maximum number of iterations allowed before the algorithm interrupts itself. dtfloat, optional A multiplication factor applied at calculations for each step, serves to accelerate the algorithm. While higher values may speed up the algorithm, they may also lead to convergence problems. init_level_setstr or (M, N) ndarray, optional Defines the starting level set used by the algorithm. If a string is inputted, a level set that matches the image size will automatically be generated. Alternatively, it is possible to define a custom level set, which should be an array of float values, with the same shape as ‘image’. Accepted string values are as follows. ‘checkerboard’ the starting level set is defined as sin(x/5*pi)*sin(y/5*pi), where x and y are pixel coordinates. This level set has fast convergence, but may fail to detect implicit edges. ‘disk’ the starting level set is defined as the opposite of the distance from the center of the image minus half of the minimum value between image width and image height. This is somewhat slower, but is more likely to properly detect implicit edges. ‘small disk’ the starting level set is defined as the opposite of the distance from the center of the image minus a quarter of the minimum value between image width and image height. extended_outputbool, optional If set to True, the return value will be a tuple containing the three return values (see below). If set to False which is the default value, only the ‘segmentation’ array will be returned. Returns segmentation(M, N) ndarray, bool Segmentation produced by the algorithm. phi(M, N) ndarray of floats Final level set computed by the algorithm. energieslist of floats Shows the evolution of the ‘energy’ for each step of the algorithm. This should allow to check whether the algorithm converged. Notes The Chan-Vese Algorithm is designed to segment objects without clearly defined boundaries. This algorithm is based on level sets that are evolved iteratively to minimize an energy, which is defined by weighted values corresponding to the sum of differences intensity from the average value outside the segmented region, the sum of differences from the average value inside the segmented region, and a term which is dependent on the length of the boundary of the segmented region. This algorithm was first proposed by Tony Chan and Luminita Vese, in a publication entitled “An Active Contour Model Without Edges” [1]. This implementation of the algorithm is somewhat simplified in the sense that the area factor ‘nu’ described in the original paper is not implemented, and is only suitable for grayscale images. Typical values for lambda1 and lambda2 are 1. If the ‘background’ is very different from the segmented object in terms of distribution (for example, a uniform black image with figures of varying intensity), then these values should be different from each other. Typical values for mu are between 0 and 1, though higher values can be used when dealing with shapes with very ill-defined contours. The ‘energy’ which this algorithm tries to minimize is defined as the sum of the differences from the average within the region squared and weighed by the ‘lambda’ factors to which is added the length of the contour multiplied by the ‘mu’ factor. Supports 2D grayscale images only, and does not implement the area term described in the original article. References 1 An Active Contour Model without Edges, Tony Chan and Luminita Vese, Scale-Space Theories in Computer Vision, 1999, DOI:10.1007/3-540-48236-9_13 2 Chan-Vese Segmentation, Pascal Getreuer Image Processing On Line, 2 (2012), pp. 214-224, DOI:10.5201/ipol.2012.g-cv 3 The Chan-Vese Algorithm - Project Report, Rami Cohen, 2011 arXiv:1107.2782
doc_1319
See Migration guide for more details. tf.compat.v1.raw_ops.ParseSingleExample tf.raw_ops.ParseSingleExample( serialized, dense_defaults, num_sparse, sparse_keys, dense_keys, sparse_types, dense_shapes, name=None ) Args serialized A Tensor of type string. A vector containing a batch of binary serialized Example protos. dense_defaults A list of Tensor objects with types from: float32, int64, string. A list of Tensors (some may be empty), whose length matches the length of dense_keys. dense_defaults[j] provides default values when the example's feature_map lacks dense_key[j]. If an empty Tensor is provided for dense_defaults[j], then the Feature dense_keys[j] is required. The input type is inferred from dense_defaults[j], even when it's empty. If dense_defaults[j] is not empty, and dense_shapes[j] is fully defined, then the shape of dense_defaults[j] must match that of dense_shapes[j]. If dense_shapes[j] has an undefined major dimension (variable strides dense feature), dense_defaults[j] must contain a single element: the padding element. num_sparse An int that is >= 0. The number of sparse features to be parsed from the example. This must match the lengths of sparse_keys and sparse_types. sparse_keys A list of strings. A list of num_sparse strings. The keys expected in the Examples' features associated with sparse values. dense_keys A list of strings. The keys expected in the Examples' features associated with dense values. sparse_types A list of tf.DTypes from: tf.float32, tf.int64, tf.string. A list of num_sparse types; the data types of data in each Feature given in sparse_keys. Currently the ParseSingleExample op supports DT_FLOAT (FloatList), DT_INT64 (Int64List), and DT_STRING (BytesList). dense_shapes A list of shapes (each a tf.TensorShape or list of ints). The shapes of data in each Feature given in dense_keys. The length of this list must match the length of dense_keys. The number of elements in the Feature corresponding to dense_key[j] must always equal dense_shapes[j].NumEntries(). If dense_shapes[j] == (D0, D1, ..., DN) then the shape of output Tensor dense_values[j] will be (D0, D1, ..., DN): In the case dense_shapes[j] = (-1, D1, ..., DN), the shape of the output Tensor dense_values[j] will be (M, D1, .., DN), where M is the number of blocks of elements of length D1 * .... * DN, in the input. name A name for the operation (optional). Returns A tuple of Tensor objects (sparse_indices, sparse_values, sparse_shapes, dense_values). sparse_indices A list of num_sparse Tensor objects with type int64. sparse_values A list of Tensor objects of type sparse_types. sparse_shapes A list of num_sparse Tensor objects with type int64. dense_values A list of Tensor objects. Has the same type as dense_defaults.
doc_1320
Creates a unique constraint in the database.
doc_1321
In-place version of bitwise_and()
doc_1322
returns the squared Euclidean magnitude of the vector. magnitude_squared() -> float calculates the magnitude of the vector which follows from the theorem: vec.magnitude_squared() == vec.x**2 + vec.y**2 + vec.z**2. This is faster than vec.magnitude() because it avoids the square root.
doc_1323
Return self%value.
doc_1324
Return a writer object responsible for converting the user’s data into delimited strings on the given file-like object. csvfile can be any object with a write() method. If csvfile is a file object, it should be opened with newline='' 1. An optional dialect parameter can be given which is used to define a set of parameters specific to a particular CSV dialect. It may be an instance of a subclass of the Dialect class or one of the strings returned by the list_dialects() function. The other optional fmtparams keyword arguments can be given to override individual formatting parameters in the current dialect. For full details about the dialect and formatting parameters, see section Dialects and Formatting Parameters. To make it as easy as possible to interface with modules which implement the DB API, the value None is written as the empty string. While this isn’t a reversible transformation, it makes it easier to dump SQL NULL data values to CSV files without preprocessing the data returned from a cursor.fetch* call. All other non-string data are stringified with str() before being written. A short usage example: import csv with open('eggs.csv', 'w', newline='') as csvfile: spamwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) spamwriter.writerow(['Spam'] * 5 + ['Baked Beans']) spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
doc_1325
Signed integer type, compatible with C int. Character code 'i' Alias on this platform (Linux x86_64) numpy.int32: 32-bit signed integer (-2_147_483_648 to 2_147_483_647).
doc_1326
A decorator to indicate to type checkers that the decorated method cannot be overridden, and the decorated class cannot be subclassed. For example: class Base: @final def done(self) -> None: ... class Sub(Base): def done(self) -> None: # Error reported by type checker ... @final class Leaf: ... class Other(Leaf): # Error reported by type checker ... There is no runtime checking of these properties. See PEP 591 for more details. New in version 3.8.
doc_1327
Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values.
doc_1328
tf.squeeze( input, axis=None, name=None ) Given a tensor input, this operation returns a tensor of the same type with all dimensions of size 1 removed. If you don't want to remove all size 1 dimensions, you can remove specific size 1 dimensions by specifying axis. For example: # 't' is a tensor of shape [1, 2, 1, 3, 1, 1] tf.shape(tf.squeeze(t)) # [2, 3] Or, to remove specific size 1 dimensions: # 't' is a tensor of shape [1, 2, 1, 3, 1, 1] tf.shape(tf.squeeze(t, [2, 4])) # [1, 2, 3, 1] Unlike the older op tf.compat.v1.squeeze, this op does not accept a deprecated squeeze_dims argument. Note: if input is a tf.RaggedTensor, then this operation takes O(N) time, where N is the number of elements in the squeezed dimensions. Args input A Tensor. The input to squeeze. axis An optional list of ints. Defaults to []. If specified, only squeezes the dimensions listed. The dimension index starts at 0. It is an error to squeeze a dimension that is not 1. Must be in the range [-rank(input), rank(input)). Must be specified if input is a RaggedTensor. name A name for the operation (optional). Returns A Tensor. Has the same type as input. Contains the same data as input, but has one or more dimensions of size 1 removed. Raises ValueError The input cannot be converted to a tensor, or the specified axis cannot be squeezed.
doc_1329
Test whether the artist contains the mouse event. Parameters mouseeventmatplotlib.backend_bases.MouseEvent Returns containsbool Whether any values are within the radius. detailsdict An artist-specific dictionary of details of the event context, such as which points are contained in the pick radius. See the individual Artist subclasses for details.
doc_1330
Applies a softmax followed by a logarithm. While mathematically equivalent to log(softmax(x)), doing these two operations separately is slower, and numerically unstable. This function uses an alternative formulation to compute the output and gradient correctly. See LogSoftmax for more details. Parameters input (Tensor) – input dim (int) – A dimension along which log_softmax will be computed. dtype (torch.dtype, optional) – the desired data type of returned tensor. If specified, the input tensor is casted to dtype before the operation is performed. This is useful for preventing data type overflows. Default: None.
doc_1331
Returns a tensor where each sub-tensor of input along dimension dim is normalized such that the p-norm of the sub-tensor is lower than the value maxnorm Note If the norm of a row is lower than maxnorm, the row is unchanged Parameters input (Tensor) – the input tensor. p (float) – the power for the norm computation dim (int) – the dimension to slice over to get the sub-tensors maxnorm (float) – the maximum norm to keep each sub-tensor under Keyword Arguments out (Tensor, optional) – the output tensor. Example: >>> x = torch.ones(3, 3) >>> x[1].fill_(2) tensor([ 2., 2., 2.]) >>> x[2].fill_(3) tensor([ 3., 3., 3.]) >>> x tensor([[ 1., 1., 1.], [ 2., 2., 2.], [ 3., 3., 3.]]) >>> torch.renorm(x, 1, 0, 5) tensor([[ 1.0000, 1.0000, 1.0000], [ 1.6667, 1.6667, 1.6667], [ 1.6667, 1.6667, 1.6667]])
doc_1332
Reduce X to the selected features and then predict using the underlying estimator. Parameters Xarray of shape [n_samples, n_features] The input samples. Returns yarray of shape [n_samples] The predicted target values.
doc_1333
Compute the roots of a Legendre series. Return the roots (a.k.a. “zeros”) of the polynomial \[p(x) = \sum_i c[i] * L_i(x).\] Parameters c1-D array_like 1-D array of coefficients. Returns outndarray Array of the roots of the series. If all the roots are real, then out is also real, otherwise it is complex. See also numpy.polynomial.polynomial.polyroots numpy.polynomial.chebyshev.chebroots numpy.polynomial.laguerre.lagroots numpy.polynomial.hermite.hermroots numpy.polynomial.hermite_e.hermeroots Notes The root estimates are obtained as the eigenvalues of the companion matrix, Roots far from the origin of the complex plane may have large errors due to the numerical instability of the series for such values. Roots with multiplicity greater than 1 will also show larger errors as the value of the series near such points is relatively insensitive to errors in the roots. Isolated roots near the origin can be improved by a few iterations of Newton’s method. The Legendre series basis polynomials aren’t powers of x so the results of this function may seem unintuitive. Examples >>> import numpy.polynomial.legendre as leg >>> leg.legroots((1, 2, 3, 4)) # 4L_3 + 3L_2 + 2L_1 + 1L_0, all real roots array([-0.85099543, -0.11407192, 0.51506735]) # may vary
doc_1334
Set the lower and upper numerical bounds of the y-axis. This method will honor axis inversion regardless of parameter order. It will not change the autoscaling setting (get_autoscaley_on()). Parameters lower, upperfloat or None The lower and upper bounds. If None, the respective axis bound is not modified. See also get_ybound get_ylim, set_ylim invert_yaxis, yaxis_inverted
doc_1335
Registers a callable to convert a bytestring from the database into a custom Python type. The callable will be invoked for all database values that are of the type typename. Confer the parameter detect_types of the connect() function for how the type detection works. Note that typename and the name of the type in your query are matched in case-insensitive manner.
doc_1336
Combine an rgb image with an intensity map using "soft light" blending, using the "pegtop" formula. Parameters rgbndarray An MxNx3 RGB array of floats ranging from 0 to 1 (color image). intensityndarray An MxNx1 array of floats ranging from 0 to 1 (grayscale image). Returns ndarray An MxNx3 RGB array representing the combined images.
doc_1337
See torch.sinh()
doc_1338
os.O_RSYNC os.O_SYNC os.O_NDELAY os.O_NONBLOCK os.O_NOCTTY os.O_CLOEXEC The above constants are only available on Unix. Changed in version 3.3: Add O_CLOEXEC constant.
doc_1339
See Migration guide for more details. tf.compat.v1.SparseTensorSpec tf.SparseTensorSpec( shape=None, dtype=tf.dtypes.float32 ) Args shape The dense shape of the SparseTensor, or None to allow any dense shape. dtype tf.DType of values in the SparseTensor. Attributes dtype The tf.dtypes.DType specified by this type for the SparseTensor. shape The tf.TensorShape specified by this type for the SparseTensor. value_type Methods from_value View source @classmethod from_value( value ) is_compatible_with View source is_compatible_with( spec_or_value ) Returns true if spec_or_value is compatible with this TypeSpec. most_specific_compatible_type View source most_specific_compatible_type( other ) Returns the most specific TypeSpec compatible with self and other. Args other A TypeSpec. Raises ValueError If there is no TypeSpec that is compatible with both self and other. __eq__ View source __eq__( other ) Return self==value. __ne__ View source __ne__( other ) Return self!=value.
doc_1340
Bases: matplotlib.backend_bases.RendererBase close_group(s)[source] Close a grouping element with label s. Only used by the SVG renderer. draw_gouraud_triangle(gc, points, colors, trans)[source] Draw a Gouraud-shaded triangle. Parameters gcGraphicsContextBase The graphics context. points(3, 2) array-like Array of (x, y) points for the triangle. colors(3, 4) array-like RGBA colors for each point of the triangle. transformmatplotlib.transforms.Transform An affine transform to apply to the points. draw_gouraud_triangles(gc, triangles_array, colors_array, transform)[source] Draw a series of Gouraud triangles. Parameters points(N, 3, 2) array-like Array of N (x, y) points for the triangles. colors(N, 3, 4) array-like Array of N RGBA colors for each point of the triangles. transformmatplotlib.transforms.Transform An affine transform to apply to the points. draw_image(gc, x, y, im, transform=None)[source] Draw an RGBA image. Parameters gcGraphicsContextBase A graphics context with clipping information. xscalar The distance in physical units (i.e., dots or pixels) from the left hand side of the canvas. yscalar The distance in physical units (i.e., dots or pixels) from the bottom side of the canvas. im(N, M, 4) array-like of np.uint8 An array of RGBA pixels. transformmatplotlib.transforms.Affine2DBase If and only if the concrete backend is written such that option_scale_image() returns True, an affine transformation (i.e., an Affine2DBase) may be passed to draw_image(). The translation vector of the transformation is given in physical units (i.e., dots or pixels). Note that the transformation does not override x and y, and has to be applied before translating the result by x and y (this can be accomplished by adding x and y to the translation vector defined by transform). draw_markers(gc, marker_path, marker_trans, path, trans, rgbFace=None)[source] Draw a marker at each of path's vertices (excluding control points). This provides a fallback implementation of draw_markers that makes multiple calls to draw_path(). Some backends may want to override this method in order to draw the marker only once and reuse it multiple times. Parameters gcGraphicsContextBase The graphics context. marker_transmatplotlib.transforms.Transform An affine transform applied to the marker. transmatplotlib.transforms.Transform An affine transform applied to the path. draw_path(gc, path, transform, rgbFace=None)[source] Draw a Path instance using the given affine transform. draw_path_collection(gc, master_transform, paths, all_transforms, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position)[source] Draw a collection of paths selecting drawing properties from the lists facecolors, edgecolors, linewidths, linestyles and antialiaseds. offsets is a list of offsets to apply to each of the paths. The offsets in offsets are first transformed by offsetTrans before being applied. offset_position is unused now, but the argument is kept for backwards compatibility. This provides a fallback implementation of draw_path_collection() that makes multiple calls to draw_path(). Some backends may want to override this in order to render each set of path data only once, and then reference that path multiple times with the different offsets, colors, styles etc. The generator methods _iter_collection_raw_paths() and _iter_collection() are provided to help with (and standardize) the implementation across backends. It is highly recommended to use those generators, so that changes to the behavior of draw_path_collection() can be made globally. draw_tex(gc, x, y, s, prop, angle, *, mtext=None)[source] draw_text(gc, x, y, s, prop, angle, ismath=False, mtext=None)[source] Draw the text instance. Parameters gcGraphicsContextBase The graphics context. xfloat The x location of the text in display coords. yfloat The y location of the text baseline in display coords. sstr The text string. propmatplotlib.font_manager.FontProperties The font properties. anglefloat The rotation angle in degrees anti-clockwise. mtextmatplotlib.text.Text The original text object to be rendered. Notes Note for backend implementers: When you are trying to determine if you have gotten your bounding box right (which is what enables the text layout/alignment to work properly), it helps to change the line in text.py: if 0: bbox_artist(self, renderer) to if 1, and then the actual bounding box will be plotted along with your text. finalize()[source] flipy()[source] Return whether y values increase from top to bottom. Note that this only affects drawing of texts and images. get_canvas_width_height()[source] Return the canvas width and height in display coords. get_image_magnification()[source] Get the factor by which to magnify images passed to draw_image(). Allows a backend to have images at a different resolution to other artists. get_text_width_height_descent(s, prop, ismath)[source] Get the width, height, and descent (offset from the bottom to the baseline), in display coords, of the string s with FontProperties prop. propertymathtext_parser[source] open_group(s, gid=None)[source] Open a grouping element with label s and gid (if set) as id. Only used by the SVG renderer. option_image_nocomposite()[source] Return whether image composition by Matplotlib should be skipped. Raster backends should usually return False (letting the C-level rasterizer take care of image composition); vector backends should usually return not rcParams["image.composite_image"]. option_scale_image()[source] Return whether arbitrary affine transformations in draw_image() are supported (True for most vector backends).
doc_1341
The ordinal day of the year.
doc_1342
Bases: object valid is a list of legal strings. matplotlib.rcsetup.cycler(*args, **kwargs)[source] Create a Cycler object much like cycler.cycler(), but includes input validation. Call signatures: cycler(cycler) cycler(label=values[, label2=values2[, ...]]) cycler(label, values) Form 1 copies a given Cycler object. Form 2 creates a Cycler which cycles over one or more properties simultaneously. If multiple properties are given, their value lists must have the same length. Form 3 creates a Cycler for a single property. This form exists for compatibility with the original cycler. Its use is discouraged in favor of the kwarg form, i.e. cycler(label=values). Parameters cyclerCycler Copy constructor for Cycler. labelstr The property key. Must be a valid Artist property. For example, 'color' or 'linestyle'. Aliases are allowed, such as 'c' for 'color' and 'lw' for 'linewidth'. valuesiterable Finite-length iterable of the property values. These values are validated and will raise a ValueError if invalid. Returns Cycler A new Cycler for the given properties. Examples Creating a cycler for a single property: >>> c = cycler(color=['red', 'green', 'blue']) Creating a cycler for simultaneously cycling over multiple properties (e.g. red circle, green plus, blue cross): >>> c = cycler(color=['red', 'green', 'blue'], ... marker=['o', '+', 'x']) matplotlib.rcsetup.validate_any(s)[source] matplotlib.rcsetup.validate_anylist(s)[source] matplotlib.rcsetup.validate_aspect(s)[source] matplotlib.rcsetup.validate_axisbelow(s)[source] matplotlib.rcsetup.validate_backend(s)[source] matplotlib.rcsetup.validate_bbox(s)[source] matplotlib.rcsetup.validate_bool(b)[source] Convert b to bool or raise. matplotlib.rcsetup.validate_color(s)[source] Return a valid color arg. matplotlib.rcsetup.validate_color_for_prop_cycle(s)[source] matplotlib.rcsetup.validate_color_or_auto(s)[source] matplotlib.rcsetup.validate_color_or_inherit(s)[source] Return a valid color arg. matplotlib.rcsetup.validate_colorlist(s)[source] return a list of colorspecs matplotlib.rcsetup.validate_cycler(s)[source] Return a Cycler object from a string repr or the object itself. matplotlib.rcsetup.validate_dashlist(s)[source] return a list of floats matplotlib.rcsetup.validate_dpi(s)[source] Confirm s is string 'figure' or convert s to float or raise. matplotlib.rcsetup.validate_fillstylelist(s)[source] matplotlib.rcsetup.validate_float(s)[source] matplotlib.rcsetup.validate_float_or_None(s)[source] matplotlib.rcsetup.validate_floatlist(s)[source] return a list of floats matplotlib.rcsetup.validate_font_properties(s)[source] matplotlib.rcsetup.validate_fontsize(s)[source] matplotlib.rcsetup.validate_fontsize_None(s)[source] matplotlib.rcsetup.validate_fontsizelist(s)[source] matplotlib.rcsetup.validate_fonttype(s)[source] Confirm that this is a Postscript or PDF font type that we know how to convert to. matplotlib.rcsetup.validate_fontweight(s)[source] matplotlib.rcsetup.validate_hatch(s)[source] Validate a hatch pattern. A hatch pattern string can have any sequence of the following characters: \ / | - + * . x o O. matplotlib.rcsetup.validate_hatchlist(s)[source] Validate a hatch pattern. A hatch pattern string can have any sequence of the following characters: \ / | - + * . x o O. matplotlib.rcsetup.validate_hist_bins(s)[source] matplotlib.rcsetup.validate_int(s)[source] matplotlib.rcsetup.validate_int_or_None(s)[source] matplotlib.rcsetup.validate_markevery(s)[source] Validate the markevery property of a Line2D object. Parameters sNone, int, (int, int), slice, float, (float, float), or list[int] Returns None, int, (int, int), slice, float, (float, float), or list[int] matplotlib.rcsetup.validate_markeverylist(s)[source] Validate the markevery property of a Line2D object. Parameters sNone, int, (int, int), slice, float, (float, float), or list[int] Returns None, int, (int, int), slice, float, (float, float), or list[int] matplotlib.rcsetup.validate_ps_distiller(s)[source] matplotlib.rcsetup.validate_sketch(s)[source] matplotlib.rcsetup.validate_string(s)[source] matplotlib.rcsetup.validate_string_or_None(s)[source] matplotlib.rcsetup.validate_stringlist(s)[source] return a list of strings matplotlib.rcsetup.validate_whiskers(s)[source]
doc_1343
Encode path-like filename to the filesystem encoding with 'surrogateescape' error handler, or 'strict' on Windows; return bytes unchanged. fsdecode() is the reverse function. New in version 3.2. Changed in version 3.6: Support added to accept objects implementing the os.PathLike interface.
doc_1344
Query or modify the options of the specific tab_id. If kw is not given, returns a dictionary of the tab option values. If option is specified, returns the value of that option. Otherwise, sets the options to the corresponding values.
doc_1345
Schedules the callable, fn, to be executed as fn(*args **kwargs) and returns a Future object representing the execution of the callable. with ThreadPoolExecutor(max_workers=1) as executor: future = executor.submit(pow, 323, 1235) print(future.result())
doc_1346
Return whether this axes supports the zoom box button functionality. Polar axes do not support zoom boxes.
doc_1347
Returns the name of the current time zone.
doc_1348
tf.keras.constraints.max_norm Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.constraints.MaxNorm, tf.compat.v1.keras.constraints.max_norm tf.keras.constraints.MaxNorm( max_value=2, axis=0 ) Constrains the weights incident to each hidden unit to have a norm less than or equal to a desired value. Also available via the shortcut function tf.keras.constraints.max_norm. Arguments max_value the maximum norm value for the incoming weights. axis integer, axis along which to calculate weight norms. For instance, in a Dense layer the weight matrix has shape (input_dim, output_dim), set axis to 0 to constrain each weight vector of length (input_dim,). In a Conv2D layer with data_format="channels_last", the weight tensor has shape (rows, cols, input_depth, output_depth), set axis to [0, 1, 2] to constrain the weights of each filter tensor of size (rows, cols, input_depth).
doc_1349
Setup for writing the movie file. Parameters figFigure The figure to grab the rendered frames from. outfilestr The filename of the resulting movie file. dpifloat, default: fig.dpi The dpi of the output file. This, with the figure size, controls the size in pixels of the resulting movie file. frame_prefixstr, optional The filename prefix to use for temporary files. If None (the default), files are written to a temporary directory which is deleted by cleanup; if not None, no temporary files are deleted.
doc_1350
Reads one line from the stream. Parameters size (Optional[int]) – Return type bytes
doc_1351
Return the TexManager instance.
doc_1352
Probability calibration with isotonic regression or logistic regression. This class uses cross-validation to both estimate the parameters of a classifier and subsequently calibrate a classifier. With default ensemble=True, for each cv split it fits a copy of the base estimator to the training subset, and calibrates it using the testing subset. For prediction, predicted probabilities are averaged across these individual calibrated classifiers. When ensemble=False, cross-validation is used to obtain unbiased predictions, via cross_val_predict, which are then used for calibration. For prediction, the base estimator, trained using all the data, is used. This is the method implemented when probabilities=True for sklearn.svm estimators. Already fitted classifiers can be calibrated via the parameter cv="prefit". In this case, no cross-validation is used and all provided data is used for calibration. The user has to take care manually that data for model fitting and calibration are disjoint. The calibration is based on the decision_function method of the base_estimator if it exists, else on predict_proba. Read more in the User Guide. Parameters base_estimatorestimator instance, default=None The classifier whose output need to be calibrated to provide more accurate predict_proba outputs. The default classifier is a LinearSVC. method{‘sigmoid’, ‘isotonic’}, default=’sigmoid’ The method to use for calibration. Can be ‘sigmoid’ which corresponds to Platt’s method (i.e. a logistic regression model) or ‘isotonic’ which is a non-parametric approach. It is not advised to use isotonic calibration with too few calibration samples (<<1000) since it tends to overfit. cvint, cross-validation generator, iterable or “prefit”, default=None Determines the cross-validation splitting strategy. Possible inputs for cv are: None, to use the default 5-fold cross-validation, integer, to specify the number of folds. CV splitter, An iterable yielding (train, test) splits as arrays of indices. For integer/None inputs, if y is binary or multiclass, StratifiedKFold is used. If y is neither binary nor multiclass, KFold is used. Refer to the User Guide for the various cross-validation strategies that can be used here. If “prefit” is passed, it is assumed that base_estimator has been fitted already and all data is used for calibration. Changed in version 0.22: cv default value if None changed from 3-fold to 5-fold. n_jobsint, default=None Number of jobs to run in parallel. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. Base estimator clones are fitted in parallel across cross-validation iterations. Therefore parallelism happens only when cv != "prefit". See Glossary for more details. New in version 0.24. ensemblebool, default=True Determines how the calibrator is fitted when cv is not 'prefit'. Ignored if cv='prefit'. If True, the base_estimator is fitted using training data and calibrated using testing data, for each cv fold. The final estimator is an ensemble of n_cv fitted classifer and calibrator pairs, where n_cv is the number of cross-validation folds. The output is the average predicted probabilities of all pairs. If False, cv is used to compute unbiased predictions, via cross_val_predict, which are then used for calibration. At prediction time, the classifier used is the base_estimator trained on all the data. Note that this method is also internally implemented in sklearn.svm estimators with the probabilities=True parameter. New in version 0.24. Attributes classes_ndarray of shape (n_classes,) The class labels. calibrated_classifiers_list (len() equal to cv or 1 if cv="prefit" or ensemble=False) The list of classifier and calibrator pairs. When cv="prefit", the fitted base_estimator and fitted calibrator. When cv is not “prefit” and ensemble=True, n_cv fitted base_estimator and calibrator pairs. n_cv is the number of cross-validation folds. When cv is not “prefit” and ensemble=False, the base_estimator, fitted on all the data, and fitted calibrator. Changed in version 0.24: Single calibrated classifier case when ensemble=False. References 1 Obtaining calibrated probability estimates from decision trees and naive Bayesian classifiers, B. Zadrozny & C. Elkan, ICML 2001 2 Transforming Classifier Scores into Accurate Multiclass Probability Estimates, B. Zadrozny & C. Elkan, (KDD 2002) 3 Probabilistic Outputs for Support Vector Machines and Comparisons to Regularized Likelihood Methods, J. Platt, (1999) 4 Predicting Good Probabilities with Supervised Learning, A. Niculescu-Mizil & R. Caruana, ICML 2005 Examples >>> from sklearn.datasets import make_classification >>> from sklearn.naive_bayes import GaussianNB >>> from sklearn.calibration import CalibratedClassifierCV >>> X, y = make_classification(n_samples=100, n_features=2, ... n_redundant=0, random_state=42) >>> base_clf = GaussianNB() >>> calibrated_clf = CalibratedClassifierCV(base_estimator=base_clf, cv=3) >>> calibrated_clf.fit(X, y) CalibratedClassifierCV(base_estimator=GaussianNB(), cv=3) >>> len(calibrated_clf.calibrated_classifiers_) 3 >>> calibrated_clf.predict_proba(X)[:5, :] array([[0.110..., 0.889...], [0.072..., 0.927...], [0.928..., 0.071...], [0.928..., 0.071...], [0.071..., 0.928...]]) >>> from sklearn.model_selection import train_test_split >>> X, y = make_classification(n_samples=100, n_features=2, ... n_redundant=0, random_state=42) >>> X_train, X_calib, y_train, y_calib = train_test_split( ... X, y, random_state=42 ... ) >>> base_clf = GaussianNB() >>> base_clf.fit(X_train, y_train) GaussianNB() >>> calibrated_clf = CalibratedClassifierCV( ... base_estimator=base_clf, ... cv="prefit" ... ) >>> calibrated_clf.fit(X_calib, y_calib) CalibratedClassifierCV(base_estimator=GaussianNB(), cv='prefit') >>> len(calibrated_clf.calibrated_classifiers_) 1 >>> calibrated_clf.predict_proba([[-0.5, 0.5]]) array([[0.936..., 0.063...]]) Methods fit(X, y[, sample_weight]) Fit the calibrated model. get_params([deep]) Get parameters for this estimator. predict(X) Predict the target of new samples. predict_proba(X) Calibrated probabilities of classification. score(X, y[, sample_weight]) Return the mean accuracy on the given test data and labels. set_params(**params) Set the parameters of this estimator. fit(X, y, sample_weight=None) [source] Fit the calibrated model. Parameters Xarray-like of shape (n_samples, n_features) Training data. yarray-like of shape (n_samples,) Target values. sample_weightarray-like of shape (n_samples,), default=None Sample weights. If None, then samples are equally weighted. Returns selfobject Returns an instance of self. get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values. predict(X) [source] Predict the target of new samples. The predicted class is the class that has the highest probability, and can thus be different from the prediction of the uncalibrated classifier. Parameters Xarray-like of shape (n_samples, n_features) The samples. Returns Cndarray of shape (n_samples,) The predicted class. predict_proba(X) [source] Calibrated probabilities of classification. This function returns calibrated probabilities of classification according to each class on an array of test vectors X. Parameters Xarray-like of shape (n_samples, n_features) The samples. Returns Cndarray of shape (n_samples, n_classes) The predicted probas. score(X, y, sample_weight=None) [source] Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. Parameters Xarray-like of shape (n_samples, n_features) Test samples. yarray-like of shape (n_samples,) or (n_samples, n_outputs) True labels for X. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns scorefloat Mean accuracy of self.predict(X) wrt. y. set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
doc_1353
Create a new debugging server. Arguments are as per SMTPServer. Messages will be discarded, and printed on stdout.
doc_1354
See torch.multinomial()
doc_1355
Returns the length of this geometry (e.g., 0 for a Point, the length of a LineString, or the circumference of a Polygon).
doc_1356
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.
doc_1357
Return probability estimates for the test vectors X. Parameters Xarray-like of shape (n_samples, n_features) Test data. Returns Pndarray of shape (n_samples, n_classes) or list of such arrays Returns the probability of the sample for each class in the model, where classes are ordered arithmetically, for each output.
doc_1358
Find indices where elements should be inserted to maintain order. Find the indices into a sorted Series self such that, if the corresponding elements in value were inserted before the indices, the order of self would be preserved. Note The Series must be monotonically sorted, otherwise wrong locations will likely be returned. Pandas does not check this for you. Parameters value:array-like or scalar Values to insert into self. side:{‘left’, ‘right’}, optional If ‘left’, the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of self). sorter:1-D array-like, optional Optional array of integer indices that sort self into ascending order. They are typically the result of np.argsort. Returns int or array of int A scalar or array of insertion points with the same shape as value. See also sort_values Sort by the values along either axis. numpy.searchsorted Similar method from NumPy. Notes Binary search is used to find the required insertion points. Examples >>> ser = pd.Series([1, 2, 3]) >>> ser 0 1 1 2 2 3 dtype: int64 >>> ser.searchsorted(4) 3 >>> ser.searchsorted([0, 4]) array([0, 3]) >>> ser.searchsorted([1, 3], side='left') array([0, 2]) >>> ser.searchsorted([1, 3], side='right') array([1, 3]) >>> ser = pd.Series(pd.to_datetime(['3/11/2000', '3/12/2000', '3/13/2000'])) >>> ser 0 2000-03-11 1 2000-03-12 2 2000-03-13 dtype: datetime64[ns] >>> ser.searchsorted('3/14/2000') 3 >>> ser = pd.Categorical( ... ['apple', 'bread', 'bread', 'cheese', 'milk'], ordered=True ... ) >>> ser ['apple', 'bread', 'bread', 'cheese', 'milk'] Categories (4, object): ['apple' < 'bread' < 'cheese' < 'milk'] >>> ser.searchsorted('bread') 1 >>> ser.searchsorted(['bread'], side='right') array([3]) If the values are not monotonically sorted, wrong locations may be returned: >>> ser = pd.Series([2, 1, 3]) >>> ser 0 2 1 1 2 3 dtype: int64 >>> ser.searchsorted(1) 0 # wrong result, correct would be 1
doc_1359
Return a short string version of the tick value. Defaults to the position-independent long value.
doc_1360
Parse the form data in the environ and return it as tuple in the form (stream, form, files). You should only call this method if the transport method is POST, PUT, or PATCH. If the mimetype of the data transmitted is multipart/form-data the files multidict will be filled with FileStorage objects. If the mimetype is unknown the input stream is wrapped and returned as first argument, else the stream is empty. This is a shortcut for the common usage of FormDataParser. Have a look at Dealing with Request Data for more details. Changelog New in version 0.5.1: The optional silent flag was added. New in version 0.5: The max_form_memory_size, max_content_length and cls parameters were added. Parameters environ (WSGIEnvironment) – the WSGI environment to be used for parsing. stream_factory (Optional[TStreamFactory]) – An optional callable that returns a new read and writeable file descriptor. This callable works the same as Response._get_file_stream(). charset (str) – The character set for URL and url encoded form data. errors (str) – The encoding error behavior. max_form_memory_size (Optional[int]) – the maximum number of bytes to be accepted for in-memory stored form data. If the data exceeds the value specified an RequestEntityTooLarge exception is raised. max_content_length (Optional[int]) – If this is provided and the transmitted data is longer than this value an RequestEntityTooLarge exception is raised. cls (Optional[Type[werkzeug.datastructures.MultiDict]]) – an optional dict class to use. If this is not specified or None the default MultiDict is used. silent (bool) – If set to False parsing errors will not be caught. Returns A tuple in the form (stream, form, files). Return type t_parse_result
doc_1361
Append a new item with value x to the end of the array.
doc_1362
Estimate model parameters using X and predict the labels for X. The method fits the model n_init times and sets the parameters with which the model has the largest likelihood or lower bound. Within each trial, the method iterates between E-step and M-step for max_iter times until the change of likelihood or lower bound is less than tol, otherwise, a ConvergenceWarning is raised. After fitting, it predicts the most probable label for the input data points. New in version 0.20. Parameters Xarray-like of shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. Returns labelsarray, shape (n_samples,) Component labels.
doc_1363
Return the offsets for the collection.
doc_1364
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance.
doc_1365
See Migration guide for more details. tf.compat.v1.keras.activations.swish tf.keras.activations.swish( x ) Swish activation function which returns x*sigmoid(x). It is a smooth, non-monotonic function that consistently matches or outperforms ReLU on deep networks, it is unbounded above and bounded below. Example Usage: a = tf.constant([-20, -1.0, 0.0, 1.0, 20], dtype = tf.float32) b = tf.keras.activations.swish(a) b.numpy() array([-4.1223075e-08, -2.6894143e-01, 0.0000000e+00, 7.3105860e-01, 2.0000000e+01], dtype=float32) Arguments x Input tensor. Returns The swish activation applied to x (see reference paper for details). Reference: Ramachandran et al., 2017
doc_1366
class sklearn.ensemble.ExtraTreesClassifier(n_estimators=100, *, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, bootstrap=False, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, class_weight=None, ccp_alpha=0.0, max_samples=None) [source] An extra-trees classifier. This class implements a meta estimator that fits a number of randomized decision trees (a.k.a. extra-trees) on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting. Read more in the User Guide. Parameters n_estimatorsint, default=100 The number of trees in the forest. Changed in version 0.22: The default value of n_estimators changed from 10 to 100 in 0.22. criterion{“gini”, “entropy”}, default=”gini” The function to measure the quality of a split. Supported criteria are “gini” for the Gini impurity and “entropy” for the information gain. max_depthint, default=None The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. min_samples_splitint or float, default=2 The minimum number of samples required to split an internal node: If int, then consider min_samples_split as the minimum number. If float, then min_samples_split is a fraction and ceil(min_samples_split * n_samples) are the minimum number of samples for each split. Changed in version 0.18: Added float values for fractions. min_samples_leafint or float, default=1 The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least min_samples_leaf training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. If int, then consider min_samples_leaf as the minimum number. If float, then min_samples_leaf is a fraction and ceil(min_samples_leaf * n_samples) are the minimum number of samples for each node. Changed in version 0.18: Added float values for fractions. min_weight_fraction_leaffloat, default=0.0 The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. max_features{“auto”, “sqrt”, “log2”}, int or float, default=”auto” The number of features to consider when looking for the best split: If int, then consider max_features features at each split. If float, then max_features is a fraction and round(max_features * n_features) features are considered at each split. If “auto”, then max_features=sqrt(n_features). If “sqrt”, then max_features=sqrt(n_features). If “log2”, then max_features=log2(n_features). If None, then max_features=n_features. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than max_features features. max_leaf_nodesint, default=None Grow trees with max_leaf_nodes in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. min_impurity_decreasefloat, default=0.0 A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where N is the total number of samples, N_t is the number of samples at the current node, N_t_L is the number of samples in the left child, and N_t_R is the number of samples in the right child. N, N_t, N_t_R and N_t_L all refer to the weighted sum, if sample_weight is passed. New in version 0.19. min_impurity_splitfloat, default=None Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf. Deprecated since version 0.19: min_impurity_split has been deprecated in favor of min_impurity_decrease in 0.19. The default value of min_impurity_split has changed from 1e-7 to 0 in 0.23 and it will be removed in 1.0 (renaming of 0.25). Use min_impurity_decrease instead. bootstrapbool, default=False Whether bootstrap samples are used when building trees. If False, the whole dataset is used to build each tree. oob_scorebool, default=False Whether to use out-of-bag samples to estimate the generalization accuracy. n_jobsint, default=None The number of jobs to run in parallel. fit, predict, decision_path and apply are all parallelized over the trees. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. random_stateint, RandomState instance or None, default=None Controls 3 sources of randomness: the bootstrapping of the samples used when building trees (if bootstrap=True) the sampling of the features to consider when looking for the best split at each node (if max_features < n_features) the draw of the splits for each of the max_features See Glossary for details. verboseint, default=0 Controls the verbosity when fitting and predicting. warm_startbool, default=False When set to True, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. See the Glossary. class_weight{“balanced”, “balanced_subsample”}, dict or list of dicts, default=None Weights associated with classes in the form {class_label: weight}. If not given, all classes are supposed to have weight one. For multi-output problems, a list of dicts can be provided in the same order as the columns of y. Note that for multioutput (including multilabel) weights should be defined for each class of every column in its own dict. For example, for four-class multilabel classification weights should be [{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of [{1:1}, {2:5}, {3:1}, {4:1}]. The “balanced” mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as n_samples / (n_classes * np.bincount(y)) The “balanced_subsample” mode is the same as “balanced” except that weights are computed based on the bootstrap sample for every tree grown. For multi-output, the weights of each column of y will be multiplied. Note that these weights will be multiplied with sample_weight (passed through the fit method) if sample_weight is specified. ccp_alphanon-negative float, default=0.0 Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ccp_alpha will be chosen. By default, no pruning is performed. See Minimal Cost-Complexity Pruning for details. New in version 0.22. max_samplesint or float, default=None If bootstrap is True, the number of samples to draw from X to train each base estimator. If None (default), then draw X.shape[0] samples. If int, then draw max_samples samples. If float, then draw max_samples * X.shape[0] samples. Thus, max_samples should be in the interval (0, 1). New in version 0.22. Attributes base_estimator_ExtraTreesClassifier The child estimator template used to create the collection of fitted sub-estimators. estimators_list of DecisionTreeClassifier The collection of fitted sub-estimators. classes_ndarray of shape (n_classes,) or a list of such arrays The classes labels (single output problem), or a list of arrays of class labels (multi-output problem). n_classes_int or list The number of classes (single output problem), or a list containing the number of classes for each output (multi-output problem). feature_importances_ndarray of shape (n_features,) The impurity-based feature importances. n_features_int The number of features when fit is performed. n_outputs_int The number of outputs when fit is performed. oob_score_float Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when oob_score is True. oob_decision_function_ndarray of shape (n_samples, n_classes) Decision function computed with out-of-bag estimate on the training set. If n_estimators is small it might be possible that a data point was never left out during the bootstrap. In this case, oob_decision_function_ might contain NaN. This attribute exists only when oob_score is True. See also sklearn.tree.ExtraTreeClassifier Base classifier for this ensemble. RandomForestClassifier Ensemble Classifier based on trees with optimal splits. Notes The default values for the parameters controlling the size of the trees (e.g. max_depth, min_samples_leaf, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values. References 1 P. Geurts, D. Ernst., and L. Wehenkel, “Extremely randomized trees”, Machine Learning, 63(1), 3-42, 2006. Examples >>> from sklearn.ensemble import ExtraTreesClassifier >>> from sklearn.datasets import make_classification >>> X, y = make_classification(n_features=4, random_state=0) >>> clf = ExtraTreesClassifier(n_estimators=100, random_state=0) >>> clf.fit(X, y) ExtraTreesClassifier(random_state=0) >>> clf.predict([[0, 0, 0, 0]]) array([1]) Methods apply(X) Apply trees in the forest to X, return leaf indices. decision_path(X) Return the decision path in the forest. fit(X, y[, sample_weight]) Build a forest of trees from the training set (X, y). get_params([deep]) Get parameters for this estimator. predict(X) Predict class for X. predict_log_proba(X) Predict class log-probabilities for X. predict_proba(X) Predict class probabilities for X. score(X, y[, sample_weight]) Return the mean accuracy on the given test data and labels. set_params(**params) Set the parameters of this estimator. apply(X) [source] Apply trees in the forest to X, return leaf indices. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csr_matrix. Returns X_leavesndarray of shape (n_samples, n_estimators) For each datapoint x in X and for each tree in the forest, return the index of the leaf x ends up in. decision_path(X) [source] Return the decision path in the forest. New in version 0.18. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csr_matrix. Returns indicatorsparse matrix of shape (n_samples, n_nodes) Return a node indicator matrix where non zero elements indicates that the samples goes through the nodes. The matrix is of CSR format. n_nodes_ptrndarray of shape (n_estimators + 1,) The columns from indicator[n_nodes_ptr[i]:n_nodes_ptr[i+1]] gives the indicator value for the i-th estimator. property feature_importances_ The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See sklearn.inspection.permutation_importance as an alternative. Returns feature_importances_ndarray of shape (n_features,) The values of this array sum to 1, unless all trees are single node trees consisting of only the root node, in which case it will be an array of zeros. fit(X, y, sample_weight=None) [source] Build a forest of trees from the training set (X, y). Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csc_matrix. yarray-like of shape (n_samples,) or (n_samples, n_outputs) The target values (class labels in classification, real numbers in regression). sample_weightarray-like of shape (n_samples,), default=None Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. In the case of classification, splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns selfobject get_params(deep=True) [source] Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values. predict(X) [source] Predict class for X. The predicted class of an input sample is a vote by the trees in the forest, weighted by their probability estimates. That is, the predicted class is the one with highest mean probability estimate across the trees. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csr_matrix. Returns yndarray of shape (n_samples,) or (n_samples, n_outputs) The predicted classes. predict_log_proba(X) [source] Predict class log-probabilities for X. The predicted class log-probabilities of an input sample is computed as the log of the mean predicted class probabilities of the trees in the forest. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csr_matrix. Returns pndarray of shape (n_samples, n_classes), or a list of n_outputs such arrays if n_outputs > 1. The class probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_. predict_proba(X) [source] Predict class probabilities for X. The predicted class probabilities of an input sample are computed as the mean predicted class probabilities of the trees in the forest. The class probability of a single tree is the fraction of samples of the same class in a leaf. Parameters X{array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csr_matrix. Returns pndarray of shape (n_samples, n_classes), or a list of n_outputs such arrays if n_outputs > 1. The class probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_. score(X, y, sample_weight=None) [source] Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. Parameters Xarray-like of shape (n_samples, n_features) Test samples. yarray-like of shape (n_samples,) or (n_samples, n_outputs) True labels for X. sample_weightarray-like of shape (n_samples,), default=None Sample weights. Returns scorefloat Mean accuracy of self.predict(X) wrt. y. set_params(**params) [source] Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters **paramsdict Estimator parameters. Returns selfestimator instance Estimator instance. Examples using sklearn.ensemble.ExtraTreesClassifier Pixel importances with a parallel forest of trees Feature importances with forests of trees Hashing feature transformation using Totally Random Trees Plot the decision surfaces of ensembles of trees on the iris dataset
doc_1367
Estimate the bandwidth to use with the mean-shift algorithm. That this function takes time at least quadratic in n_samples. For large datasets, it’s wise to set that parameter to a small value. Parameters Xarray-like of shape (n_samples, n_features) Input points. quantilefloat, default=0.3 should be between [0, 1] 0.5 means that the median of all pairwise distances is used. n_samplesint, default=None The number of samples to use. If not given, all samples are used. random_stateint, RandomState instance, default=None The generator used to randomly select the samples from input points for bandwidth estimation. Use an int to make the randomness deterministic. See Glossary. n_jobsint, default=None The number of parallel jobs to run for neighbors search. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details. Returns bandwidthfloat The bandwidth parameter.
doc_1368
Apply this handler’s filters to the record and return True if the record is to be processed. The filters are consulted in turn, until one of them returns a false value. If none of them return a false value, the record will be emitted. If one returns a false value, the handler will not emit the record.
doc_1369
Returns copies of the rules wrapped and expands string templates in the endpoint, rule, defaults or subdomain sections. Here a small example for such a rule template: from werkzeug.routing import Map, Rule, RuleTemplate resource = RuleTemplate([ Rule('/$name/', endpoint='$name.list'), Rule('/$name/<int:id>', endpoint='$name.show') ]) url_map = Map([resource(name='user'), resource(name='page')]) When a rule template is called the keyword arguments are used to replace the placeholders in all the string parameters. Parameters rules (Iterable[Rule]) – Return type None
doc_1370
An Executor subclass that uses a pool of at most max_workers threads to execute calls asynchronously. initializer is an optional callable that is called at the start of each worker thread; initargs is a tuple of arguments passed to the initializer. Should initializer raise an exception, all currently pending jobs will raise a BrokenThreadPool, as well as any attempt to submit more jobs to the pool. Changed in version 3.5: If max_workers is None or not given, it will default to the number of processors on the machine, multiplied by 5, assuming that ThreadPoolExecutor is often used to overlap I/O instead of CPU work and the number of workers should be higher than the number of workers for ProcessPoolExecutor. New in version 3.6: The thread_name_prefix argument was added to allow users to control the threading.Thread names for worker threads created by the pool for easier debugging. Changed in version 3.7: Added the initializer and initargs arguments. Changed in version 3.8: Default value of max_workers is changed to min(32, os.cpu_count() + 4). This default value preserves at least 5 workers for I/O bound tasks. It utilizes at most 32 CPU cores for CPU bound tasks which release the GIL. And it avoids using very large resources implicitly on many-core machines. ThreadPoolExecutor now reuses idle worker threads before starting max_workers worker threads too.
doc_1371
Convert inputs to arrays with at least one dimension. Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved. Parameters arys1, arys2, …array_like One or more input arrays. Returns retndarray An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary. See also atleast_2d, atleast_3d Examples >>> np.atleast_1d(1.0) array([1.]) >>> x = np.arange(9.0).reshape(3,3) >>> np.atleast_1d(x) array([[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]]) >>> np.atleast_1d(x) is x True >>> np.atleast_1d(1, [3, 4]) [array([1]), array([3, 4])]
doc_1372
A mapping of ContextVars to their values. Context() creates an empty context with no values in it. To get a copy of the current context use the copy_context() function. Context implements the collections.abc.Mapping interface. run(callable, *args, **kwargs) Execute callable(*args, **kwargs) code in the context object the run method is called on. Return the result of the execution or propagate an exception if one occurred. Any changes to any context variables that callable makes will be contained in the context object: var = ContextVar('var') var.set('spam') def main(): # 'var' was set to 'spam' before # calling 'copy_context()' and 'ctx.run(main)', so: # var.get() == ctx[var] == 'spam' var.set('ham') # Now, after setting 'var' to 'ham': # var.get() == ctx[var] == 'ham' ctx = copy_context() # Any changes that the 'main' function makes to 'var' # will be contained in 'ctx'. ctx.run(main) # The 'main()' function was run in the 'ctx' context, # so changes to 'var' are contained in it: # ctx[var] == 'ham' # However, outside of 'ctx', 'var' is still set to 'spam': # var.get() == 'spam' The method raises a RuntimeError when called on the same context object from more than one OS thread, or when called recursively. copy() Return a shallow copy of the context object. var in context Return True if the context has a value for var set; return False otherwise. context[var] Return the value of the var ContextVar variable. If the variable is not set in the context object, a KeyError is raised. get(var[, default]) Return the value for var if var has the value in the context object. Return default otherwise. If default is not given, return None. iter(context) Return an iterator over the variables stored in the context object. len(proxy) Return the number of variables set in the context object. keys() Return a list of all variables in the context object. values() Return a list of all variables’ values in the context object. items() Return a list of 2-tuples containing all variables and their values in the context object.
doc_1373
See Migration guide for more details. tf.compat.v1.raw_ops.Neg tf.raw_ops.Neg( x, name=None ) I.e., \(y = -x\). Args x A Tensor. Must be one of the following types: bfloat16, half, float32, float64, int8, int16, int32, int64, complex64, complex128. name A name for the operation (optional). Returns A Tensor. Has the same type as x.
doc_1374
The OpenerDirector class opens URLs via BaseHandlers chained together. It manages the chaining of handlers, and recovery from errors.
doc_1375
Set the state of the encoder to state. state must be an encoder state returned by getstate().
doc_1376
True if the QuerySet is ordered — i.e. has an order_by() clause or a default ordering on the model. False otherwise.
doc_1377
Deletes the specified key. key is an already open key, or one of the predefined HKEY_* constants. sub_key is a string that must be a subkey of the key identified by the key parameter. This value must not be None, and the key may not have subkeys. This method can not delete keys with subkeys. If the method succeeds, the entire key, including all of its values, is removed. If the method fails, an OSError exception is raised. Raises an auditing event winreg.DeleteKey with arguments key, sub_key, access. Changed in version 3.3: See above.
doc_1378
This is raised if data is specified for a node which does not support data.
doc_1379
Return current line number and offset.
doc_1380
Compute the 2-dimensional inverse finite radon transform (iFRT) for an (n+1) x n integer array. Parameters aarray_like A 2-D (n+1) row x n column integer array. Returns iFRT2-D n x n ndarray Inverse Finite Radon Transform array of n x n integer coefficients. See also frt2 The two-dimensional FRT Notes The FRT has a unique inverse if and only if n is prime. See [1] for an overview. The idea for this algorithm is due to Vlad Negnevitski. References 1 A. Kingston and I. Svalbe, “Projective transforms on periodic discrete image arrays,” in P. Hawkes (Ed), Advances in Imaging and Electron Physics, 139 (2006) Examples >>> SIZE = 59 >>> img = np.tri(SIZE, dtype=np.int32) Apply the Finite Radon Transform: >>> f = frt2(img) Apply the Inverse Finite Radon Transform to recover the input >>> fi = ifrt2(f) Check that it’s identical to the original >>> assert len(np.nonzero(img-fi)[0]) == 0
doc_1381
Raised when a Unicode-related encoding or decoding error occurs. It is a subclass of ValueError. UnicodeError has attributes that describe the encoding or decoding error. For example, err.object[err.start:err.end] gives the particular invalid input that the codec failed on. encoding The name of the encoding that raised the error. reason A string describing the specific codec error. object The object the codec was attempting to encode or decode. start The first index of invalid data in object. end The index after the last invalid data in object.
doc_1382
Bases: matplotlib.patches.BoxStyle.Sawtooth A box with a rounded sawtooth outline. Parameters padfloat, default: 0.3 The amount of padding around the original box. tooth_sizefloat, default: pad/2 Size of the sawtooth. __call__(x0, y0, width, height, mutation_size, mutation_aspect=<deprecated parameter>)[source] Given the location and size of the box, return the path of the box around it. Parameters x0, y0, width, heightfloat Location and size of the box. mutation_sizefloat A reference scale for the mutation. Returns Path
doc_1383
Return True if a stopped child has been resumed by delivery of SIGCONT (if the process has been continued from a job control stop), otherwise return False. See WCONTINUED option. Availability: Unix.
doc_1384
tf.compat.v1.tuple( tensors, name=None, control_inputs=None ) This creates a tuple of tensors with the same values as the tensors argument, except that the value of each tensor is only returned after the values of all tensors have been computed. control_inputs contains additional ops that have to finish before this op finishes, but whose outputs are not returned. This can be used as a "join" mechanism for parallel computations: all the argument tensors can be computed in parallel, but the values of any tensor returned by tuple are only available after all the parallel computations are done. See also tf.group and tf.control_dependencies. Args tensors A list of Tensors or IndexedSlices, some entries can be None. name (optional) A name to use as a name_scope for the operation. control_inputs List of additional ops to finish before returning. Returns Same as tensors. Raises ValueError If tensors does not contain any Tensor or IndexedSlices. TypeError If control_inputs is not a list of Operation or Tensor objects.
doc_1385
import ssl hostname = 'www.python.org' context = ssl.create_default_context() with socket.create_connection((hostname, 443)) as sock: with context.wrap_socket(sock, server_hostname=hostname) as ssock: print(ssock.version()) Client socket example with custom context and IPv4: hostname = 'www.python.org' # PROTOCOL_TLS_CLIENT requires valid cert chain and hostname context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) context.load_verify_locations('path/to/cabundle.pem') with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock: with context.wrap_socket(sock, server_hostname=hostname) as ssock: print(ssock.version()) Server socket example listening on localhost IPv4: context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) context.load_cert_chain('/path/to/certchain.pem', '/path/to/private.key') with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock: sock.bind(('127.0.0.1', 8443)) sock.listen(5) with context.wrap_socket(sock, server_side=True) as ssock: conn, addr = ssock.accept() ... Context creation A convenience function helps create SSLContext objects for common purposes. ssl.create_default_context(purpose=Purpose.SERVER_AUTH, cafile=None, capath=None, cadata=None) Return a new SSLContext object with default settings for the given purpose. The settings are chosen by the ssl module, and usually represent a higher security level than when calling the SSLContext constructor directly. cafile, capath, cadata represent optional CA certificates to trust for certificate verification, as in SSLContext.load_verify_locations(). If all three are None, this function can choose to trust the system’s default CA certificates instead. The settings are: PROTOCOL_TLS, OP_NO_SSLv2, and OP_NO_SSLv3 with high encryption cipher suites without RC4 and without unauthenticated cipher suites. Passing SERVER_AUTH as purpose sets verify_mode to CERT_REQUIRED and either loads CA certificates (when at least one of cafile, capath or cadata is given) or uses SSLContext.load_default_certs() to load default CA certificates. When keylog_filename is supported and the environment variable SSLKEYLOGFILE is set, create_default_context() enables key logging. Note The protocol, options, cipher and other settings may change to more restrictive values anytime without prior deprecation. The values represent a fair balance between compatibility and security. If your application needs specific settings, you should create a SSLContext and apply the settings yourself. Note If you find that when certain older clients or servers attempt to connect with a SSLContext created by this function that they get an error stating “Protocol or cipher suite mismatch”, it may be that they only support SSL3.0 which this function excludes using the OP_NO_SSLv3. SSL3.0 is widely considered to be completely broken. If you still wish to continue to use this function but still allow SSL 3.0 connections you can re-enable them using: ctx = ssl.create_default_context(Purpose.CLIENT_AUTH) ctx.options &= ~ssl.OP_NO_SSLv3 New in version 3.4. Changed in version 3.4.4: RC4 was dropped from the default cipher string. Changed in version 3.6: ChaCha20/Poly1305 was added to the default cipher string. 3DES was dropped from the default cipher string. Changed in version 3.8: Support for key logging to SSLKEYLOGFILE was added. Exceptions exception ssl.SSLError 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. library 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. reason 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. exception ssl.SSLZeroReturnError 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. exception ssl.SSLWantReadError 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. exception ssl.SSLWantWriteError 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. exception ssl.SSLSyscallError 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. exception ssl.SSLEOFError 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. exception ssl.SSLCertVerificationError A subclass of SSLError raised when certificate validation has failed. New in version 3.7. verify_code A numeric error number that denotes the verification error. verify_message A human readable string of the verification error. exception ssl.CertificateError An alias for SSLCertVerificationError. Changed in version 3.7: The exception is now an alias for SSLCertVerificationError. Random generation ssl.RAND_bytes(num) Return num cryptographically strong pseudo-random bytes. Raises an SSLError if the PRNG has not been seeded with enough data or if the operation is not supported by the current RAND method. RAND_status() can be used to check the status of the PRNG and RAND_add() can be used to seed the PRNG. For almost all applications os.urandom() is preferable. Read the Wikipedia article, Cryptographically secure pseudorandom number generator (CSPRNG), to get the requirements of a cryptographically strong generator. New in version 3.3. ssl.RAND_pseudo_bytes(num) Return (bytes, is_cryptographic): bytes are num pseudo-random bytes, is_cryptographic is True if the bytes generated are cryptographically strong. Raises an SSLError if the operation is not supported by the current RAND method. Generated pseudo-random byte sequences will be unique if they are of sufficient length, but are not necessarily unpredictable. They can be used for non-cryptographic purposes and for certain purposes in cryptographic protocols, but usually not for key generation etc. For almost all applications os.urandom() is preferable. New in version 3.3. Deprecated since version 3.6: OpenSSL has deprecated ssl.RAND_pseudo_bytes(), use ssl.RAND_bytes() instead. ssl.RAND_status() Return True if the SSL pseudo-random number generator has been seeded with ‘enough’ randomness, and False otherwise. You can use ssl.RAND_egd() and ssl.RAND_add() to increase the randomness of the pseudo-random number generator. ssl.RAND_egd(path) If you are running an entropy-gathering daemon (EGD) somewhere, and path is the pathname of a socket connection open to it, this will read 256 bytes of randomness from the socket, and add it to the SSL pseudo-random number generator to increase the security of generated secret keys. This is typically only necessary on systems without better sources of randomness. See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources of entropy-gathering daemons. Availability: not available with LibreSSL and OpenSSL > 1.1.0. ssl.RAND_add(bytes, entropy) Mix the given bytes into the SSL pseudo-random number generator. The parameter entropy (a float) is a lower bound on the entropy contained in string (so you can always use 0.0). See RFC 1750 for more information on sources of entropy. Changed in version 3.5: Writable bytes-like object is now accepted. Certificate handling ssl.match_hostname(cert, hostname) Verify that cert (in decoded format as returned by SSLSocket.getpeercert()) matches the given hostname. The rules applied are those for checking the identity of HTTPS servers as outlined in RFC 2818, RFC 5280 and RFC 6125. In addition to HTTPS, this function should be suitable for checking the identity of servers in various SSL-based protocols such as FTPS, IMAPS, POPS and others. CertificateError is raised on failure. On success, the function returns nothing: >>> cert = {'subject': ((('commonName', 'example.com'),),)} >>> ssl.match_hostname(cert, "example.com") >>> ssl.match_hostname(cert, "example.org") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/py3k/Lib/ssl.py", line 130, in match_hostname ssl.CertificateError: hostname 'example.org' doesn't match 'example.com' New in version 3.2. Changed in version 3.3.3: The function now follows RFC 6125, section 6.4.3 and does neither match multiple wildcards (e.g. *.*.com or *a*.example.org) nor a wildcard inside an internationalized domain names (IDN) fragment. IDN A-labels such as www*.xn--pthon-kva.org are still supported, but x*.python.org no longer matches xn--tda.python.org. Changed in version 3.5: Matching of IP addresses, when present in the subjectAltName field of the certificate, is now supported. Changed in version 3.7: The function is no longer used to TLS connections. Hostname matching is now performed by OpenSSL. Allow wildcard when it is the leftmost and the only character in that segment. Partial wildcards like www*.example.com are no longer supported. Deprecated since version 3.7. ssl.cert_time_to_seconds(cert_time) Return the time in seconds since the Epoch, given the cert_time string representing the “notBefore” or “notAfter” date from a certificate in "%b %d %H:%M:%S %Y %Z" strptime format (C locale). Here’s an example: >>> import ssl >>> timestamp = ssl.cert_time_to_seconds("Jan 5 09:34:43 2018 GMT") >>> timestamp 1515144883 >>> from datetime import datetime >>> print(datetime.utcfromtimestamp(timestamp)) 2018-01-05 09:34:43 “notBefore” or “notAfter” dates must use GMT (RFC 5280). Changed in version 3.5: Interpret the input time as a time in UTC as specified by ‘GMT’ timezone in the input string. Local timezone was used previously. Return an integer (no fractions of a second in the input format) ssl.get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None) Given the address addr of an SSL-protected server, as a (hostname, port-number) pair, fetches the server’s certificate, and returns it as a PEM-encoded string. If ssl_version is specified, uses that version of the SSL protocol to attempt to connect to the server. If ca_certs is specified, it should be a file containing a list of root certificates, the same format as used for the same parameter in SSLContext.wrap_socket(). The call will attempt to validate the server certificate against that set of root certificates, and will fail if the validation attempt fails. Changed in version 3.3: This function is now IPv6-compatible. Changed in version 3.5: The default ssl_version is changed from PROTOCOL_SSLv3 to PROTOCOL_TLS for maximum compatibility with modern servers. ssl.DER_cert_to_PEM_cert(DER_cert_bytes) Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded string version of the same certificate. ssl.PEM_cert_to_DER_cert(PEM_cert_string) Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of bytes for that same certificate. ssl.get_default_verify_paths() Returns a named tuple with paths to OpenSSL’s default cafile and capath. The paths are the same as used by SSLContext.set_default_verify_paths(). The return value is a named tuple DefaultVerifyPaths: cafile - resolved path to cafile or None if the file doesn’t exist, capath - resolved path to capath or None if the directory doesn’t exist, openssl_cafile_env - OpenSSL’s environment key that points to a cafile, openssl_cafile - hard coded path to a cafile, openssl_capath_env - OpenSSL’s environment key that points to a capath, openssl_capath - hard coded path to a capath directory Availability: LibreSSL ignores the environment vars openssl_cafile_env and openssl_capath_env. New in version 3.4. ssl.enum_certificates(store_name) Retrieve certificates from Windows’ system cert store. store_name may be one of CA, ROOT or MY. Windows may provide additional cert stores, too. The function returns a list of (cert_bytes, encoding_type, trust) tuples. The encoding_type specifies the encoding of cert_bytes. It is either x509_asn for X.509 ASN.1 data or pkcs_7_asn for PKCS#7 ASN.1 data. Trust specifies the purpose of the certificate as a set of OIDS or exactly True if the certificate is trustworthy for all purposes. Example: >>> ssl.enum_certificates("CA") [(b'data...', 'x509_asn', {'1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2'}), (b'data...', 'x509_asn', True)] Availability: Windows. New in version 3.4. ssl.enum_crls(store_name) Retrieve CRLs from Windows’ system cert store. store_name may be one of CA, ROOT or MY. Windows may provide additional cert stores, too. The function returns a list of (cert_bytes, encoding_type, trust) tuples. The encoding_type specifies the encoding of cert_bytes. It is either x509_asn for X.509 ASN.1 data or pkcs_7_asn for PKCS#7 ASN.1 data. Availability: Windows. New in version 3.4. ssl.wrap_socket(sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version=PROTOCOL_TLS, ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True, ciphers=None) 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. Constants All constants are now enum.IntEnum or enum.IntFlag collections. New in version 3.6. ssl.CERT_NONE Possible value for SSLContext.verify_mode, or the cert_reqs parameter to wrap_socket(). Except for PROTOCOL_TLS_CLIENT, it is the default mode. With client-side sockets, just about any cert is accepted. Validation errors, such as untrusted or expired cert, are ignored and do not abort the TLS/SSL handshake. In server mode, no certificate is requested from the client, so the client does not send any for client cert authentication. See the discussion of Security considerations below. ssl.CERT_OPTIONAL Possible value for SSLContext.verify_mode, or the cert_reqs parameter to wrap_socket(). In client mode, CERT_OPTIONAL has the same meaning as CERT_REQUIRED. It is recommended to use CERT_REQUIRED for client-side sockets instead. In server mode, a client certificate request is sent to the client. The client may either ignore the request or send a certificate in order perform TLS client cert authentication. If the client chooses to send a certificate, it is verified. Any verification error immediately aborts the TLS handshake. Use of this setting requires a valid set of CA certificates to be passed, either to SSLContext.load_verify_locations() or as a value of the ca_certs parameter to wrap_socket(). ssl.CERT_REQUIRED Possible value for SSLContext.verify_mode, or the cert_reqs parameter to wrap_socket(). In this mode, certificates are required from the other side of the socket connection; an SSLError will be raised if no certificate is provided, or if its validation fails. This mode is not sufficient to verify a certificate in client mode as it does not match hostnames. check_hostname must be enabled as well to verify the authenticity of a cert. PROTOCOL_TLS_CLIENT uses CERT_REQUIRED and enables check_hostname by default. With server socket, this mode provides mandatory TLS client cert authentication. A client certificate request is sent to the client and the client must provide a valid and trusted certificate. Use of this setting requires a valid set of CA certificates to be passed, either to SSLContext.load_verify_locations() or as a value of the ca_certs parameter to wrap_socket(). class ssl.VerifyMode enum.IntEnum collection of CERT_* constants. New in version 3.6. ssl.VERIFY_DEFAULT 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. ssl.VERIFY_CRL_CHECK_LEAF 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. ssl.VERIFY_CRL_CHECK_CHAIN 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. ssl.VERIFY_X509_STRICT Possible value for SSLContext.verify_flags to disable workarounds for broken X.509 certificates. New in version 3.4. ssl.VERIFY_X509_TRUSTED_FIRST 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. class ssl.VerifyFlags enum.IntFlag collection of VERIFY_* constants. New in version 3.6. ssl.PROTOCOL_TLS Selects the highest protocol version that both the client and server support. Despite the name, this option can select both “SSL” and “TLS” protocols. New in version 3.6. ssl.PROTOCOL_TLS_CLIENT Auto-negotiate the highest protocol version like PROTOCOL_TLS, but only support client-side SSLSocket connections. The protocol enables CERT_REQUIRED and check_hostname by default. New in version 3.6. ssl.PROTOCOL_TLS_SERVER Auto-negotiate the highest protocol version like PROTOCOL_TLS, but only support server-side SSLSocket connections. New in version 3.6. ssl.PROTOCOL_SSLv23 Alias for PROTOCOL_TLS. Deprecated since version 3.6: Use PROTOCOL_TLS instead. ssl.PROTOCOL_SSLv2 Selects SSL version 2 as the channel encryption protocol. This protocol is not available if OpenSSL is compiled with the OPENSSL_NO_SSL2 flag. Warning SSL version 2 is insecure. Its use is highly discouraged. Deprecated since version 3.6: OpenSSL has removed support for SSLv2. ssl.PROTOCOL_SSLv3 Selects SSL version 3 as the channel encryption protocol. This protocol is not be available if OpenSSL is compiled with the OPENSSL_NO_SSLv3 flag. Warning SSL version 3 is insecure. Its use is highly discouraged. Deprecated since version 3.6: OpenSSL has deprecated all version specific protocols. Use the default protocol PROTOCOL_TLS with flags like OP_NO_SSLv3 instead. ssl.PROTOCOL_TLSv1 Selects TLS version 1.0 as the channel encryption protocol. Deprecated since version 3.6: OpenSSL has deprecated all version specific protocols. Use the default protocol PROTOCOL_TLS with flags like OP_NO_SSLv3 instead. ssl.PROTOCOL_TLSv1_1 Selects TLS version 1.1 as the channel encryption protocol. Available only with openssl version 1.0.1+. New in version 3.4. Deprecated since version 3.6: OpenSSL has deprecated all version specific protocols. Use the default protocol PROTOCOL_TLS with flags like OP_NO_SSLv3 instead. ssl.PROTOCOL_TLSv1_2 Selects TLS version 1.2 as the channel encryption protocol. This is the most modern version, and probably the best choice for maximum protection, if both sides can speak it. Available only with openssl version 1.0.1+. New in version 3.4. Deprecated since version 3.6: OpenSSL has deprecated all version specific protocols. Use the default protocol PROTOCOL_TLS with flags like OP_NO_SSLv3 instead. ssl.OP_ALL Enables workarounds for various bugs present in other SSL implementations. This option is set by default. It does not necessarily set the same flags as OpenSSL’s SSL_OP_ALL constant. New in version 3.2. ssl.OP_NO_SSLv2 Prevents an SSLv2 connection. This option is only applicable in conjunction with PROTOCOL_TLS. It prevents the peers from choosing SSLv2 as the protocol version. New in version 3.2. Deprecated since version 3.6: SSLv2 is deprecated ssl.OP_NO_SSLv3 Prevents an SSLv3 connection. This option is only applicable in conjunction with PROTOCOL_TLS. It prevents the peers from choosing SSLv3 as the protocol version. New in version 3.2. Deprecated since version 3.6: SSLv3 is deprecated ssl.OP_NO_TLSv1 Prevents a TLSv1 connection. This option is only applicable in conjunction with PROTOCOL_TLS. It prevents the peers from choosing TLSv1 as the protocol version. New in version 3.2. Deprecated since version 3.7: The option is deprecated since OpenSSL 1.1.0, use the new SSLContext.minimum_version and SSLContext.maximum_version instead. ssl.OP_NO_TLSv1_1 Prevents a TLSv1.1 connection. This option is only applicable in conjunction with PROTOCOL_TLS. It prevents the peers from choosing TLSv1.1 as the protocol version. Available only with openssl version 1.0.1+. New in version 3.4. Deprecated since version 3.7: The option is deprecated since OpenSSL 1.1.0. ssl.OP_NO_TLSv1_2 Prevents a TLSv1.2 connection. This option is only applicable in conjunction with PROTOCOL_TLS. It prevents the peers from choosing TLSv1.2 as the protocol version. Available only with openssl version 1.0.1+. New in version 3.4. Deprecated since version 3.7: The option is deprecated since OpenSSL 1.1.0. ssl.OP_NO_TLSv1_3 Prevents a TLSv1.3 connection. This option is only applicable in conjunction with PROTOCOL_TLS. It prevents the peers from choosing TLSv1.3 as the protocol version. TLS 1.3 is available with OpenSSL 1.1.1 or later. When Python has been compiled against an older version of OpenSSL, the flag defaults to 0. New in version 3.7. Deprecated since version 3.7: The option is deprecated since OpenSSL 1.1.0. It was added to 2.7.15, 3.6.3 and 3.7.0 for backwards compatibility with OpenSSL 1.0.2. ssl.OP_NO_RENEGOTIATION Disable all renegotiation in TLSv1.2 and earlier. Do not send HelloRequest messages, and ignore renegotiation requests via ClientHello. This option is only available with OpenSSL 1.1.0h and later. New in version 3.7. ssl.OP_CIPHER_SERVER_PREFERENCE Use the server’s cipher ordering preference, rather than the client’s. This option has no effect on client sockets and SSLv2 server sockets. New in version 3.3. ssl.OP_SINGLE_DH_USE Prevents re-use of the same DH key for distinct SSL sessions. This improves forward secrecy but requires more computational resources. This option only applies to server sockets. New in version 3.3. ssl.OP_SINGLE_ECDH_USE Prevents re-use of the same ECDH key for distinct SSL sessions. This improves forward secrecy but requires more computational resources. This option only applies to server sockets. New in version 3.3. ssl.OP_ENABLE_MIDDLEBOX_COMPAT Send dummy Change Cipher Spec (CCS) messages in TLS 1.3 handshake to make a TLS 1.3 connection look more like a TLS 1.2 connection. This option is only available with OpenSSL 1.1.1 and later. New in version 3.8. ssl.OP_NO_COMPRESSION Disable compression on the SSL channel. This is useful if the application protocol supports its own compression scheme. This option is only available with OpenSSL 1.0.0 and later. New in version 3.3. class ssl.Options enum.IntFlag collection of OP_* constants. ssl.OP_NO_TICKET Prevent client side from requesting a session ticket. New in version 3.6. ssl.OP_IGNORE_UNEXPECTED_EOF Ignore unexpected shutdown of TLS connections. This option is only available with OpenSSL 3.0.0 and later. New in version 3.10. ssl.HAS_ALPN Whether the OpenSSL library has built-in support for the Application-Layer Protocol Negotiation TLS extension as described in RFC 7301. New in version 3.5. ssl.HAS_NEVER_CHECK_COMMON_NAME Whether the OpenSSL library has built-in support not checking subject common name and SSLContext.hostname_checks_common_name is writeable. New in version 3.7. ssl.HAS_ECDH Whether the OpenSSL library has built-in support for the Elliptic Curve-based Diffie-Hellman key exchange. This should be true unless the feature was explicitly disabled by the distributor. New in version 3.3. ssl.HAS_SNI Whether the OpenSSL library has built-in support for the Server Name Indication extension (as defined in RFC 6066). New in version 3.2. ssl.HAS_NPN Whether the OpenSSL library has built-in support for the Next Protocol Negotiation as described in the Application Layer Protocol Negotiation. When true, you can use the SSLContext.set_npn_protocols() method to advertise which protocols you want to support. New in version 3.3. ssl.HAS_SSLv2 Whether the OpenSSL library has built-in support for the SSL 2.0 protocol. New in version 3.7. ssl.HAS_SSLv3 Whether the OpenSSL library has built-in support for the SSL 3.0 protocol. New in version 3.7. ssl.HAS_TLSv1 Whether the OpenSSL library has built-in support for the TLS 1.0 protocol. New in version 3.7. ssl.HAS_TLSv1_1 Whether the OpenSSL library has built-in support for the TLS 1.1 protocol. New in version 3.7. ssl.HAS_TLSv1_2 Whether the OpenSSL library has built-in support for the TLS 1.2 protocol. New in version 3.7. ssl.HAS_TLSv1_3 Whether the OpenSSL library has built-in support for the TLS 1.3 protocol. New in version 3.7. ssl.CHANNEL_BINDING_TYPES List of supported TLS channel binding types. Strings in this list can be used as arguments to SSLSocket.get_channel_binding(). New in version 3.3. ssl.OPENSSL_VERSION The version string of the OpenSSL library loaded by the interpreter: >>> ssl.OPENSSL_VERSION 'OpenSSL 1.0.2k 26 Jan 2017' New in version 3.2. ssl.OPENSSL_VERSION_INFO A tuple of five integers representing version information about the OpenSSL library: >>> ssl.OPENSSL_VERSION_INFO (1, 0, 2, 11, 15) New in version 3.2. ssl.OPENSSL_VERSION_NUMBER The raw version number of the OpenSSL library, as a single integer: >>> ssl.OPENSSL_VERSION_NUMBER 268443839 >>> hex(ssl.OPENSSL_VERSION_NUMBER) '0x100020bf' New in version 3.2. ssl.ALERT_DESCRIPTION_HANDSHAKE_FAILURE ssl.ALERT_DESCRIPTION_INTERNAL_ERROR ALERT_DESCRIPTION_* Alert Descriptions from RFC 5246 and others. The IANA TLS Alert Registry contains this list and references to the RFCs where their meaning is defined. Used as the return value of the callback function in SSLContext.set_servername_callback(). New in version 3.4. class ssl.AlertDescription enum.IntEnum collection of ALERT_DESCRIPTION_* constants. New in version 3.6. Purpose.SERVER_AUTH Option for create_default_context() and SSLContext.load_default_certs(). This value indicates that the context may be used to authenticate Web servers (therefore, it will be used to create client-side sockets). New in version 3.4. Purpose.CLIENT_AUTH Option for create_default_context() and SSLContext.load_default_certs(). This value indicates that the context may be used to authenticate Web clients (therefore, it will be used to create server-side sockets). New in version 3.4. class ssl.SSLErrorNumber enum.IntEnum collection of SSL_ERROR_* constants. New in version 3.6. class ssl.TLSVersion enum.IntEnum collection of SSL and TLS versions for SSLContext.maximum_version and SSLContext.minimum_version. New in version 3.7. TLSVersion.MINIMUM_SUPPORTED TLSVersion.MAXIMUM_SUPPORTED 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. TLSVersion.SSLv3 TLSVersion.TLSv1 TLSVersion.TLSv1_1 TLSVersion.TLSv1_2 TLSVersion.TLSv1_3 SSL 3.0 to TLS 1.3. SSL Sockets class ssl.SSLSocket(socket.socket) SSL sockets provide the following methods of Socket Objects: accept() bind() close() connect() detach() fileno() getpeername(), getsockname() getsockopt(), setsockopt() gettimeout(), settimeout(), setblocking() listen() makefile() recv(), recv_into() (but passing a non-zero flags argument is not allowed) send(), sendall() (with the same limitation) sendfile() (but os.sendfile will be used for plain-text sockets only, else send() will be used) shutdown() 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. SSL sockets also have the following additional methods and attributes: SSLSocket.read(len=1024, buffer=None) 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(). SSLSocket.write(buf) 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(). Note The read() and write() methods are the low-level methods that read and write unencrypted, application-level data and decrypt/encrypt it to encrypted, wire-level data. These methods require an active SSL connection, i.e. the handshake was completed and SSLSocket.unwrap() was not called. Normally you should use the socket API methods like recv() and send() instead of these methods. SSLSocket.do_handshake() 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. SSLSocket.getpeercert(binary_form=False) 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: {'issuer': ((('countryName', 'IL'),), (('organizationName', 'StartCom Ltd.'),), (('organizationalUnitName', 'Secure Digital Certificate Signing'),), (('commonName', 'StartCom Class 2 Primary Intermediate Server CA'),)), 'notAfter': 'Nov 22 08:15:19 2013 GMT', 'notBefore': 'Nov 21 03:09:52 2011 GMT', 'serialNumber': '95F0', 'subject': ((('description', '571208-SLe257oHY9fVQ07Z'),), (('countryName', 'US'),), (('stateOrProvinceName', 'California'),), (('localityName', 'San Francisco'),), (('organizationName', 'Electronic Frontier Foundation, Inc.'),), (('commonName', '*.eff.org'),), (('emailAddress', 'hostmaster@eff.org'),)), 'subjectAltName': (('DNS', '*.eff.org'), ('DNS', 'eff.org')), 'version': 3} 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: for a client SSL socket, the server will always provide a certificate, regardless of whether validation was required; for a server SSL socket, the client will only provide a certificate when requested by the server; therefore getpeercert() will return None if you used CERT_NONE (rather than CERT_OPTIONAL or CERT_REQUIRED). 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. SSLSocket.cipher() 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. SSLSocket.shared_ciphers() 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. SSLSocket.compression() 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. SSLSocket.get_channel_binding(cb_type="tls-unique") 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. SSLSocket.selected_alpn_protocol() 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. SSLSocket.selected_npn_protocol() 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. SSLSocket.unwrap() 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. SSLSocket.verify_client_post_handshake() 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. SSLSocket.version() 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. SSLSocket.pending() Returns the number of already decrypted bytes available for read, pending on the connection. SSLSocket.context 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. SSLSocket.server_side A boolean which is True for server-side sockets and False for client-side sockets. New in version 3.2. SSLSocket.server_hostname 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"). SSLSocket.session 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. SSLSocket.session_reused New in version 3.6. SSL Contexts New in version 3.2. An SSL context holds various data longer-lived than single SSL connections, such as SSL configuration options, certificate(s) and private key(s). It also manages a cache of SSL sessions for server-side sockets, in order to speed up repeated connections from the same clients. class ssl.SSLContext(protocol=PROTOCOL_TLS) Create a new SSL context. You may pass protocol which must be one of the PROTOCOL_* constants defined in this module. The parameter specifies which version of the SSL protocol to use. Typically, the server chooses a particular protocol version, and the client must adapt to the server’s choice. Most of the versions are not interoperable with the other versions. If not specified, the default is PROTOCOL_TLS; it provides the most compatibility with other versions. Here’s a table showing which versions in a client (down the side) can connect to which versions in a server (along the top): client / server SSLv2 SSLv3 TLS 3 TLSv1 TLSv1.1 TLSv1.2 SSLv2 yes no no 1 no no no SSLv3 no yes no 2 no no no TLS (SSLv23) 3 no 1 no 2 yes yes yes yes TLSv1 no no yes yes no no TLSv1.1 no no yes no yes no TLSv1.2 no no yes no no yes Footnotes 1(1,2) SSLContext disables SSLv2 with OP_NO_SSLv2 by default. 2(1,2) SSLContext disables SSLv3 with OP_NO_SSLv3 by default. 3(1,2) TLS 1.3 protocol will be available with PROTOCOL_TLS in OpenSSL >= 1.1.1. There is no dedicated PROTOCOL constant for just TLS 1.3. See also create_default_context() lets the ssl module choose security settings for a given purpose. Changed in version 3.6: The context is created with secure default values. The options OP_NO_COMPRESSION, OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE, OP_SINGLE_ECDH_USE, OP_NO_SSLv2 (except for PROTOCOL_SSLv2), and OP_NO_SSLv3 (except for PROTOCOL_SSLv3) are set by default. The initial cipher suite list contains only HIGH ciphers, no NULL ciphers and no MD5 ciphers (except for PROTOCOL_SSLv2). SSLContext objects have the following methods and attributes: SSLContext.cert_store_stats() Get statistics about quantities of loaded X.509 certificates, count of X.509 certificates flagged as CA certificates and certificate revocation lists as dictionary. Example for a context with one CA cert and one other cert: >>> context.cert_store_stats() {'crl': 0, 'x509_ca': 1, 'x509': 2} New in version 3.4. SSLContext.load_cert_chain(certfile, keyfile=None, password=None) Load a private key and the corresponding certificate. The certfile string must be the path to a single file in PEM format containing the certificate as well as any number of CA certificates needed to establish the certificate’s authenticity. The keyfile string, if present, must point to a file containing the private key in. Otherwise the private key will be taken from certfile as well. See the discussion of Certificates for more information on how the certificate is stored in the certfile. The password argument may be a function to call to get the password for decrypting the private key. It will only be called if the private key is encrypted and a password is necessary. It will be called with no arguments, and it should return a string, bytes, or bytearray. If the return value is a string it will be encoded as UTF-8 before using it to decrypt the key. Alternatively a string, bytes, or bytearray value may be supplied directly as the password argument. It will be ignored if the private key is not encrypted and no password is needed. If the password argument is not specified and a password is required, OpenSSL’s built-in password prompting mechanism will be used to interactively prompt the user for a password. An SSLError is raised if the private key doesn’t match with the certificate. Changed in version 3.3: New optional argument password. SSLContext.load_default_certs(purpose=Purpose.SERVER_AUTH) Load a set of default “certification authority” (CA) certificates from default locations. On Windows it loads CA certs from the CA and ROOT system stores. On other systems it calls SSLContext.set_default_verify_paths(). In the future the method may load CA certificates from other locations, too. The purpose flag specifies what kind of CA certificates are loaded. The default settings Purpose.SERVER_AUTH loads certificates, that are flagged and trusted for TLS web server authentication (client side sockets). Purpose.CLIENT_AUTH loads CA certificates for client certificate verification on the server side. New in version 3.4. SSLContext.load_verify_locations(cafile=None, capath=None, cadata=None) Load a set of “certification authority” (CA) certificates used to validate other peers’ certificates when verify_mode is other than CERT_NONE. At least one of cafile or capath must be specified. This method can also load certification revocation lists (CRLs) in PEM or DER format. In order to make use of CRLs, SSLContext.verify_flags must be configured properly. The cafile string, if present, is the path to a file of concatenated CA certificates in PEM format. See the discussion of Certificates for more information about how to arrange the certificates in this file. The capath string, if present, is the path to a directory containing several CA certificates in PEM format, following an OpenSSL specific layout. The cadata object, if present, is either an ASCII string of one or more PEM-encoded certificates or a bytes-like object of DER-encoded certificates. Like with capath extra lines around PEM-encoded certificates are ignored but at least one certificate must be present. Changed in version 3.4: New optional argument cadata SSLContext.get_ca_certs(binary_form=False) Get a list of loaded “certification authority” (CA) certificates. If the binary_form parameter is False each list entry is a dict like the output of SSLSocket.getpeercert(). Otherwise the method returns a list of DER-encoded certificates. The returned list does not contain certificates from capath unless a certificate was requested and loaded by a SSL connection. Note Certificates in a capath directory aren’t loaded unless they have been used at least once. New in version 3.4. SSLContext.get_ciphers() Get a list of enabled ciphers. The list is in order of cipher priority. See SSLContext.set_ciphers(). Example: >>> ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) >>> ctx.set_ciphers('ECDHE+AESGCM:!ECDSA') >>> ctx.get_ciphers() # OpenSSL 1.0.x [{'alg_bits': 256, 'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=RSA ' 'Enc=AESGCM(256) Mac=AEAD', 'id': 50380848, 'name': 'ECDHE-RSA-AES256-GCM-SHA384', 'protocol': 'TLSv1/SSLv3', 'strength_bits': 256}, {'alg_bits': 128, 'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA ' 'Enc=AESGCM(128) Mac=AEAD', 'id': 50380847, 'name': 'ECDHE-RSA-AES128-GCM-SHA256', 'protocol': 'TLSv1/SSLv3', 'strength_bits': 128}] On OpenSSL 1.1 and newer the cipher dict contains additional fields: >>> ctx.get_ciphers() # OpenSSL 1.1+ [{'aead': True, 'alg_bits': 256, 'auth': 'auth-rsa', 'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=RSA ' 'Enc=AESGCM(256) Mac=AEAD', 'digest': None, 'id': 50380848, 'kea': 'kx-ecdhe', 'name': 'ECDHE-RSA-AES256-GCM-SHA384', 'protocol': 'TLSv1.2', 'strength_bits': 256, 'symmetric': 'aes-256-gcm'}, {'aead': True, 'alg_bits': 128, 'auth': 'auth-rsa', 'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA ' 'Enc=AESGCM(128) Mac=AEAD', 'digest': None, 'id': 50380847, 'kea': 'kx-ecdhe', 'name': 'ECDHE-RSA-AES128-GCM-SHA256', 'protocol': 'TLSv1.2', 'strength_bits': 128, 'symmetric': 'aes-128-gcm'}] Availability: OpenSSL 1.0.2+. New in version 3.6. SSLContext.set_default_verify_paths() 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. SSLContext.set_ciphers(ciphers) 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(). SSLContext.set_alpn_protocols(protocols) 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. SSLContext.set_npn_protocols(protocols) 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. SSLContext.sni_callback 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. SSLContext.set_servername_callback(server_name_callback) 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. SSLContext.load_dh_params(dhfile) Load the key generation parameters for Diffie-Hellman (DH) key exchange. Using DH key exchange improves forward secrecy at the expense of computational resources (both on the server and on the client). The dhfile parameter should be the path to a file containing DH parameters in PEM format. This setting doesn’t apply to client sockets. You can also use the OP_SINGLE_DH_USE option to further improve security. New in version 3.3. SSLContext.set_ecdh_curve(curve_name) 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 SSL/TLS & Perfect Forward Secrecy Vincent Bernat. SSLContext.wrap_socket(sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True, server_hostname=None, session=None) 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. SSLContext.sslsocket_class 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. SSLContext.wrap_bio(incoming, outgoing, server_side=False, server_hostname=None, session=None) 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. SSLContext.sslobject_class 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. SSLContext.session_stats() 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: >>> stats = context.session_stats() >>> stats['hits'], stats['misses'] (0, 0) SSLContext.check_hostname Whether to match the peer cert’s hostname in SSLSocket.do_handshake(). The context’s verify_mode must be set to CERT_OPTIONAL or CERT_REQUIRED, and you must pass server_hostname to wrap_socket() in order to match the hostname. Enabling hostname checking automatically sets verify_mode from CERT_NONE to CERT_REQUIRED. It cannot be set back to CERT_NONE as long as hostname checking is enabled. The PROTOCOL_TLS_CLIENT protocol enables hostname checking by default. With other protocols, hostname checking must be enabled explicitly. Example: import socket, ssl context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) context.verify_mode = ssl.CERT_REQUIRED context.check_hostname = True context.load_default_certs() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssl_sock = context.wrap_socket(s, server_hostname='www.verisign.com') ssl_sock.connect(('www.verisign.com', 443)) New in version 3.4. Changed in version 3.7: verify_mode is now automatically changed to CERT_REQUIRED when hostname checking is enabled and verify_mode is CERT_NONE. Previously the same operation would have failed with a ValueError. Note This features requires OpenSSL 0.9.8f or newer. SSLContext.keylog_filename Write TLS keys to a keylog file, whenever key material is generated or received. The keylog file is designed for debugging purposes only. The file format is specified by NSS and used by many traffic analyzers such as Wireshark. The log file is opened in append-only mode. Writes are synchronized between threads, but not between processes. New in version 3.8. Note This features requires OpenSSL 1.1.1 or newer. SSLContext.maximum_version A TLSVersion enum member representing the highest supported TLS version. The value defaults to TLSVersion.MAXIMUM_SUPPORTED. The attribute is read-only for protocols other than PROTOCOL_TLS, PROTOCOL_TLS_CLIENT, and PROTOCOL_TLS_SERVER. The attributes maximum_version, minimum_version and SSLContext.options all affect the supported SSL and TLS versions of the context. The implementation does not prevent invalid combination. For example a context with OP_NO_TLSv1_2 in options and maximum_version set to TLSVersion.TLSv1_2 will not be able to establish a TLS 1.2 connection. Note This attribute is not available unless the ssl module is compiled with OpenSSL 1.1.0g or newer. New in version 3.7. SSLContext.minimum_version Like SSLContext.maximum_version except it is the lowest supported version or TLSVersion.MINIMUM_SUPPORTED. Note This attribute is not available unless the ssl module is compiled with OpenSSL 1.1.0g or newer. New in version 3.7. SSLContext.num_tickets Control the number of TLS 1.3 session tickets of a TLS_PROTOCOL_SERVER context. The setting has no impact on TLS 1.0 to 1.2 connections. Note This attribute is not available unless the ssl module is compiled with OpenSSL 1.1.1 or newer. New in version 3.8. SSLContext.options 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: >>> ssl.create_default_context().options <Options.OP_ALL|OP_NO_SSLv3|OP_NO_SSLv2|OP_NO_COMPRESSION: 2197947391> SSLContext.post_handshake_auth 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. SSLContext.protocol The protocol version chosen when constructing the context. This attribute is read-only. SSLContext.hostname_checks_common_name Whether check_hostname falls back to verify the cert’s subject common name in the absence of a subject alternative name extension (default: true). Note Only writeable with OpenSSL 1.1.0 or higher. New in version 3.7. Changed in version 3.9.3: The flag had no effect with OpenSSL before version 1.1.1k. Python 3.8.9, 3.9.3, and 3.10 include workarounds for previous versions. SSLContext.verify_flags 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: >>> ssl.create_default_context().verify_flags <VerifyFlags.VERIFY_X509_TRUSTED_FIRST: 32768> SSLContext.verify_mode 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: >>> ssl.create_default_context().verify_mode <VerifyMode.CERT_REQUIRED: 2> Certificates Certificates in general are part of a public-key / private-key system. In this system, each principal, (which may be a machine, or a person, or an organization) is assigned a unique two-part encryption key. One part of the key is public, and is called the public key; the other part is kept secret, and is called the private key. The two parts are related, in that if you encrypt a message with one of the parts, you can decrypt it with the other part, and only with the other part. A certificate contains information about two principals. It contains the name of a subject, and the subject’s public key. It also contains a statement by a second principal, the issuer, that the subject is who they claim to be, and that this is indeed the subject’s public key. The issuer’s statement is signed with the issuer’s private key, which only the issuer knows. However, anyone can verify the issuer’s statement by finding the issuer’s public key, decrypting the statement with it, and comparing it to the other information in the certificate. The certificate also contains information about the time period over which it is valid. This is expressed as two fields, called “notBefore” and “notAfter”. In the Python use of certificates, a client or server can use a certificate to prove who they are. The other side of a network connection can also be required to produce a certificate, and that certificate can be validated to the satisfaction of the client or server that requires such validation. The connection attempt can be set to raise an exception if the validation fails. Validation is done automatically, by the underlying OpenSSL framework; the application need not concern itself with its mechanics. But the application does usually need to provide sets of certificates to allow this process to take place. Python uses files to contain certificates. They should be formatted as “PEM” (see RFC 1422), which is a base-64 encoded form wrapped with a header line and a footer line: -----BEGIN CERTIFICATE----- ... (certificate in base64 PEM encoding) ... -----END CERTIFICATE----- Certificate chains The Python files which contain certificates can contain a sequence of certificates, sometimes called a certificate chain. This chain should start with the specific certificate for the principal who “is” the client or server, and then the certificate for the issuer of that certificate, and then the certificate for the issuer of that certificate, and so on up the chain till you get to a certificate which is self-signed, that is, a certificate which has the same subject and issuer, sometimes called a root certificate. The certificates should just be concatenated together in the certificate file. For example, suppose we had a three certificate chain, from our server certificate to the certificate of the certification authority that signed our server certificate, to the root certificate of the agency which issued the certification authority’s certificate: -----BEGIN CERTIFICATE----- ... (certificate for your server)... -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- ... (the certificate for the CA)... -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- ... (the root certificate for the CA's issuer)... -----END CERTIFICATE----- CA certificates If you are going to require validation of the other side of the connection’s certificate, you need to provide a “CA certs” file, filled with the certificate chains for each issuer you are willing to trust. Again, this file just contains these chains concatenated together. For validation, Python will use the first chain it finds in the file which matches. The platform’s certificates file can be used by calling SSLContext.load_default_certs(), this is done automatically with create_default_context(). Combined key and certificate Often the private key is stored in the same file as the certificate; in this case, only the certfile parameter to SSLContext.load_cert_chain() and wrap_socket() needs to be passed. If the private key is stored with the certificate, it should come before the first certificate in the certificate chain: -----BEGIN RSA PRIVATE KEY----- ... (private key in base64 encoding) ... -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- ... (certificate in base64 PEM encoding) ... -----END CERTIFICATE----- Self-signed certificates If you are going to create a server that provides SSL-encrypted connection services, you will need to acquire a certificate for that service. There are many ways of acquiring appropriate certificates, such as buying one from a certification authority. Another common practice is to generate a self-signed certificate. The simplest way to do this is with the OpenSSL package, using something like the following: % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem Generating a 1024 bit RSA private key .......++++++ .............................++++++ writing new private key to 'cert.pem' ----- You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [AU]:US State or Province Name (full name) [Some-State]:MyState Locality Name (eg, city) []:Some City Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc. Organizational Unit Name (eg, section) []:My Group Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com Email Address []:ops@myserver.mygroup.myorganization.com % The disadvantage of a self-signed certificate is that it is its own root certificate, and no one else will have it in their cache of known (and trusted) root certificates. Examples Testing for SSL support To test for the presence of SSL support in a Python installation, user code should use the following idiom: try: import ssl except ImportError: pass else: ... # do something that requires SSL support Client-side operation This example creates a SSL context with the recommended security settings for client sockets, including automatic certificate verification: >>> context = ssl.create_default_context() If you prefer to tune security settings yourself, you might create a context from scratch (but beware that you might not get the settings right): >>> context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt") (this snippet assumes your operating system places a bundle of all CA certificates in /etc/ssl/certs/ca-bundle.crt; if not, you’ll get an error and have to adjust the location) The PROTOCOL_TLS_CLIENT protocol configures the context for cert validation and hostname verification. verify_mode is set to CERT_REQUIRED and check_hostname is set to True. All other protocols create SSL contexts with insecure defaults. When you use the context to connect to a server, CERT_REQUIRED and check_hostname validate the server certificate: it ensures that the server certificate was signed with one of the CA certificates, checks the signature for correctness, and verifies other properties like validity and identity of the hostname: >>> conn = context.wrap_socket(socket.socket(socket.AF_INET), ... server_hostname="www.python.org") >>> conn.connect(("www.python.org", 443)) You may then fetch the certificate: >>> cert = conn.getpeercert() Visual inspection shows that the certificate does identify the desired service (that is, the HTTPS host www.python.org): >>> pprint.pprint(cert) {'OCSP': ('http://ocsp.digicert.com',), 'caIssuers': ('http://cacerts.digicert.com/DigiCertSHA2ExtendedValidationServerCA.crt',), 'crlDistributionPoints': ('http://crl3.digicert.com/sha2-ev-server-g1.crl', 'http://crl4.digicert.com/sha2-ev-server-g1.crl'), 'issuer': ((('countryName', 'US'),), (('organizationName', 'DigiCert Inc'),), (('organizationalUnitName', 'www.digicert.com'),), (('commonName', 'DigiCert SHA2 Extended Validation Server CA'),)), 'notAfter': 'Sep 9 12:00:00 2016 GMT', 'notBefore': 'Sep 5 00:00:00 2014 GMT', 'serialNumber': '01BB6F00122B177F36CAB49CEA8B6B26', 'subject': ((('businessCategory', 'Private Organization'),), (('1.3.6.1.4.1.311.60.2.1.3', 'US'),), (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),), (('serialNumber', '3359300'),), (('streetAddress', '16 Allen Rd'),), (('postalCode', '03894-4801'),), (('countryName', 'US'),), (('stateOrProvinceName', 'NH'),), (('localityName', 'Wolfeboro'),), (('organizationName', 'Python Software Foundation'),), (('commonName', 'www.python.org'),)), 'subjectAltName': (('DNS', 'www.python.org'), ('DNS', 'python.org'), ('DNS', 'pypi.org'), ('DNS', 'docs.python.org'), ('DNS', 'testpypi.org'), ('DNS', 'bugs.python.org'), ('DNS', 'wiki.python.org'), ('DNS', 'hg.python.org'), ('DNS', 'mail.python.org'), ('DNS', 'packaging.python.org'), ('DNS', 'pythonhosted.org'), ('DNS', 'www.pythonhosted.org'), ('DNS', 'test.pythonhosted.org'), ('DNS', 'us.pycon.org'), ('DNS', 'id.python.org')), 'version': 3} Now the SSL channel is established and the certificate verified, you can proceed to talk with the server: >>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n") >>> pprint.pprint(conn.recv(1024).split(b"\r\n")) [b'HTTP/1.1 200 OK', b'Date: Sat, 18 Oct 2014 18:27:20 GMT', b'Server: nginx', b'Content-Type: text/html; charset=utf-8', b'X-Frame-Options: SAMEORIGIN', b'Content-Length: 45679', b'Accept-Ranges: bytes', b'Via: 1.1 varnish', b'Age: 2188', b'X-Served-By: cache-lcy1134-LCY', b'X-Cache: HIT', b'X-Cache-Hits: 11', b'Vary: Cookie', b'Strict-Transport-Security: max-age=63072000; includeSubDomains', b'Connection: close', b'', b''] See the discussion of Security considerations below. Server-side operation For server operation, typically you’ll need to have a server certificate, and private key, each in a file. You’ll first create a context holding the key and the certificate, so that clients can check your authenticity. Then you’ll open a socket, bind it to a port, call listen() on it, and start waiting for clients to connect: import socket, ssl context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile") bindsocket = socket.socket() bindsocket.bind(('myaddr.mydomain.com', 10023)) bindsocket.listen(5) When a client connects, you’ll call accept() on the socket to get the new socket from the other end, and use the context’s SSLContext.wrap_socket() method to create a server-side SSL socket for the connection: while True: newsocket, fromaddr = bindsocket.accept() connstream = context.wrap_socket(newsocket, server_side=True) try: deal_with_client(connstream) finally: connstream.shutdown(socket.SHUT_RDWR) connstream.close() Then you’ll read data from the connstream and do something with it till you are finished with the client (or the client is finished with you): def deal_with_client(connstream): data = connstream.recv(1024) # empty data means the client is finished with us while data: if not do_something(connstream, data): # we'll assume do_something returns False # when we're finished with client break data = connstream.recv(1024) # finished with client And go back to listening for new client connections (of course, a real server would probably handle each client connection in a separate thread, or put the sockets in non-blocking mode and use an event loop). Notes on non-blocking sockets SSL sockets behave slightly different than regular sockets in non-blocking mode. When working with non-blocking sockets, there are thus several things you need to be aware of: Most SSLSocket methods will raise either SSLWantWriteError or SSLWantReadError instead of BlockingIOError if an I/O operation would block. SSLWantReadError will be raised if a read operation on the underlying socket is necessary, and SSLWantWriteError for a write operation on the underlying socket. Note that attempts to write to an SSL socket may require reading from the underlying socket first, and attempts to read from the SSL socket may require a prior write to the underlying socket. Changed in version 3.5: In earlier Python versions, the SSLSocket.send() method returned zero instead of raising SSLWantWriteError or SSLWantReadError. Calling select() tells you that the OS-level socket can be read from (or written to), but it does not imply that there is sufficient data at the upper SSL layer. For example, only part of an SSL frame might have arrived. Therefore, you must be ready to handle SSLSocket.recv() and SSLSocket.send() failures, and retry after another call to select(). Conversely, since the SSL layer has its own framing, a SSL socket may still have data available for reading without select() being aware of it. Therefore, you should first call SSLSocket.recv() to drain any potentially available data, and then only block on a select() call if still necessary. (of course, similar provisions apply when using other primitives such as poll(), or those in the selectors module) The SSL handshake itself will be non-blocking: the SSLSocket.do_handshake() method has to be retried until it returns successfully. Here is a synopsis using select() to wait for the socket’s readiness: while True: try: sock.do_handshake() break except ssl.SSLWantReadError: select.select([sock], [], []) except ssl.SSLWantWriteError: select.select([], [sock], []) See also The asyncio module supports non-blocking SSL sockets and provides a higher level API. It polls for events using the selectors module and handles SSLWantWriteError, SSLWantReadError and BlockingIOError exceptions. It runs the SSL handshake asynchronously as well. Memory BIO Support New in version 3.5. Ever since the SSL module was introduced in Python 2.6, the SSLSocket class has provided two related but distinct areas of functionality: SSL protocol handling Network IO The network IO API is identical to that provided by socket.socket, from which SSLSocket also inherits. This allows an SSL socket to be used as a drop-in replacement for a regular socket, making it very easy to add SSL support to an existing application. Combining SSL protocol handling and network IO usually works well, but there are some cases where it doesn’t. An example is async IO frameworks that want to use a different IO multiplexing model than the “select/poll on a file descriptor” (readiness based) model that is assumed by socket.socket and by the internal OpenSSL socket IO routines. This is mostly relevant for platforms like Windows where this model is not efficient. For this purpose, a reduced scope variant of SSLSocket called SSLObject is provided. class ssl.SSLObject 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: context server_side server_hostname session session_reused read() write() getpeercert() selected_alpn_protocol() selected_npn_protocol() cipher() shared_ciphers() compression() pending() do_handshake() verify_client_post_handshake() unwrap() get_channel_binding() version() When compared to SSLSocket, this object lacks the following features: Any form of network IO; recv() and send() read and write only to the underlying MemoryBIO buffers. There is no do_handshake_on_connect machinery. You must always manually call do_handshake() to start the handshake. There is no handling of suppress_ragged_eofs. All end-of-file conditions that are in violation of the protocol are reported via the SSLEOFError exception. The method unwrap() call does not return anything, unlike for an SSL socket where it returns the underlying socket. The server_name_callback callback passed to SSLContext.set_servername_callback() will get an SSLObject instance instead of a SSLSocket instance as its first parameter. Some notes related to the use of SSLObject: All IO on an SSLObject is non-blocking. This means that for example read() will raise an SSLWantReadError if it needs more data than the incoming BIO has available. There is no module-level wrap_bio() call like there is for wrap_socket(). An SSLObject is always created via an SSLContext. 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. An SSLObject communicates with the outside world using memory buffers. The class MemoryBIO provides a memory buffer that can be used for this purpose. It wraps an OpenSSL memory BIO (Basic IO) object: class ssl.MemoryBIO A memory buffer that can be used to pass data between Python and an SSL protocol instance. pending Return the number of bytes currently in the memory buffer. eof A boolean indicating whether the memory BIO is current at the end-of-file position. read(n=-1) Read up to n bytes from the memory buffer. If n is not specified or negative, all bytes are returned. write(buf) Write the bytes from buf to the memory BIO. The buf argument must be an object supporting the buffer protocol. The return value is the number of bytes written, which is always equal to the length of buf. write_eof() Write an EOF marker to the memory BIO. After this method has been called, it is illegal to call write(). The attribute eof will become true after all data currently in the buffer has been read. SSL session New in version 3.6. class ssl.SSLSession Session object used by session. id time timeout ticket_lifetime_hint has_ticket Security considerations Best defaults For client use, if you don’t have any special requirements for your security policy, it is highly recommended that you use the create_default_context() function to create your SSL context. It will load the system’s trusted CA certificates, enable certificate validation and hostname checking, and try to choose reasonably secure protocol and cipher settings. For example, here is how you would use the smtplib.SMTP class to create a trusted, secure connection to a SMTP server: >>> import ssl, smtplib >>> smtp = smtplib.SMTP("mail.python.org", port=587) >>> context = ssl.create_default_context() >>> smtp.starttls(context=context) (220, b'2.0.0 Ready to start TLS') If a client certificate is needed for the connection, it can be added with SSLContext.load_cert_chain(). By contrast, if you create the SSL context by calling the SSLContext constructor yourself, it will not have certificate validation nor hostname checking enabled by default. If you do so, please read the paragraphs below to achieve a good security level. Manual settings Verifying certificates When calling the SSLContext constructor directly, CERT_NONE is the default. Since it does not authenticate the other peer, it can be insecure, especially in client mode where most of time you would like to ensure the authenticity of the server you’re talking to. Therefore, when in client mode, it is highly recommended to use CERT_REQUIRED. However, it is in itself not sufficient; you also have to check that the server certificate, which can be obtained by calling SSLSocket.getpeercert(), matches the desired service. For many protocols and applications, the service can be identified by the hostname; in this case, the match_hostname() function can be used. This common check is automatically performed when SSLContext.check_hostname is enabled. Changed in version 3.7: Hostname matchings is now performed by OpenSSL. Python no longer uses match_hostname(). In server mode, if you want to authenticate your clients using the SSL layer (rather than using a higher-level authentication mechanism), you’ll also have to specify CERT_REQUIRED and similarly check the client certificate. Protocol versions SSL versions 2 and 3 are considered insecure and are therefore dangerous to use. If you want maximum compatibility between clients and servers, it is recommended to use PROTOCOL_TLS_CLIENT or PROTOCOL_TLS_SERVER as the protocol version. SSLv2 and SSLv3 are disabled by default. >>> client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) >>> client_context.options |= ssl.OP_NO_TLSv1 >>> client_context.options |= ssl.OP_NO_TLSv1_1 The SSL context created above will only allow TLSv1.2 and later (if supported by your system) connections to a server. PROTOCOL_TLS_CLIENT implies certificate validation and hostname checks by default. You have to load certificates into the context. Cipher selection If you have advanced security requirements, fine-tuning of the ciphers enabled when negotiating a SSL session is possible through the SSLContext.set_ciphers() method. Starting from Python 3.2.3, the ssl module disables certain weak ciphers by default, but you may want to further restrict the cipher choice. Be sure to read OpenSSL’s documentation about the cipher list format. If you want to check which ciphers are enabled by a given cipher list, use SSLContext.get_ciphers() or the openssl ciphers command on your system. Multi-processing If using this module as part of a multi-processed application (using, for example the multiprocessing or concurrent.futures modules), be aware that OpenSSL’s internal random number generator does not properly handle forked processes. Applications must change the PRNG state of the parent process if they use any SSL feature with os.fork(). Any successful call of RAND_add(), RAND_bytes() or RAND_pseudo_bytes() is sufficient. TLS 1.3 New in version 3.7. Python has provisional and experimental support for TLS 1.3 with OpenSSL 1.1.1. The new protocol behaves slightly differently than previous version of TLS/SSL. Some new TLS 1.3 features are not yet available. TLS 1.3 uses a disjunct set of cipher suites. All AES-GCM and ChaCha20 cipher suites are enabled by default. The method SSLContext.set_ciphers() cannot enable or disable any TLS 1.3 ciphers yet, but SSLContext.get_ciphers() returns them. Session tickets are no longer sent as part of the initial handshake and are handled differently. SSLSocket.session and SSLSession are not compatible with TLS 1.3. Client-side certificates are also no longer verified during the initial handshake. A server can request a certificate at any time. Clients process certificate requests while they send or receive application data from the server. TLS 1.3 features like early data, deferred TLS client cert request, signature algorithm configuration, and rekeying are not supported yet. LibreSSL support LibreSSL is a fork of OpenSSL 1.0.1. The ssl module has limited support for LibreSSL. Some features are not available when the ssl module is compiled with LibreSSL. LibreSSL >= 2.6.1 no longer supports NPN. The methods SSLContext.set_npn_protocols() and SSLSocket.selected_npn_protocol() are not available. SSLContext.set_default_verify_paths() ignores the env vars SSL_CERT_FILE and SSL_CERT_PATH although get_default_verify_paths() still reports them. See also Class socket.socket Documentation of underlying socket class SSL/TLS Strong Encryption: An Introduction Intro from the Apache HTTP Server documentation RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management Steve Kent RFC 4086: Randomness Requirements for Security Donald E., Jeffrey I. Schiller RFC 5280: Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile D. Cooper RFC 5246: The Transport Layer Security (TLS) Protocol Version 1.2 T. Dierks et. al. RFC 6066: Transport Layer Security (TLS) Extensions D. Eastlake IANA TLS: Transport Layer Security (TLS) Parameters IANA RFC 7525: Recommendations for Secure Use of Transport Layer Security (TLS) and Datagram Transport Layer Security (DTLS) IETF Mozilla’s Server Side TLS recommendations Mozilla
doc_1386
Get parameters for this estimator. Parameters deepbool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns paramsdict Parameter names mapped to their values.
doc_1387
Set the rectangle width. Parameters wfloat
doc_1388
This function is used to turn the capture of warnings by logging on and off. If capture is True, warnings issued by the warnings module will be redirected to the logging system. Specifically, a warning will be formatted using warnings.formatwarning() and the resulting string logged to a logger named 'py.warnings' with a severity of WARNING. If capture is False, the redirection of warnings to the logging system will stop, and warnings will be redirected to their original destinations (i.e. those in effect before captureWarnings(True) was called).
doc_1389
Object that when printed, prints the message “Type license() to see the full license text”, and when called, displays the full license text in a pager-like fashion (one screen at a time).
doc_1390
Get the width, height, and descent (offset from the bottom to the baseline), in display coords, of the string s with FontProperties prop.
doc_1391
logging.config.dictConfig(config) Takes the logging configuration from a dictionary. The contents of this dictionary are described in Configuration dictionary schema below. If an error is encountered during configuration, this function will raise a ValueError, TypeError, AttributeError or ImportError with a suitably descriptive message. The following is a (possibly incomplete) list of conditions which will raise an error: A level which is not a string or which is a string not corresponding to an actual logging level. A propagate value which is not a boolean. An id which does not have a corresponding destination. A non-existent handler id found during an incremental call. An invalid logger name. Inability to resolve to an internal or external object. Parsing is performed by the DictConfigurator class, whose constructor is passed the dictionary used for configuration, and has a configure() method. The logging.config module has a callable attribute dictConfigClass which is initially set to DictConfigurator. You can replace the value of dictConfigClass with a suitable implementation of your own. dictConfig() calls dictConfigClass passing the specified dictionary, and then calls the configure() method on the returned object to put the configuration into effect: def dictConfig(config): dictConfigClass(config).configure() For example, a subclass of DictConfigurator could call DictConfigurator.__init__() in its own __init__(), then set up custom prefixes which would be usable in the subsequent configure() call. dictConfigClass would be bound to this new subclass, and then dictConfig() could be called exactly as in the default, uncustomized state. New in version 3.2. logging.config.fileConfig(fname, defaults=None, disable_existing_loggers=True) Reads the logging configuration from a configparser-format file. The format of the file should be as described in Configuration file format. This function can be called several times from an application, allowing an end user to select from various pre-canned configurations (if the developer provides a mechanism to present the choices and load the chosen configuration). Parameters fname – A filename, or a file-like object, or an instance derived from RawConfigParser. If a RawConfigParser-derived instance is passed, it is used as is. Otherwise, a Configparser is instantiated, and the configuration read by it from the object passed in fname. If that has a readline() method, it is assumed to be a file-like object and read using read_file(); otherwise, it is assumed to be a filename and passed to read(). defaults – Defaults to be passed to the ConfigParser can be specified in this argument. disable_existing_loggers – If specified as False, loggers which exist when this call is made are left enabled. The default is True because this enables old behaviour in a backward-compatible way. This behaviour is to disable any existing non-root loggers unless they or their ancestors are explicitly named in the logging configuration. Changed in version 3.4: An instance of a subclass of RawConfigParser is now accepted as a value for fname. This facilitates: Use of a configuration file where logging configuration is just part of the overall application configuration. Use of a configuration read from a file, and then modified by the using application (e.g. based on command-line parameters or other aspects of the runtime environment) before being passed to fileConfig. logging.config.listen(port=DEFAULT_LOGGING_CONFIG_PORT, verify=None) Starts up a socket server on the specified port, and listens for new configurations. If no port is specified, the module’s default DEFAULT_LOGGING_CONFIG_PORT is used. Logging configurations will be sent as a file suitable for processing by dictConfig() or fileConfig(). Returns a Thread instance on which you can call start() to start the server, and which you can join() when appropriate. To stop the server, call stopListening(). The verify argument, if specified, should be a callable which should verify whether bytes received across the socket are valid and should be processed. This could be done by encrypting and/or signing what is sent across the socket, such that the verify callable can perform signature verification and/or decryption. The verify callable is called with a single argument - the bytes received across the socket - and should return the bytes to be processed, or None to indicate that the bytes should be discarded. The returned bytes could be the same as the passed in bytes (e.g. when only verification is done), or they could be completely different (perhaps if decryption were performed). To send a configuration to the socket, read in the configuration file and send it to the socket as a sequence of bytes preceded by a four-byte length string packed in binary using struct.pack('>L', n). Note Because portions of the configuration are passed through eval(), use of this function may open its users to a security risk. While the function only binds to a socket on localhost, and so does not accept connections from remote machines, there are scenarios where untrusted code could be run under the account of the process which calls listen(). Specifically, if the process calling listen() runs on a multi-user machine where users cannot trust each other, then a malicious user could arrange to run essentially arbitrary code in a victim user’s process, simply by connecting to the victim’s listen() socket and sending a configuration which runs whatever code the attacker wants to have executed in the victim’s process. This is especially easy to do if the default port is used, but not hard even if a different port is used). To avoid the risk of this happening, use the verify argument to listen() to prevent unrecognised configurations from being applied. Changed in version 3.4: The verify argument was added. Note If you want to send configurations to the listener which don’t disable existing loggers, you will need to use a JSON format for the configuration, which will use dictConfig() for configuration. This method allows you to specify disable_existing_loggers as False in the configuration you send. logging.config.stopListening() Stops the listening server which was created with a call to listen(). This is typically called before calling join() on the return value from listen(). Configuration dictionary schema Describing a logging configuration requires listing the various objects to create and the connections between them; for example, you may create a handler named ‘console’ and then say that the logger named ‘startup’ will send its messages to the ‘console’ handler. These objects aren’t limited to those provided by the logging module because you might write your own formatter or handler class. The parameters to these classes may also need to include external objects such as sys.stderr. The syntax for describing these objects and connections is defined in Object connections below. Dictionary Schema Details The dictionary passed to dictConfig() must contain the following keys: version - to be set to an integer value representing the schema version. The only valid value at present is 1, but having this key allows the schema to evolve while still preserving backwards compatibility. All other keys are optional, but if present they will be interpreted as described below. In all cases below where a ‘configuring dict’ is mentioned, it will be checked for the special '()' key to see if a custom instantiation is required. If so, the mechanism described in User-defined objects below is used to create an instance; otherwise, the context is used to determine what to instantiate. formatters - the corresponding value will be a dict in which each key is a formatter id and each value is a dict describing how to configure the corresponding Formatter instance. The configuring dict is searched for keys format and datefmt (with defaults of None) and these are used to construct a Formatter instance. Changed in version 3.8: a validate key (with default of True) can be added into the formatters section of the configuring dict, this is to validate the format. filters - the corresponding value will be a dict in which each key is a filter id and each value is a dict describing how to configure the corresponding Filter instance. The configuring dict is searched for the key name (defaulting to the empty string) and this is used to construct a logging.Filter instance. handlers - the corresponding value will be a dict in which each key is a handler id and each value is a dict describing how to configure the corresponding Handler instance. The configuring dict is searched for the following keys: class (mandatory). This is the fully qualified name of the handler class. level (optional). The level of the handler. formatter (optional). The id of the formatter for this handler. filters (optional). A list of ids of the filters for this handler. All other keys are passed through as keyword arguments to the handler’s constructor. For example, given the snippet: handlers: console: class : logging.StreamHandler formatter: brief level : INFO filters: [allow_foo] stream : ext://sys.stdout file: class : logging.handlers.RotatingFileHandler formatter: precise filename: logconfig.log maxBytes: 1024 backupCount: 3 the handler with id console is instantiated as a logging.StreamHandler, using sys.stdout as the underlying stream. The handler with id file is instantiated as a logging.handlers.RotatingFileHandler with the keyword arguments filename='logconfig.log', maxBytes=1024, backupCount=3. loggers - the corresponding value will be a dict in which each key is a logger name and each value is a dict describing how to configure the corresponding Logger instance. The configuring dict is searched for the following keys: level (optional). The level of the logger. propagate (optional). The propagation setting of the logger. filters (optional). A list of ids of the filters for this logger. handlers (optional). A list of ids of the handlers for this logger. The specified loggers will be configured according to the level, propagation, filters and handlers specified. root - this will be the configuration for the root logger. Processing of the configuration will be as for any logger, except that the propagate setting will not be applicable. incremental - whether the configuration is to be interpreted as incremental to the existing configuration. This value defaults to False, which means that the specified configuration replaces the existing configuration with the same semantics as used by the existing fileConfig() API. If the specified value is True, the configuration is processed as described in the section on Incremental Configuration. disable_existing_loggers - whether any existing non-root loggers are to be disabled. This setting mirrors the parameter of the same name in fileConfig(). If absent, this parameter defaults to True. This value is ignored if incremental is True. Incremental Configuration It is difficult to provide complete flexibility for incremental configuration. For example, because objects such as filters and formatters are anonymous, once a configuration is set up, it is not possible to refer to such anonymous objects when augmenting a configuration. Furthermore, there is not a compelling case for arbitrarily altering the object graph of loggers, handlers, filters, formatters at run-time, once a configuration is set up; the verbosity of loggers and handlers can be controlled just by setting levels (and, in the case of loggers, propagation flags). Changing the object graph arbitrarily in a safe way is problematic in a multi-threaded environment; while not impossible, the benefits are not worth the complexity it adds to the implementation. Thus, when the incremental key of a configuration dict is present and is True, the system will completely ignore any formatters and filters entries, and process only the level settings in the handlers entries, and the level and propagate settings in the loggers and root entries. Using a value in the configuration dict lets configurations to be sent over the wire as pickled dicts to a socket listener. Thus, the logging verbosity of a long-running application can be altered over time with no need to stop and restart the application. Object connections The schema describes a set of logging objects - loggers, handlers, formatters, filters - which are connected to each other in an object graph. Thus, the schema needs to represent connections between the objects. For example, say that, once configured, a particular logger has attached to it a particular handler. For the purposes of this discussion, we can say that the logger represents the source, and the handler the destination, of a connection between the two. Of course in the configured objects this is represented by the logger holding a reference to the handler. In the configuration dict, this is done by giving each destination object an id which identifies it unambiguously, and then using the id in the source object’s configuration to indicate that a connection exists between the source and the destination object with that id. So, for example, consider the following YAML snippet: formatters: brief: # configuration for formatter with id 'brief' goes here precise: # configuration for formatter with id 'precise' goes here handlers: h1: #This is an id # configuration of handler with id 'h1' goes here formatter: brief h2: #This is another id # configuration of handler with id 'h2' goes here formatter: precise loggers: foo.bar.baz: # other configuration for logger 'foo.bar.baz' handlers: [h1, h2] (Note: YAML used here because it’s a little more readable than the equivalent Python source form for the dictionary.) The ids for loggers are the logger names which would be used programmatically to obtain a reference to those loggers, e.g. foo.bar.baz. The ids for Formatters and Filters can be any string value (such as brief, precise above) and they are transient, in that they are only meaningful for processing the configuration dictionary and used to determine connections between objects, and are not persisted anywhere when the configuration call is complete. The above snippet indicates that logger named foo.bar.baz should have two handlers attached to it, which are described by the handler ids h1 and h2. The formatter for h1 is that described by id brief, and the formatter for h2 is that described by id precise. User-defined objects The schema supports user-defined objects for handlers, filters and formatters. (Loggers do not need to have different types for different instances, so there is no support in this configuration schema for user-defined logger classes.) Objects to be configured are described by dictionaries which detail their configuration. In some places, the logging system will be able to infer from the context how an object is to be instantiated, but when a user-defined object is to be instantiated, the system will not know how to do this. In order to provide complete flexibility for user-defined object instantiation, the user needs to provide a ‘factory’ - a callable which is called with a configuration dictionary and which returns the instantiated object. This is signalled by an absolute import path to the factory being made available under the special key '()'. Here’s a concrete example: formatters: brief: format: '%(message)s' default: format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s' datefmt: '%Y-%m-%d %H:%M:%S' custom: (): my.package.customFormatterFactory bar: baz spam: 99.9 answer: 42 The above YAML snippet defines three formatters. The first, with id brief, is a standard logging.Formatter instance with the specified format string. The second, with id default, has a longer format and also defines the time format explicitly, and will result in a logging.Formatter initialized with those two format strings. Shown in Python source form, the brief and default formatters have configuration sub-dictionaries: { 'format' : '%(message)s' } and: { 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s', 'datefmt' : '%Y-%m-%d %H:%M:%S' } respectively, and as these dictionaries do not contain the special key '()', the instantiation is inferred from the context: as a result, standard logging.Formatter instances are created. The configuration sub-dictionary for the third formatter, with id custom, is: { '()' : 'my.package.customFormatterFactory', 'bar' : 'baz', 'spam' : 99.9, 'answer' : 42 } and this contains the special key '()', which means that user-defined instantiation is wanted. In this case, the specified factory callable will be used. If it is an actual callable it will be used directly - otherwise, if you specify a string (as in the example) the actual callable will be located using normal import mechanisms. The callable will be called with the remaining items in the configuration sub-dictionary as keyword arguments. In the above example, the formatter with id custom will be assumed to be returned by the call: my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42) The key '()' has been used as the special key because it is not a valid keyword parameter name, and so will not clash with the names of the keyword arguments used in the call. The '()' also serves as a mnemonic that the corresponding value is a callable. Access to external objects There are times where a configuration needs to refer to objects external to the configuration, for example sys.stderr. If the configuration dict is constructed using Python code, this is straightforward, but a problem arises when the configuration is provided via a text file (e.g. JSON, YAML). In a text file, there is no standard way to distinguish sys.stderr from the literal string 'sys.stderr'. To facilitate this distinction, the configuration system looks for certain special prefixes in string values and treat them specially. For example, if the literal string 'ext://sys.stderr' is provided as a value in the configuration, then the ext:// will be stripped off and the remainder of the value processed using normal import mechanisms. The handling of such prefixes is done in a way analogous to protocol handling: there is a generic mechanism to look for prefixes which match the regular expression ^(?P<prefix>[a-z]+)://(?P<suffix>.*)$ whereby, if the prefix is recognised, the suffix is processed in a prefix-dependent manner and the result of the processing replaces the string value. If the prefix is not recognised, then the string value will be left as-is. Access to internal objects As well as external objects, there is sometimes also a need to refer to objects in the configuration. This will be done implicitly by the configuration system for things that it knows about. For example, the string value 'DEBUG' for a level in a logger or handler will automatically be converted to the value logging.DEBUG, and the handlers, filters and formatter entries will take an object id and resolve to the appropriate destination object. However, a more generic mechanism is needed for user-defined objects which are not known to the logging module. For example, consider logging.handlers.MemoryHandler, which takes a target argument which is another handler to delegate to. Since the system already knows about this class, then in the configuration, the given target just needs to be the object id of the relevant target handler, and the system will resolve to the handler from the id. If, however, a user defines a my.package.MyHandler which has an alternate handler, the configuration system would not know that the alternate referred to a handler. To cater for this, a generic resolution system allows the user to specify: handlers: file: # configuration of file handler goes here custom: (): my.package.MyHandler alternate: cfg://handlers.file The literal string 'cfg://handlers.file' will be resolved in an analogous way to strings with the ext:// prefix, but looking in the configuration itself rather than the import namespace. The mechanism allows access by dot or by index, in a similar way to that provided by str.format. Thus, given the following snippet: handlers: email: class: logging.handlers.SMTPHandler mailhost: localhost fromaddr: my_app@domain.tld toaddrs: - support_team@domain.tld - dev_team@domain.tld subject: Houston, we have a problem. in the configuration, the string 'cfg://handlers' would resolve to the dict with key handlers, the string 'cfg://handlers.email would resolve to the dict with key email in the handlers dict, and so on. The string 'cfg://handlers.email.toaddrs[1] would resolve to 'dev_team.domain.tld' and the string 'cfg://handlers.email.toaddrs[0]' would resolve to the value 'support_team@domain.tld'. The subject value could be accessed using either 'cfg://handlers.email.subject' or, equivalently, 'cfg://handlers.email[subject]'. The latter form only needs to be used if the key contains spaces or non-alphanumeric characters. If an index value consists only of decimal digits, access will be attempted using the corresponding integer value, falling back to the string value if needed. Given a string cfg://handlers.myhandler.mykey.123, this will resolve to config_dict['handlers']['myhandler']['mykey']['123']. If the string is specified as cfg://handlers.myhandler.mykey[123], the system will attempt to retrieve the value from config_dict['handlers']['myhandler']['mykey'][123], and fall back to config_dict['handlers']['myhandler']['mykey']['123'] if that fails. Import resolution and custom importers Import resolution, by default, uses the builtin __import__() function to do its importing. You may want to replace this with your own importing mechanism: if so, you can replace the importer attribute of the DictConfigurator or its superclass, the BaseConfigurator class. However, you need to be careful because of the way functions are accessed from classes via descriptors. If you are using a Python callable to do your imports, and you want to define it at class level rather than instance level, you need to wrap it with staticmethod(). For example: from importlib import import_module from logging.config import BaseConfigurator BaseConfigurator.importer = staticmethod(import_module) You don’t need to wrap with staticmethod() if you’re setting the import callable on a configurator instance. Configuration file format The configuration file format understood by fileConfig() is based on configparser functionality. The file must contain sections called [loggers], [handlers] and [formatters] which identify by name the entities of each type which are defined in the file. For each such entity, there is a separate section which identifies how that entity is configured. Thus, for a logger named log01 in the [loggers] section, the relevant configuration details are held in a section [logger_log01]. Similarly, a handler called hand01 in the [handlers] section will have its configuration held in a section called [handler_hand01], while a formatter called form01 in the [formatters] section will have its configuration specified in a section called [formatter_form01]. The root logger configuration must be specified in a section called [logger_root]. Note The fileConfig() API is older than the dictConfig() API and does not provide functionality to cover certain aspects of logging. For example, you cannot configure Filter objects, which provide for filtering of messages beyond simple integer levels, using fileConfig(). If you need to have instances of Filter in your logging configuration, you will need to use dictConfig(). Note that future enhancements to configuration functionality will be added to dictConfig(), so it’s worth considering transitioning to this newer API when it’s convenient to do so. Examples of these sections in the file are given below. [loggers] keys=root,log02,log03,log04,log05,log06,log07 [handlers] keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09 [formatters] keys=form01,form02,form03,form04,form05,form06,form07,form08,form09 The root logger must specify a level and a list of handlers. An example of a root logger section is given below. [logger_root] level=NOTSET handlers=hand01 The level entry can be one of DEBUG, INFO, WARNING, ERROR, CRITICAL or NOTSET. For the root logger only, NOTSET means that all messages will be logged. Level values are eval()uated in the context of the logging package’s namespace. The handlers entry is a comma-separated list of handler names, which must appear in the [handlers] section. These names must appear in the [handlers] section and have corresponding sections in the configuration file. For loggers other than the root logger, some additional information is required. This is illustrated by the following example. [logger_parser] level=DEBUG handlers=hand01 propagate=1 qualname=compiler.parser The level and handlers entries are interpreted as for the root logger, except that if a non-root logger’s level is specified as NOTSET, the system consults loggers higher up the hierarchy to determine the effective level of the logger. The propagate entry is set to 1 to indicate that messages must propagate to handlers higher up the logger hierarchy from this logger, or 0 to indicate that messages are not propagated to handlers up the hierarchy. The qualname entry is the hierarchical channel name of the logger, that is to say the name used by the application to get the logger. Sections which specify handler configuration are exemplified by the following. [handler_hand01] class=StreamHandler level=NOTSET formatter=form01 args=(sys.stdout,) The class entry indicates the handler’s class (as determined by eval() in the logging package’s namespace). The level is interpreted as for loggers, and NOTSET is taken to mean ‘log everything’. The formatter entry indicates the key name of the formatter for this handler. If blank, a default formatter (logging._defaultFormatter) is used. If a name is specified, it must appear in the [formatters] section and have a corresponding section in the configuration file. The args entry, when eval()uated in the context of the logging package’s namespace, is the list of arguments to the constructor for the handler class. Refer to the constructors for the relevant handlers, or to the examples below, to see how typical entries are constructed. If not provided, it defaults to (). The optional kwargs entry, when eval()uated in the context of the logging package’s namespace, is the keyword argument dict to the constructor for the handler class. If not provided, it defaults to {}. [handler_hand02] class=FileHandler level=DEBUG formatter=form02 args=('python.log', 'w') [handler_hand03] class=handlers.SocketHandler level=INFO formatter=form03 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT) [handler_hand04] class=handlers.DatagramHandler level=WARN formatter=form04 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT) [handler_hand05] class=handlers.SysLogHandler level=ERROR formatter=form05 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER) [handler_hand06] class=handlers.NTEventLogHandler level=CRITICAL formatter=form06 args=('Python Application', '', 'Application') [handler_hand07] class=handlers.SMTPHandler level=WARN formatter=form07 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject') kwargs={'timeout': 10.0} [handler_hand08] class=handlers.MemoryHandler level=NOTSET formatter=form08 target= args=(10, ERROR) [handler_hand09] class=handlers.HTTPHandler level=NOTSET formatter=form09 args=('localhost:9022', '/log', 'GET') kwargs={'secure': True} Sections which specify formatter configuration are typified by the following. [formatter_form01] format=F1 %(asctime)s %(levelname)s %(message)s datefmt= class=logging.Formatter The format entry is the overall format string, and the datefmt entry is the strftime()-compatible date/time format string. If empty, the package substitutes something which is almost equivalent to specifying the date format string '%Y-%m-%d %H:%M:%S'. This format also specifies milliseconds, which are appended to the result of using the above format string, with a comma separator. An example time in this format is 2003-01-23 00:29:50,411. The class entry is optional. It indicates the name of the formatter’s class (as a dotted module and class name.) This option is useful for instantiating a Formatter subclass. Subclasses of Formatter can present exception tracebacks in an expanded or condensed format. Note Due to the use of eval() as described above, there are potential security risks which result from using the listen() to send and receive configurations via sockets. The risks are limited to where multiple users with no mutual trust run code on the same machine; see the listen() documentation for more information. See also Module logging API reference for the logging module. Module logging.handlers Useful handlers included with the logging module.
doc_1392
Suspend or resume input or output on file descriptor fd. The action argument can be TCOOFF to suspend output, TCOON to restart output, TCIOFF to suspend input, or TCION to restart input.
doc_1393
globally disables swizzling for vectors. disable_swizzling() -> None DEPRECATED: Not needed anymore. Will be removed in a later version. Disables swizzling for all vectors until enable_swizzling() is called. By default swizzling is disabled.
doc_1394
Set the parameters of this estimator. Valid parameter keys can be listed with get_params(). Note that you can directly set the parameters of the estimators contained in tranformer_list. Returns self
doc_1395
Implements the 'ignore' error handling: malformed data is ignored and encoding or decoding is continued without further notice.
doc_1396
Return all breakpoints that are set.
doc_1397
Send an XOVER command. start and end are article numbers delimiting the range of articles to select. The return value is the same of for over(). It is recommended to use over() instead, since it will automatically use the newer OVER command if available.
doc_1398
tf.keras.preprocessing.text_dataset_from_directory( directory, labels='inferred', label_mode='int', class_names=None, batch_size=32, max_length=None, shuffle=True, seed=None, validation_split=None, subset=None, follow_links=False ) If your directory structure is: main_directory/ ...class_a/ ......a_text_1.txt ......a_text_2.txt ...class_b/ ......b_text_1.txt ......b_text_2.txt Then calling text_dataset_from_directory(main_directory, labels='inferred') will return a tf.data.Dataset that yields batches of texts from the subdirectories class_a and class_b, together with labels 0 and 1 (0 corresponding to class_a and 1 corresponding to class_b). Only .txt files are supported at this time. Arguments directory Directory where the data is located. If labels is "inferred", it should contain subdirectories, each containing text files for a class. Otherwise, the directory structure is ignored. labels Either "inferred" (labels are generated from the directory structure), or a list/tuple of integer labels of the same size as the number of text files found in the directory. Labels should be sorted according to the alphanumeric order of the text file paths (obtained via os.walk(directory) in Python). label_mode 'int': means that the labels are encoded as integers (e.g. for sparse_categorical_crossentropy loss). 'categorical' means that the labels are encoded as a categorical vector (e.g. for categorical_crossentropy loss). 'binary' means that the labels (there can be only 2) are encoded as float32 scalars with values 0 or 1 (e.g. for binary_crossentropy). None (no labels). class_names Only valid if "labels" is "inferred". This is the explict list of class names (must match names of subdirectories). Used to control the order of the classes (otherwise alphanumerical order is used). batch_size Size of the batches of data. Default: 32. max_length Maximum size of a text string. Texts longer than this will be truncated to max_length. shuffle Whether to shuffle the data. Default: True. If set to False, sorts the data in alphanumeric order. seed Optional random seed for shuffling and transformations. validation_split Optional float between 0 and 1, fraction of data to reserve for validation. subset One of "training" or "validation". Only used if validation_split is set. follow_links Whether to visits subdirectories pointed to by symlinks. Defaults to False. Returns A tf.data.Dataset object. If label_mode is None, it yields string tensors of shape (batch_size,), containing the contents of a batch of text files. Otherwise, it yields a tuple (texts, labels), where texts has shape (batch_size,) and labels follows the format described below. Rules regarding labels format: if label_mode is int, the labels are an int32 tensor of shape (batch_size,). if label_mode is binary, the labels are a float32 tensor of 1s and 0s of shape (batch_size, 1). if label_mode is categorial, the labels are a float32 tensor of shape (batch_size, num_classes), representing a one-hot encoding of the class index.
doc_1399
Attributes reports repeated string reports