doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
math — Mathematical functions This module provides access to the mathematical functions defined by the C standard. These functions cannot be used with complex numbers; use the functions of the same name from the cmath module if you require support for complex numbers. The distinction between functions which support complex numbers and those which don’t is made since most users do not want to learn quite as much mathematics as required to understand complex numbers. Receiving an exception instead of a complex result allows earlier detection of the unexpected complex number used as a parameter, so that the programmer can determine how and why it was generated in the first place. The following functions are provided by this module. Except when explicitly noted otherwise, all return values are floats. Number-theoretic and representation functions math.ceil(x) Return the ceiling of x, the smallest integer greater than or equal to x. If x is not a float, delegates to x.__ceil__(), which should return an Integral value. math.comb(n, k) Return the number of ways to choose k items from n items without repetition and without order. Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates to zero when k > n. Also called the binomial coefficient because it is equivalent to the coefficient of k-th term in polynomial expansion of the expression (1 + x) ** n. Raises TypeError if either of the arguments are not integers. Raises ValueError if either of the arguments are negative. New in version 3.8. math.copysign(x, y) Return a float with the magnitude (absolute value) of x but the sign of y. On platforms that support signed zeros, copysign(1.0, -0.0) returns -1.0. math.fabs(x) Return the absolute value of x. math.factorial(x) Return x factorial as an integer. Raises ValueError if x is not integral or is negative. Deprecated since version 3.9: Accepting floats with integral values (like 5.0) is deprecated. math.floor(x) Return the floor of x, the largest integer less than or equal to x. If x is not a float, delegates to x.__floor__(), which should return an Integral value. math.fmod(x, y) Return fmod(x, y), as defined by the platform C library. Note that the Python expression x % y may not return the same result. The intent of the C standard is that fmod(x, y) be exactly (mathematically; to infinite precision) equal to x - n*y for some integer n such that the result has the same sign as x and magnitude less than abs(y). Python’s x % y returns a result with the sign of y instead, and may not be exactly computable for float arguments. For example, fmod(-1e-100, 1e100) is -1e-100, but the result of Python’s -1e-100 % 1e100 is 1e100-1e-100, which cannot be represented exactly as a float, and rounds to the surprising 1e100. For this reason, function fmod() is generally preferred when working with floats, while Python’s x % y is preferred when working with integers. math.frexp(x) Return the mantissa and exponent of x as the pair (m, e). m is a float and e is an integer such that x == m * 2**e exactly. If x is zero, returns (0.0, 0), otherwise 0.5 <= abs(m) < 1. This is used to “pick apart” the internal representation of a float in a portable way. math.fsum(iterable) Return an accurate floating point sum of values in the iterable. Avoids loss of precision by tracking multiple intermediate partial sums: >>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 0.9999999999999999 >>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 1.0 The algorithm’s accuracy depends on IEEE-754 arithmetic guarantees and the typical case where the rounding mode is half-even. On some non-Windows builds, the underlying C library uses extended precision addition and may occasionally double-round an intermediate sum causing it to be off in its least significant bit. For further discussion and two alternative approaches, see the ASPN cookbook recipes for accurate floating point summation. math.gcd(*integers) Return the greatest common divisor of the specified integer arguments. If any of the arguments is nonzero, then the returned value is the largest positive integer that is a divisor of all arguments. If all arguments are zero, then the returned value is 0. gcd() without arguments returns 0. New in version 3.5. Changed in version 3.9: Added support for an arbitrary number of arguments. Formerly, only two arguments were supported. math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) Return True if the values a and b are close to each other and False otherwise. Whether or not two values are considered close is determined according to given absolute and relative tolerances. rel_tol is the relative tolerance – it is the maximum allowed difference between a and b, relative to the larger absolute value of a or b. For example, to set a tolerance of 5%, pass rel_tol=0.05. The default tolerance is 1e-09, which assures that the two values are the same within about 9 decimal digits. rel_tol must be greater than zero. abs_tol is the minimum absolute tolerance – useful for comparisons near zero. abs_tol must be at least zero. If no errors occur, the result will be: abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol). The IEEE 754 special values of NaN, inf, and -inf will be handled according to IEEE rules. Specifically, NaN is not considered close to any other value, including NaN. inf and -inf are only considered close to themselves. New in version 3.5. See also PEP 485 – A function for testing approximate equality math.isfinite(x) Return True if x is neither an infinity nor a NaN, and False otherwise. (Note that 0.0 is considered finite.) New in version 3.2. math.isinf(x) Return True if x is a positive or negative infinity, and False otherwise. math.isnan(x) Return True if x is a NaN (not a number), and False otherwise. math.isqrt(n) Return the integer square root of the nonnegative integer n. This is the floor of the exact square root of n, or equivalently the greatest integer a such that a² ≤ n. For some applications, it may be more convenient to have the least integer a such that n ≤ a², or in other words the ceiling of the exact square root of n. For positive n, this can be computed using a = 1 + isqrt(n - 1). New in version 3.8. math.lcm(*integers) Return the least common multiple of the specified integer arguments. If all arguments are nonzero, then the returned value is the smallest positive integer that is a multiple of all arguments. If any of the arguments is zero, then the returned value is 0. lcm() without arguments returns 1. New in version 3.9. math.ldexp(x, i) Return x * (2**i). This is essentially the inverse of function frexp(). math.modf(x) Return the fractional and integer parts of x. Both results carry the sign of x and are floats. math.nextafter(x, y) Return the next floating-point value after x towards y. If x is equal to y, return y. Examples: math.nextafter(x, math.inf) goes up: towards positive infinity. math.nextafter(x, -math.inf) goes down: towards minus infinity. math.nextafter(x, 0.0) goes towards zero. math.nextafter(x, math.copysign(math.inf, x)) goes away from zero. See also math.ulp(). New in version 3.9. math.perm(n, k=None) Return the number of ways to choose k items from n items without repetition and with order. Evaluates to n! / (n - k)! when k <= n and evaluates to zero when k > n. If k is not specified or is None, then k defaults to n and the function returns n!. Raises TypeError if either of the arguments are not integers. Raises ValueError if either of the arguments are negative. New in version 3.8. math.prod(iterable, *, start=1) Calculate the product of all the elements in the input iterable. The default start value for the product is 1. When the iterable is empty, return the start value. This function is intended specifically for use with numeric values and may reject non-numeric types. New in version 3.8. math.remainder(x, y) Return the IEEE 754-style remainder of x with respect to y. For finite x and finite nonzero y, this is the difference x - n*y, where n is the closest integer to the exact value of the quotient x / y. If x / y is exactly halfway between two consecutive integers, the nearest even integer is used for n. The remainder r = remainder(x, y) thus always satisfies abs(r) <= 0.5 * abs(y). Special cases follow IEEE 754: in particular, remainder(x, math.inf) is x for any finite x, and remainder(x, 0) and remainder(math.inf, x) raise ValueError for any non-NaN x. If the result of the remainder operation is zero, that zero will have the same sign as x. On platforms using IEEE 754 binary floating-point, the result of this operation is always exactly representable: no rounding error is introduced. New in version 3.7. math.trunc(x) Return the Real value x truncated to an Integral (usually an integer). Delegates to x.__trunc__(). math.ulp(x) Return the value of the least significant bit of the float x: If x is a NaN (not a number), return x. If x is negative, return ulp(-x). If x is a positive infinity, return x. If x is equal to zero, return the smallest positive denormalized representable float (smaller than the minimum positive normalized float, sys.float_info.min). If x is equal to the largest positive representable float, return the value of the least significant bit of x, such that the first float smaller than x is x - ulp(x). Otherwise (x is a positive finite number), return the value of the least significant bit of x, such that the first float bigger than x is x + ulp(x). ULP stands for “Unit in the Last Place”. See also math.nextafter() and sys.float_info.epsilon. New in version 3.9. Note that frexp() and modf() have a different call/return pattern than their C equivalents: they take a single argument and return a pair of values, rather than returning their second return value through an ‘output parameter’ (there is no such thing in Python). For the ceil(), floor(), and modf() functions, note that all floating-point numbers of sufficiently large magnitude are exact integers. Python floats typically carry no more than 53 bits of precision (the same as the platform C double type), in which case any float x with abs(x) >= 2**52 necessarily has no fractional bits. Power and logarithmic functions math.exp(x) Return e raised to the power x, where e = 2.718281… is the base of natural logarithms. This is usually more accurate than math.e ** x or pow(math.e, x). math.expm1(x) Return e raised to the power x, minus 1. Here e is the base of natural logarithms. For small floats x, the subtraction in exp(x) - 1 can result in a significant loss of precision; the expm1() function provides a way to compute this quantity to full precision: >>> from math import exp, expm1 >>> exp(1e-5) - 1 # gives result accurate to 11 places 1.0000050000069649e-05 >>> expm1(1e-5) # result accurate to full precision 1.0000050000166668e-05 New in version 3.2. math.log(x[, base]) With one argument, return the natural logarithm of x (to base e). With two arguments, return the logarithm of x to the given base, calculated as log(x)/log(base). math.log1p(x) Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero. math.log2(x) Return the base-2 logarithm of x. This is usually more accurate than log(x, 2). New in version 3.3. See also int.bit_length() returns the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros. math.log10(x) Return the base-10 logarithm of x. This is usually more accurate than log(x, 10). math.pow(x, y) Return x raised to the power y. Exceptional cases follow Annex ‘F’ of the C99 standard as far as possible. In particular, pow(1.0, x) and pow(x, 0.0) always return 1.0, even when x is a zero or a NaN. If both x and y are finite, x is negative, and y is not an integer then pow(x, y) is undefined, and raises ValueError. Unlike the built-in ** operator, math.pow() converts both its arguments to type float. Use ** or the built-in pow() function for computing exact integer powers. math.sqrt(x) Return the square root of x. Trigonometric functions math.acos(x) Return the arc cosine of x, in radians. The result is between 0 and pi. math.asin(x) Return the arc sine of x, in radians. The result is between -pi/2 and pi/2. math.atan(x) Return the arc tangent of x, in radians. The result is between -pi/2 and pi/2. math.atan2(y, x) Return atan(y / x), in radians. The result is between -pi and pi. The vector in the plane from the origin to point (x, y) makes this angle with the positive X axis. The point of atan2() is that the signs of both inputs are known to it, so it can compute the correct quadrant for the angle. For example, atan(1) and atan2(1, 1) are both pi/4, but atan2(-1, -1) is -3*pi/4. math.cos(x) Return the cosine of x radians. math.dist(p, q) Return the Euclidean distance between two points p and q, each given as a sequence (or iterable) of coordinates. The two points must have the same dimension. Roughly equivalent to: sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q))) New in version 3.8. math.hypot(*coordinates) Return the Euclidean norm, sqrt(sum(x**2 for x in coordinates)). This is the length of the vector from the origin to the point given by the coordinates. For a two dimensional point (x, y), this is equivalent to computing the hypotenuse of a right triangle using the Pythagorean theorem, sqrt(x*x + y*y). Changed in version 3.8: Added support for n-dimensional points. Formerly, only the two dimensional case was supported. math.sin(x) Return the sine of x radians. math.tan(x) Return the tangent of x radians. Angular conversion math.degrees(x) Convert angle x from radians to degrees. math.radians(x) Convert angle x from degrees to radians. Hyperbolic functions Hyperbolic functions are analogs of trigonometric functions that are based on hyperbolas instead of circles. math.acosh(x) Return the inverse hyperbolic cosine of x. math.asinh(x) Return the inverse hyperbolic sine of x. math.atanh(x) Return the inverse hyperbolic tangent of x. math.cosh(x) Return the hyperbolic cosine of x. math.sinh(x) Return the hyperbolic sine of x. math.tanh(x) Return the hyperbolic tangent of x. Special functions math.erf(x) Return the error function at x. The erf() function can be used to compute traditional statistical functions such as the cumulative standard normal distribution: def phi(x): 'Cumulative distribution function for the standard normal distribution' return (1.0 + erf(x / sqrt(2.0))) / 2.0 New in version 3.2. math.erfc(x) Return the complementary error function at x. The complementary error function is defined as 1.0 - erf(x). It is used for large values of x where a subtraction from one would cause a loss of significance. New in version 3.2. math.gamma(x) Return the Gamma function at x. New in version 3.2. math.lgamma(x) Return the natural logarithm of the absolute value of the Gamma function at x. New in version 3.2. Constants math.pi The mathematical constant π = 3.141592…, to available precision. math.e The mathematical constant e = 2.718281…, to available precision. math.tau The mathematical constant τ = 6.283185…, to available precision. Tau is a circle constant equal to 2π, the ratio of a circle’s circumference to its radius. To learn more about Tau, check out Vi Hart’s video Pi is (still) Wrong, and start celebrating Tau day by eating twice as much pie! New in version 3.6. math.inf A floating-point positive infinity. (For negative infinity, use -math.inf.) Equivalent to the output of float('inf'). New in version 3.5. math.nan A floating-point “not a number” (NaN) value. Equivalent to the output of float('nan'). New in version 3.5. CPython implementation detail: The math module consists mostly of thin wrappers around the platform C math library functions. Behavior in exceptional cases follows Annex F of the C99 standard where appropriate. The current implementation will raise ValueError for invalid operations like sqrt(-1.0) or log(0.0) (where C99 Annex F recommends signaling invalid operation or divide-by-zero), and OverflowError for results that overflow (for example, exp(1000.0)). A NaN will not be returned from any of the functions above unless one or more of the input arguments was a NaN; in that case, most functions will return a NaN, but (again following C99 Annex F) there are some exceptions to this rule, for example pow(float('nan'), 0.0) or hypot(float('nan'), float('inf')). Note that Python makes no effort to distinguish signaling NaNs from quiet NaNs, and behavior for signaling NaNs remains unspecified. Typical behavior is to treat all NaNs as though they were quiet. See also Module cmath Complex number versions of many of these functions.
python.library.math
math.acos(x) Return the arc cosine of x, in radians. The result is between 0 and pi.
python.library.math#math.acos
math.acosh(x) Return the inverse hyperbolic cosine of x.
python.library.math#math.acosh
math.asin(x) Return the arc sine of x, in radians. The result is between -pi/2 and pi/2.
python.library.math#math.asin
math.asinh(x) Return the inverse hyperbolic sine of x.
python.library.math#math.asinh
math.atan(x) Return the arc tangent of x, in radians. The result is between -pi/2 and pi/2.
python.library.math#math.atan
math.atan2(y, x) Return atan(y / x), in radians. The result is between -pi and pi. The vector in the plane from the origin to point (x, y) makes this angle with the positive X axis. The point of atan2() is that the signs of both inputs are known to it, so it can compute the correct quadrant for the angle. For example, atan(1) and atan2(1, 1) are both pi/4, but atan2(-1, -1) is -3*pi/4.
python.library.math#math.atan2
math.atanh(x) Return the inverse hyperbolic tangent of x.
python.library.math#math.atanh
math.ceil(x) Return the ceiling of x, the smallest integer greater than or equal to x. If x is not a float, delegates to x.__ceil__(), which should return an Integral value.
python.library.math#math.ceil
math.comb(n, k) Return the number of ways to choose k items from n items without repetition and without order. Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates to zero when k > n. Also called the binomial coefficient because it is equivalent to the coefficient of k-th term in polynomial expansion of the expression (1 + x) ** n. Raises TypeError if either of the arguments are not integers. Raises ValueError if either of the arguments are negative. New in version 3.8.
python.library.math#math.comb
math.copysign(x, y) Return a float with the magnitude (absolute value) of x but the sign of y. On platforms that support signed zeros, copysign(1.0, -0.0) returns -1.0.
python.library.math#math.copysign
math.cos(x) Return the cosine of x radians.
python.library.math#math.cos
math.cosh(x) Return the hyperbolic cosine of x.
python.library.math#math.cosh
math.degrees(x) Convert angle x from radians to degrees.
python.library.math#math.degrees
math.dist(p, q) Return the Euclidean distance between two points p and q, each given as a sequence (or iterable) of coordinates. The two points must have the same dimension. Roughly equivalent to: sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q))) New in version 3.8.
python.library.math#math.dist
math.e The mathematical constant e = 2.718281…, to available precision.
python.library.math#math.e
math.erf(x) Return the error function at x. The erf() function can be used to compute traditional statistical functions such as the cumulative standard normal distribution: def phi(x): 'Cumulative distribution function for the standard normal distribution' return (1.0 + erf(x / sqrt(2.0))) / 2.0 New in version 3.2.
python.library.math#math.erf
math.erfc(x) Return the complementary error function at x. The complementary error function is defined as 1.0 - erf(x). It is used for large values of x where a subtraction from one would cause a loss of significance. New in version 3.2.
python.library.math#math.erfc
math.exp(x) Return e raised to the power x, where e = 2.718281… is the base of natural logarithms. This is usually more accurate than math.e ** x or pow(math.e, x).
python.library.math#math.exp
math.expm1(x) Return e raised to the power x, minus 1. Here e is the base of natural logarithms. For small floats x, the subtraction in exp(x) - 1 can result in a significant loss of precision; the expm1() function provides a way to compute this quantity to full precision: >>> from math import exp, expm1 >>> exp(1e-5) - 1 # gives result accurate to 11 places 1.0000050000069649e-05 >>> expm1(1e-5) # result accurate to full precision 1.0000050000166668e-05 New in version 3.2.
python.library.math#math.expm1
math.fabs(x) Return the absolute value of x.
python.library.math#math.fabs
math.factorial(x) Return x factorial as an integer. Raises ValueError if x is not integral or is negative. Deprecated since version 3.9: Accepting floats with integral values (like 5.0) is deprecated.
python.library.math#math.factorial
math.floor(x) Return the floor of x, the largest integer less than or equal to x. If x is not a float, delegates to x.__floor__(), which should return an Integral value.
python.library.math#math.floor
math.fmod(x, y) Return fmod(x, y), as defined by the platform C library. Note that the Python expression x % y may not return the same result. The intent of the C standard is that fmod(x, y) be exactly (mathematically; to infinite precision) equal to x - n*y for some integer n such that the result has the same sign as x and magnitude less than abs(y). Python’s x % y returns a result with the sign of y instead, and may not be exactly computable for float arguments. For example, fmod(-1e-100, 1e100) is -1e-100, but the result of Python’s -1e-100 % 1e100 is 1e100-1e-100, which cannot be represented exactly as a float, and rounds to the surprising 1e100. For this reason, function fmod() is generally preferred when working with floats, while Python’s x % y is preferred when working with integers.
python.library.math#math.fmod
math.frexp(x) Return the mantissa and exponent of x as the pair (m, e). m is a float and e is an integer such that x == m * 2**e exactly. If x is zero, returns (0.0, 0), otherwise 0.5 <= abs(m) < 1. This is used to “pick apart” the internal representation of a float in a portable way.
python.library.math#math.frexp
math.fsum(iterable) Return an accurate floating point sum of values in the iterable. Avoids loss of precision by tracking multiple intermediate partial sums: >>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 0.9999999999999999 >>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 1.0 The algorithm’s accuracy depends on IEEE-754 arithmetic guarantees and the typical case where the rounding mode is half-even. On some non-Windows builds, the underlying C library uses extended precision addition and may occasionally double-round an intermediate sum causing it to be off in its least significant bit. For further discussion and two alternative approaches, see the ASPN cookbook recipes for accurate floating point summation.
python.library.math#math.fsum
math.gamma(x) Return the Gamma function at x. New in version 3.2.
python.library.math#math.gamma
math.gcd(*integers) Return the greatest common divisor of the specified integer arguments. If any of the arguments is nonzero, then the returned value is the largest positive integer that is a divisor of all arguments. If all arguments are zero, then the returned value is 0. gcd() without arguments returns 0. New in version 3.5. Changed in version 3.9: Added support for an arbitrary number of arguments. Formerly, only two arguments were supported.
python.library.math#math.gcd
math.hypot(*coordinates) Return the Euclidean norm, sqrt(sum(x**2 for x in coordinates)). This is the length of the vector from the origin to the point given by the coordinates. For a two dimensional point (x, y), this is equivalent to computing the hypotenuse of a right triangle using the Pythagorean theorem, sqrt(x*x + y*y). Changed in version 3.8: Added support for n-dimensional points. Formerly, only the two dimensional case was supported.
python.library.math#math.hypot
math.inf A floating-point positive infinity. (For negative infinity, use -math.inf.) Equivalent to the output of float('inf'). New in version 3.5.
python.library.math#math.inf
math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) Return True if the values a and b are close to each other and False otherwise. Whether or not two values are considered close is determined according to given absolute and relative tolerances. rel_tol is the relative tolerance – it is the maximum allowed difference between a and b, relative to the larger absolute value of a or b. For example, to set a tolerance of 5%, pass rel_tol=0.05. The default tolerance is 1e-09, which assures that the two values are the same within about 9 decimal digits. rel_tol must be greater than zero. abs_tol is the minimum absolute tolerance – useful for comparisons near zero. abs_tol must be at least zero. If no errors occur, the result will be: abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol). The IEEE 754 special values of NaN, inf, and -inf will be handled according to IEEE rules. Specifically, NaN is not considered close to any other value, including NaN. inf and -inf are only considered close to themselves. New in version 3.5. See also PEP 485 – A function for testing approximate equality
python.library.math#math.isclose
math.isfinite(x) Return True if x is neither an infinity nor a NaN, and False otherwise. (Note that 0.0 is considered finite.) New in version 3.2.
python.library.math#math.isfinite
math.isinf(x) Return True if x is a positive or negative infinity, and False otherwise.
python.library.math#math.isinf
math.isnan(x) Return True if x is a NaN (not a number), and False otherwise.
python.library.math#math.isnan
math.isqrt(n) Return the integer square root of the nonnegative integer n. This is the floor of the exact square root of n, or equivalently the greatest integer a such that a² ≤ n. For some applications, it may be more convenient to have the least integer a such that n ≤ a², or in other words the ceiling of the exact square root of n. For positive n, this can be computed using a = 1 + isqrt(n - 1). New in version 3.8.
python.library.math#math.isqrt
math.lcm(*integers) Return the least common multiple of the specified integer arguments. If all arguments are nonzero, then the returned value is the smallest positive integer that is a multiple of all arguments. If any of the arguments is zero, then the returned value is 0. lcm() without arguments returns 1. New in version 3.9.
python.library.math#math.lcm
math.ldexp(x, i) Return x * (2**i). This is essentially the inverse of function frexp().
python.library.math#math.ldexp
math.lgamma(x) Return the natural logarithm of the absolute value of the Gamma function at x. New in version 3.2.
python.library.math#math.lgamma
math.log(x[, base]) With one argument, return the natural logarithm of x (to base e). With two arguments, return the logarithm of x to the given base, calculated as log(x)/log(base).
python.library.math#math.log
math.log10(x) Return the base-10 logarithm of x. This is usually more accurate than log(x, 10).
python.library.math#math.log10
math.log1p(x) Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.
python.library.math#math.log1p
math.log2(x) Return the base-2 logarithm of x. This is usually more accurate than log(x, 2). New in version 3.3. See also int.bit_length() returns the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros.
python.library.math#math.log2
math.modf(x) Return the fractional and integer parts of x. Both results carry the sign of x and are floats.
python.library.math#math.modf
math.nan A floating-point “not a number” (NaN) value. Equivalent to the output of float('nan'). New in version 3.5.
python.library.math#math.nan
math.nextafter(x, y) Return the next floating-point value after x towards y. If x is equal to y, return y. Examples: math.nextafter(x, math.inf) goes up: towards positive infinity. math.nextafter(x, -math.inf) goes down: towards minus infinity. math.nextafter(x, 0.0) goes towards zero. math.nextafter(x, math.copysign(math.inf, x)) goes away from zero. See also math.ulp(). New in version 3.9.
python.library.math#math.nextafter
math.perm(n, k=None) Return the number of ways to choose k items from n items without repetition and with order. Evaluates to n! / (n - k)! when k <= n and evaluates to zero when k > n. If k is not specified or is None, then k defaults to n and the function returns n!. Raises TypeError if either of the arguments are not integers. Raises ValueError if either of the arguments are negative. New in version 3.8.
python.library.math#math.perm
math.pi The mathematical constant π = 3.141592…, to available precision.
python.library.math#math.pi
math.pow(x, y) Return x raised to the power y. Exceptional cases follow Annex ‘F’ of the C99 standard as far as possible. In particular, pow(1.0, x) and pow(x, 0.0) always return 1.0, even when x is a zero or a NaN. If both x and y are finite, x is negative, and y is not an integer then pow(x, y) is undefined, and raises ValueError. Unlike the built-in ** operator, math.pow() converts both its arguments to type float. Use ** or the built-in pow() function for computing exact integer powers.
python.library.math#math.pow
math.prod(iterable, *, start=1) Calculate the product of all the elements in the input iterable. The default start value for the product is 1. When the iterable is empty, return the start value. This function is intended specifically for use with numeric values and may reject non-numeric types. New in version 3.8.
python.library.math#math.prod
math.radians(x) Convert angle x from degrees to radians.
python.library.math#math.radians
math.remainder(x, y) Return the IEEE 754-style remainder of x with respect to y. For finite x and finite nonzero y, this is the difference x - n*y, where n is the closest integer to the exact value of the quotient x / y. If x / y is exactly halfway between two consecutive integers, the nearest even integer is used for n. The remainder r = remainder(x, y) thus always satisfies abs(r) <= 0.5 * abs(y). Special cases follow IEEE 754: in particular, remainder(x, math.inf) is x for any finite x, and remainder(x, 0) and remainder(math.inf, x) raise ValueError for any non-NaN x. If the result of the remainder operation is zero, that zero will have the same sign as x. On platforms using IEEE 754 binary floating-point, the result of this operation is always exactly representable: no rounding error is introduced. New in version 3.7.
python.library.math#math.remainder
math.sin(x) Return the sine of x radians.
python.library.math#math.sin
math.sinh(x) Return the hyperbolic sine of x.
python.library.math#math.sinh
math.sqrt(x) Return the square root of x.
python.library.math#math.sqrt
math.tan(x) Return the tangent of x radians.
python.library.math#math.tan
math.tanh(x) Return the hyperbolic tangent of x.
python.library.math#math.tanh
math.tau The mathematical constant τ = 6.283185…, to available precision. Tau is a circle constant equal to 2π, the ratio of a circle’s circumference to its radius. To learn more about Tau, check out Vi Hart’s video Pi is (still) Wrong, and start celebrating Tau day by eating twice as much pie! New in version 3.6.
python.library.math#math.tau
math.trunc(x) Return the Real value x truncated to an Integral (usually an integer). Delegates to x.__trunc__().
python.library.math#math.trunc
math.ulp(x) Return the value of the least significant bit of the float x: If x is a NaN (not a number), return x. If x is negative, return ulp(-x). If x is a positive infinity, return x. If x is equal to zero, return the smallest positive denormalized representable float (smaller than the minimum positive normalized float, sys.float_info.min). If x is equal to the largest positive representable float, return the value of the least significant bit of x, such that the first float smaller than x is x - ulp(x). Otherwise (x is a positive finite number), return the value of the least significant bit of x, such that the first float bigger than x is x + ulp(x). ULP stands for “Unit in the Last Place”. See also math.nextafter() and sys.float_info.epsilon. New in version 3.9.
python.library.math#math.ulp
max(iterable, *[, key, default]) max(arg1, arg2, *args[, key]) Return the largest item in an iterable or the largest of two or more arguments. If one positional argument is provided, it should be an iterable. The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned. There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised. If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc, reverse=True)[0] and heapq.nlargest(1, iterable, key=keyfunc). New in version 3.4: The default keyword-only argument. Changed in version 3.8: The key can be None.
python.library.functions#max
exception MemoryError Raised when an operation runs out of memory but the situation may still be rescued (by deleting some objects). The associated value is a string indicating what kind of (internal) operation ran out of memory. Note that because of the underlying memory management architecture (C’s malloc() function), the interpreter may not always be able to completely recover from this situation; it nevertheless raises an exception so that a stack traceback can be printed, in case a run-away program was the cause.
python.library.exceptions#MemoryError
class memoryview(obj) Create a memoryview that references obj. obj must support the buffer protocol. Built-in objects that support the buffer protocol include bytes and bytearray. A memoryview has the notion of an element, which is the atomic memory unit handled by the originating object obj. For many simple types such as bytes and bytearray, an element is a single byte, but other types such as array.array may have bigger elements. len(view) is equal to the length of tolist. If view.ndim = 0, the length is 1. If view.ndim = 1, the length is equal to the number of elements in the view. For higher dimensions, the length is equal to the length of the nested list representation of the view. The itemsize attribute will give you the number of bytes in a single element. A memoryview supports slicing and indexing to expose its data. One-dimensional slicing will result in a subview: >>> v = memoryview(b'abcefg') >>> v[1] 98 >>> v[-1] 103 >>> v[1:4] <memory at 0x7f3ddc9f4350> >>> bytes(v[1:4]) b'bce' If format is one of the native format specifiers from the struct module, indexing with an integer or a tuple of integers is also supported and returns a single element with the correct type. One-dimensional memoryviews can be indexed with an integer or a one-integer tuple. Multi-dimensional memoryviews can be indexed with tuples of exactly ndim integers where ndim is the number of dimensions. Zero-dimensional memoryviews can be indexed with the empty tuple. Here is an example with a non-byte format: >>> import array >>> a = array.array('l', [-11111111, 22222222, -33333333, 44444444]) >>> m = memoryview(a) >>> m[0] -11111111 >>> m[-1] 44444444 >>> m[::2].tolist() [-11111111, -33333333] If the underlying object is writable, the memoryview supports one-dimensional slice assignment. Resizing is not allowed: >>> data = bytearray(b'abcefg') >>> v = memoryview(data) >>> v.readonly False >>> v[0] = ord(b'z') >>> data bytearray(b'zbcefg') >>> v[1:4] = b'123' >>> data bytearray(b'z123fg') >>> v[2:3] = b'spam' Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: memoryview assignment: lvalue and rvalue have different structures >>> v[2:6] = b'spam' >>> data bytearray(b'z1spam') One-dimensional memoryviews of hashable (read-only) types with formats ‘B’, ‘b’ or ‘c’ are also hashable. The hash is defined as hash(m) == hash(m.tobytes()): >>> v = memoryview(b'abcefg') >>> hash(v) == hash(b'abcefg') True >>> hash(v[2:4]) == hash(b'ce') True >>> hash(v[::-2]) == hash(b'abcefg'[::-2]) True Changed in version 3.3: One-dimensional memoryviews can now be sliced. One-dimensional memoryviews with formats ‘B’, ‘b’ or ‘c’ are now hashable. Changed in version 3.4: memoryview is now registered automatically with collections.abc.Sequence Changed in version 3.5: memoryviews can now be indexed with tuple of integers. memoryview has several methods: __eq__(exporter) A memoryview and a PEP 3118 exporter are equal if their shapes are equivalent and if all corresponding values are equal when the operands’ respective format codes are interpreted using struct syntax. For the subset of struct format strings currently supported by tolist(), v and w are equal if v.tolist() == w.tolist(): >>> import array >>> a = array.array('I', [1, 2, 3, 4, 5]) >>> b = array.array('d', [1.0, 2.0, 3.0, 4.0, 5.0]) >>> c = array.array('b', [5, 3, 1]) >>> x = memoryview(a) >>> y = memoryview(b) >>> x == a == y == b True >>> x.tolist() == a.tolist() == y.tolist() == b.tolist() True >>> z = y[::-2] >>> z == c True >>> z.tolist() == c.tolist() True If either format string is not supported by the struct module, then the objects will always compare as unequal (even if the format strings and buffer contents are identical): >>> from ctypes import BigEndianStructure, c_long >>> class BEPoint(BigEndianStructure): ... _fields_ = [("x", c_long), ("y", c_long)] ... >>> point = BEPoint(100, 200) >>> a = memoryview(point) >>> b = memoryview(point) >>> a == point False >>> a == b False Note that, as with floating point numbers, v is w does not imply v == w for memoryview objects. Changed in version 3.3: Previous versions compared the raw memory disregarding the item format and the logical array structure. tobytes(order=None) Return the data in the buffer as a bytestring. This is equivalent to calling the bytes constructor on the memoryview. >>> m = memoryview(b"abc") >>> m.tobytes() b'abc' >>> bytes(m) b'abc' For non-contiguous arrays the result is equal to the flattened list representation with all elements converted to bytes. tobytes() supports all format strings, including those that are not in struct module syntax. New in version 3.8: order can be {‘C’, ‘F’, ‘A’}. When order is ‘C’ or ‘F’, the data of the original array is converted to C or Fortran order. For contiguous views, ‘A’ returns an exact copy of the physical memory. In particular, in-memory Fortran order is preserved. For non-contiguous views, the data is converted to C first. order=None is the same as order=’C’. hex([sep[, bytes_per_sep]]) Return a string object containing two hexadecimal digits for each byte in the buffer. >>> m = memoryview(b"abc") >>> m.hex() '616263' New in version 3.5. Changed in version 3.8: Similar to bytes.hex(), memoryview.hex() now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output. tolist() Return the data in the buffer as a list of elements. >>> memoryview(b'abc').tolist() [97, 98, 99] >>> import array >>> a = array.array('d', [1.1, 2.2, 3.3]) >>> m = memoryview(a) >>> m.tolist() [1.1, 2.2, 3.3] Changed in version 3.3: tolist() now supports all single character native formats in struct module syntax as well as multi-dimensional representations. toreadonly() Return a readonly version of the memoryview object. The original memoryview object is unchanged. >>> m = memoryview(bytearray(b'abc')) >>> mm = m.toreadonly() >>> mm.tolist() [89, 98, 99] >>> mm[0] = 42 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot modify read-only memory >>> m[0] = 43 >>> mm.tolist() [43, 98, 99] New in version 3.8. release() Release the underlying buffer exposed by the memoryview object. Many objects take special actions when a view is held on them (for example, a bytearray would temporarily forbid resizing); therefore, calling release() is handy to remove these restrictions (and free any dangling resources) as soon as possible. After this method has been called, any further operation on the view raises a ValueError (except release() itself which can be called multiple times): >>> m = memoryview(b'abc') >>> m.release() >>> m[0] Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: operation forbidden on released memoryview object The context management protocol can be used for a similar effect, using the with statement: >>> with memoryview(b'abc') as m: ... m[0] ... 97 >>> m[0] Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: operation forbidden on released memoryview object New in version 3.2. cast(format[, shape]) Cast a memoryview to a new format or shape. shape defaults to [byte_length//new_itemsize], which means that the result view will be one-dimensional. The return value is a new memoryview, but the buffer itself is not copied. Supported casts are 1D -> C-contiguous and C-contiguous -> 1D. The destination format is restricted to a single element native format in struct syntax. One of the formats must be a byte format (‘B’, ‘b’ or ‘c’). The byte length of the result must be the same as the original length. Cast 1D/long to 1D/unsigned bytes: >>> import array >>> a = array.array('l', [1,2,3]) >>> x = memoryview(a) >>> x.format 'l' >>> x.itemsize 8 >>> len(x) 3 >>> x.nbytes 24 >>> y = x.cast('B') >>> y.format 'B' >>> y.itemsize 1 >>> len(y) 24 >>> y.nbytes 24 Cast 1D/unsigned bytes to 1D/char: >>> b = bytearray(b'zyz') >>> x = memoryview(b) >>> x[0] = b'a' Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: memoryview: invalid value for format "B" >>> y = x.cast('c') >>> y[0] = b'a' >>> b bytearray(b'ayz') Cast 1D/bytes to 3D/ints to 1D/signed char: >>> import struct >>> buf = struct.pack("i"*12, *list(range(12))) >>> x = memoryview(buf) >>> y = x.cast('i', shape=[2,2,3]) >>> y.tolist() [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]] >>> y.format 'i' >>> y.itemsize 4 >>> len(y) 2 >>> y.nbytes 48 >>> z = y.cast('b') >>> z.format 'b' >>> z.itemsize 1 >>> len(z) 48 >>> z.nbytes 48 Cast 1D/unsigned long to 2D/unsigned long: >>> buf = struct.pack("L"*6, *list(range(6))) >>> x = memoryview(buf) >>> y = x.cast('L', shape=[2,3]) >>> len(y) 2 >>> y.nbytes 48 >>> y.tolist() [[0, 1, 2], [3, 4, 5]] New in version 3.3. Changed in version 3.5: The source format is no longer restricted when casting to a byte view. There are also several readonly attributes available: obj The underlying object of the memoryview: >>> b = bytearray(b'xyz') >>> m = memoryview(b) >>> m.obj is b True New in version 3.3. nbytes nbytes == product(shape) * itemsize == len(m.tobytes()). This is the amount of space in bytes that the array would use in a contiguous representation. It is not necessarily equal to len(m): >>> import array >>> a = array.array('i', [1,2,3,4,5]) >>> m = memoryview(a) >>> len(m) 5 >>> m.nbytes 20 >>> y = m[::2] >>> len(y) 3 >>> y.nbytes 12 >>> len(y.tobytes()) 12 Multi-dimensional arrays: >>> import struct >>> buf = struct.pack("d"*12, *[1.5*x for x in range(12)]) >>> x = memoryview(buf) >>> y = x.cast('d', shape=[3,4]) >>> y.tolist() [[0.0, 1.5, 3.0, 4.5], [6.0, 7.5, 9.0, 10.5], [12.0, 13.5, 15.0, 16.5]] >>> len(y) 3 >>> y.nbytes 96 New in version 3.3. readonly A bool indicating whether the memory is read only. format A string containing the format (in struct module style) for each element in the view. A memoryview can be created from exporters with arbitrary format strings, but some methods (e.g. tolist()) are restricted to native single element formats. Changed in version 3.3: format 'B' is now handled according to the struct module syntax. This means that memoryview(b'abc')[0] == b'abc'[0] == 97. itemsize The size in bytes of each element of the memoryview: >>> import array, struct >>> m = memoryview(array.array('H', [32000, 32001, 32002])) >>> m.itemsize 2 >>> m[0] 32000 >>> struct.calcsize('H') == m.itemsize True ndim An integer indicating how many dimensions of a multi-dimensional array the memory represents. shape A tuple of integers the length of ndim giving the shape of the memory as an N-dimensional array. Changed in version 3.3: An empty tuple instead of None when ndim = 0. strides A tuple of integers the length of ndim giving the size in bytes to access each element for each dimension of the array. Changed in version 3.3: An empty tuple instead of None when ndim = 0. suboffsets Used internally for PIL-style arrays. The value is informational only. c_contiguous A bool indicating whether the memory is C-contiguous. New in version 3.3. f_contiguous A bool indicating whether the memory is Fortran contiguous. New in version 3.3. contiguous A bool indicating whether the memory is contiguous. New in version 3.3.
python.library.stdtypes#memoryview
class memoryview(obj) Return a “memory view” object created from the given argument. See Memory Views for more information.
python.library.functions#memoryview
cast(format[, shape]) Cast a memoryview to a new format or shape. shape defaults to [byte_length//new_itemsize], which means that the result view will be one-dimensional. The return value is a new memoryview, but the buffer itself is not copied. Supported casts are 1D -> C-contiguous and C-contiguous -> 1D. The destination format is restricted to a single element native format in struct syntax. One of the formats must be a byte format (‘B’, ‘b’ or ‘c’). The byte length of the result must be the same as the original length. Cast 1D/long to 1D/unsigned bytes: >>> import array >>> a = array.array('l', [1,2,3]) >>> x = memoryview(a) >>> x.format 'l' >>> x.itemsize 8 >>> len(x) 3 >>> x.nbytes 24 >>> y = x.cast('B') >>> y.format 'B' >>> y.itemsize 1 >>> len(y) 24 >>> y.nbytes 24 Cast 1D/unsigned bytes to 1D/char: >>> b = bytearray(b'zyz') >>> x = memoryview(b) >>> x[0] = b'a' Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: memoryview: invalid value for format "B" >>> y = x.cast('c') >>> y[0] = b'a' >>> b bytearray(b'ayz') Cast 1D/bytes to 3D/ints to 1D/signed char: >>> import struct >>> buf = struct.pack("i"*12, *list(range(12))) >>> x = memoryview(buf) >>> y = x.cast('i', shape=[2,2,3]) >>> y.tolist() [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]] >>> y.format 'i' >>> y.itemsize 4 >>> len(y) 2 >>> y.nbytes 48 >>> z = y.cast('b') >>> z.format 'b' >>> z.itemsize 1 >>> len(z) 48 >>> z.nbytes 48 Cast 1D/unsigned long to 2D/unsigned long: >>> buf = struct.pack("L"*6, *list(range(6))) >>> x = memoryview(buf) >>> y = x.cast('L', shape=[2,3]) >>> len(y) 2 >>> y.nbytes 48 >>> y.tolist() [[0, 1, 2], [3, 4, 5]] New in version 3.3. Changed in version 3.5: The source format is no longer restricted when casting to a byte view.
python.library.stdtypes#memoryview.cast
contiguous A bool indicating whether the memory is contiguous. New in version 3.3.
python.library.stdtypes#memoryview.contiguous
c_contiguous A bool indicating whether the memory is C-contiguous. New in version 3.3.
python.library.stdtypes#memoryview.c_contiguous
format A string containing the format (in struct module style) for each element in the view. A memoryview can be created from exporters with arbitrary format strings, but some methods (e.g. tolist()) are restricted to native single element formats. Changed in version 3.3: format 'B' is now handled according to the struct module syntax. This means that memoryview(b'abc')[0] == b'abc'[0] == 97.
python.library.stdtypes#memoryview.format
f_contiguous A bool indicating whether the memory is Fortran contiguous. New in version 3.3.
python.library.stdtypes#memoryview.f_contiguous
hex([sep[, bytes_per_sep]]) Return a string object containing two hexadecimal digits for each byte in the buffer. >>> m = memoryview(b"abc") >>> m.hex() '616263' New in version 3.5. Changed in version 3.8: Similar to bytes.hex(), memoryview.hex() now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.
python.library.stdtypes#memoryview.hex
itemsize The size in bytes of each element of the memoryview: >>> import array, struct >>> m = memoryview(array.array('H', [32000, 32001, 32002])) >>> m.itemsize 2 >>> m[0] 32000 >>> struct.calcsize('H') == m.itemsize True
python.library.stdtypes#memoryview.itemsize
nbytes nbytes == product(shape) * itemsize == len(m.tobytes()). This is the amount of space in bytes that the array would use in a contiguous representation. It is not necessarily equal to len(m): >>> import array >>> a = array.array('i', [1,2,3,4,5]) >>> m = memoryview(a) >>> len(m) 5 >>> m.nbytes 20 >>> y = m[::2] >>> len(y) 3 >>> y.nbytes 12 >>> len(y.tobytes()) 12 Multi-dimensional arrays: >>> import struct >>> buf = struct.pack("d"*12, *[1.5*x for x in range(12)]) >>> x = memoryview(buf) >>> y = x.cast('d', shape=[3,4]) >>> y.tolist() [[0.0, 1.5, 3.0, 4.5], [6.0, 7.5, 9.0, 10.5], [12.0, 13.5, 15.0, 16.5]] >>> len(y) 3 >>> y.nbytes 96 New in version 3.3.
python.library.stdtypes#memoryview.nbytes
ndim An integer indicating how many dimensions of a multi-dimensional array the memory represents.
python.library.stdtypes#memoryview.ndim
obj The underlying object of the memoryview: >>> b = bytearray(b'xyz') >>> m = memoryview(b) >>> m.obj is b True New in version 3.3.
python.library.stdtypes#memoryview.obj
readonly A bool indicating whether the memory is read only.
python.library.stdtypes#memoryview.readonly
release() Release the underlying buffer exposed by the memoryview object. Many objects take special actions when a view is held on them (for example, a bytearray would temporarily forbid resizing); therefore, calling release() is handy to remove these restrictions (and free any dangling resources) as soon as possible. After this method has been called, any further operation on the view raises a ValueError (except release() itself which can be called multiple times): >>> m = memoryview(b'abc') >>> m.release() >>> m[0] Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: operation forbidden on released memoryview object The context management protocol can be used for a similar effect, using the with statement: >>> with memoryview(b'abc') as m: ... m[0] ... 97 >>> m[0] Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: operation forbidden on released memoryview object New in version 3.2.
python.library.stdtypes#memoryview.release
shape A tuple of integers the length of ndim giving the shape of the memory as an N-dimensional array. Changed in version 3.3: An empty tuple instead of None when ndim = 0.
python.library.stdtypes#memoryview.shape
strides A tuple of integers the length of ndim giving the size in bytes to access each element for each dimension of the array. Changed in version 3.3: An empty tuple instead of None when ndim = 0.
python.library.stdtypes#memoryview.strides
suboffsets Used internally for PIL-style arrays. The value is informational only.
python.library.stdtypes#memoryview.suboffsets
tobytes(order=None) Return the data in the buffer as a bytestring. This is equivalent to calling the bytes constructor on the memoryview. >>> m = memoryview(b"abc") >>> m.tobytes() b'abc' >>> bytes(m) b'abc' For non-contiguous arrays the result is equal to the flattened list representation with all elements converted to bytes. tobytes() supports all format strings, including those that are not in struct module syntax. New in version 3.8: order can be {‘C’, ‘F’, ‘A’}. When order is ‘C’ or ‘F’, the data of the original array is converted to C or Fortran order. For contiguous views, ‘A’ returns an exact copy of the physical memory. In particular, in-memory Fortran order is preserved. For non-contiguous views, the data is converted to C first. order=None is the same as order=’C’.
python.library.stdtypes#memoryview.tobytes
tolist() Return the data in the buffer as a list of elements. >>> memoryview(b'abc').tolist() [97, 98, 99] >>> import array >>> a = array.array('d', [1.1, 2.2, 3.3]) >>> m = memoryview(a) >>> m.tolist() [1.1, 2.2, 3.3] Changed in version 3.3: tolist() now supports all single character native formats in struct module syntax as well as multi-dimensional representations.
python.library.stdtypes#memoryview.tolist
toreadonly() Return a readonly version of the memoryview object. The original memoryview object is unchanged. >>> m = memoryview(bytearray(b'abc')) >>> mm = m.toreadonly() >>> mm.tolist() [89, 98, 99] >>> mm[0] = 42 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot modify read-only memory >>> m[0] = 43 >>> mm.tolist() [43, 98, 99] New in version 3.8.
python.library.stdtypes#memoryview.toreadonly
__eq__(exporter) A memoryview and a PEP 3118 exporter are equal if their shapes are equivalent and if all corresponding values are equal when the operands’ respective format codes are interpreted using struct syntax. For the subset of struct format strings currently supported by tolist(), v and w are equal if v.tolist() == w.tolist(): >>> import array >>> a = array.array('I', [1, 2, 3, 4, 5]) >>> b = array.array('d', [1.0, 2.0, 3.0, 4.0, 5.0]) >>> c = array.array('b', [5, 3, 1]) >>> x = memoryview(a) >>> y = memoryview(b) >>> x == a == y == b True >>> x.tolist() == a.tolist() == y.tolist() == b.tolist() True >>> z = y[::-2] >>> z == c True >>> z.tolist() == c.tolist() True If either format string is not supported by the struct module, then the objects will always compare as unequal (even if the format strings and buffer contents are identical): >>> from ctypes import BigEndianStructure, c_long >>> class BEPoint(BigEndianStructure): ... _fields_ = [("x", c_long), ("y", c_long)] ... >>> point = BEPoint(100, 200) >>> a = memoryview(point) >>> b = memoryview(point) >>> a == point False >>> a == b False Note that, as with floating point numbers, v is w does not imply v == w for memoryview objects. Changed in version 3.3: Previous versions compared the raw memory disregarding the item format and the logical array structure.
python.library.stdtypes#memoryview.__eq__
mimetypes — Map filenames to MIME types Source code: Lib/mimetypes.py The mimetypes module converts between a filename or URL and the MIME type associated with the filename extension. Conversions are provided from filename to MIME type and from MIME type to filename extension; encodings are not supported for the latter conversion. The module provides one class and a number of convenience functions. The functions are the normal interface to this module, but some applications may be interested in the class as well. The functions described below provide the primary interface for this module. If the module has not been initialized, they will call init() if they rely on the information init() sets up. mimetypes.guess_type(url, strict=True) Guess the type of a file based on its filename, path or URL, given by url. URL can be a string or a path-like object. The return value is a tuple (type, encoding) where type is None if the type can’t be guessed (missing or unknown suffix) or a string of the form 'type/subtype', usable for a MIME content-type header. encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip). The encoding is suitable for use as a Content-Encoding header, not as a Content-Transfer-Encoding header. The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitively, then case insensitively. The optional strict argument is a flag specifying whether the list of known MIME types is limited to only the official types registered with IANA. When strict is True (the default), only the IANA types are supported; when strict is False, some additional non-standard but commonly used MIME types are also recognized. Changed in version 3.8: Added support for url being a path-like object. mimetypes.guess_all_extensions(type, strict=True) Guess the extensions for a file based on its MIME type, given by type. The return value is a list of strings giving all possible filename extensions, including the leading dot ('.'). The extensions are not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type type by guess_type(). The optional strict argument has the same meaning as with the guess_type() function. mimetypes.guess_extension(type, strict=True) Guess the extension for a file based on its MIME type, given by type. The return value is a string giving a filename extension, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type type by guess_type(). If no extension can be guessed for type, None is returned. The optional strict argument has the same meaning as with the guess_type() function. Some additional functions and data items are available for controlling the behavior of the module. mimetypes.init(files=None) 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. mimetypes.read_mime_types(filename) Load the type map given in the file filename, if it exists. The type map is returned as a dictionary mapping filename extensions, including the leading dot ('.'), to strings of the form 'type/subtype'. If the file filename does not exist or cannot be read, None is returned. mimetypes.add_type(type, ext, strict=True) Add a mapping from the MIME type type to the extension ext. When the extension is already known, the new type will replace the old one. When the type is already known the extension will be added to the list of known extensions. When strict is True (the default), the mapping will be added to the official MIME types, otherwise to the non-standard ones. mimetypes.inited Flag indicating whether or not the global data structures have been initialized. This is set to True by init(). mimetypes.knownfiles List of type map file names commonly installed. These files are typically named mime.types and are installed in different locations by different packages. mimetypes.suffix_map Dictionary mapping suffixes to suffixes. This is used to allow recognition of encoded files for which the encoding and the type are indicated by the same extension. For example, the .tgz extension is mapped to .tar.gz to allow the encoding and type to be recognized separately. mimetypes.encodings_map Dictionary mapping filename extensions to encoding types. mimetypes.types_map Dictionary mapping filename extensions to MIME types. mimetypes.common_types Dictionary mapping filename extensions to non-standard, but commonly found MIME types. An example usage of the module: >>> import mimetypes >>> mimetypes.init() >>> mimetypes.knownfiles ['/etc/mime.types', '/etc/httpd/mime.types', ... ] >>> mimetypes.suffix_map['.tgz'] '.tar.gz' >>> mimetypes.encodings_map['.gz'] 'gzip' >>> mimetypes.types_map['.tgz'] 'application/x-tar-gz' MimeTypes Objects The MimeTypes class may be useful for applications which may want more than one MIME-type database; it provides an interface similar to the one of the mimetypes module. class mimetypes.MimeTypes(filenames=(), strict=True) This class represents a MIME-types database. By default, it provides access to the same database as the rest of this module. The initial database is a copy of that provided by the module, and may be extended by loading additional mime.types-style files into the database using the read() or readfp() methods. The mapping dictionaries may also be cleared before loading additional data if the default data is not desired. The optional filenames parameter can be used to cause additional files to be loaded “on top” of the default database. suffix_map Dictionary mapping suffixes to suffixes. This is used to allow recognition of encoded files for which the encoding and the type are indicated by the same extension. For example, the .tgz extension is mapped to .tar.gz to allow the encoding and type to be recognized separately. This is initially a copy of the global suffix_map defined in the module. encodings_map Dictionary mapping filename extensions to encoding types. This is initially a copy of the global encodings_map defined in the module. types_map Tuple containing two dictionaries, mapping filename extensions to MIME types: the first dictionary is for the non-standards types and the second one is for the standard types. They are initialized by common_types and types_map. types_map_inv Tuple containing two dictionaries, mapping MIME types to a list of filename extensions: the first dictionary is for the non-standards types and the second one is for the standard types. They are initialized by common_types and types_map. guess_extension(type, strict=True) Similar to the guess_extension() function, using the tables stored as part of the object. guess_type(url, strict=True) Similar to the guess_type() function, using the tables stored as part of the object. guess_all_extensions(type, strict=True) Similar to the guess_all_extensions() function, using the tables stored as part of the object. read(filename, strict=True) Load MIME information from a file named filename. This uses readfp() to parse the file. If strict is True, information will be added to list of standard types, else to the list of non-standard types. readfp(fp, strict=True) Load MIME type information from an open file fp. The file must have the format of the standard mime.types files. If strict is True, information will be added to the list of standard types, else to the list of non-standard types. read_windows_registry(strict=True) Load MIME type information from the Windows registry. Availability: Windows. If strict is True, information will be added to the list of standard types, else to the list of non-standard types. New in version 3.2.
python.library.mimetypes
mimetypes.add_type(type, ext, strict=True) Add a mapping from the MIME type type to the extension ext. When the extension is already known, the new type will replace the old one. When the type is already known the extension will be added to the list of known extensions. When strict is True (the default), the mapping will be added to the official MIME types, otherwise to the non-standard ones.
python.library.mimetypes#mimetypes.add_type
mimetypes.common_types Dictionary mapping filename extensions to non-standard, but commonly found MIME types.
python.library.mimetypes#mimetypes.common_types
mimetypes.encodings_map Dictionary mapping filename extensions to encoding types.
python.library.mimetypes#mimetypes.encodings_map
mimetypes.guess_all_extensions(type, strict=True) Guess the extensions for a file based on its MIME type, given by type. The return value is a list of strings giving all possible filename extensions, including the leading dot ('.'). The extensions are not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type type by guess_type(). The optional strict argument has the same meaning as with the guess_type() function.
python.library.mimetypes#mimetypes.guess_all_extensions
mimetypes.guess_extension(type, strict=True) Guess the extension for a file based on its MIME type, given by type. The return value is a string giving a filename extension, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type type by guess_type(). If no extension can be guessed for type, None is returned. The optional strict argument has the same meaning as with the guess_type() function.
python.library.mimetypes#mimetypes.guess_extension
mimetypes.guess_type(url, strict=True) Guess the type of a file based on its filename, path or URL, given by url. URL can be a string or a path-like object. The return value is a tuple (type, encoding) where type is None if the type can’t be guessed (missing or unknown suffix) or a string of the form 'type/subtype', usable for a MIME content-type header. encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip). The encoding is suitable for use as a Content-Encoding header, not as a Content-Transfer-Encoding header. The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitively, then case insensitively. The optional strict argument is a flag specifying whether the list of known MIME types is limited to only the official types registered with IANA. When strict is True (the default), only the IANA types are supported; when strict is False, some additional non-standard but commonly used MIME types are also recognized. Changed in version 3.8: Added support for url being a path-like object.
python.library.mimetypes#mimetypes.guess_type
mimetypes.init(files=None) 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.
python.library.mimetypes#mimetypes.init
mimetypes.inited Flag indicating whether or not the global data structures have been initialized. This is set to True by init().
python.library.mimetypes#mimetypes.inited
mimetypes.knownfiles List of type map file names commonly installed. These files are typically named mime.types and are installed in different locations by different packages.
python.library.mimetypes#mimetypes.knownfiles
class mimetypes.MimeTypes(filenames=(), strict=True) This class represents a MIME-types database. By default, it provides access to the same database as the rest of this module. The initial database is a copy of that provided by the module, and may be extended by loading additional mime.types-style files into the database using the read() or readfp() methods. The mapping dictionaries may also be cleared before loading additional data if the default data is not desired. The optional filenames parameter can be used to cause additional files to be loaded “on top” of the default database. suffix_map Dictionary mapping suffixes to suffixes. This is used to allow recognition of encoded files for which the encoding and the type are indicated by the same extension. For example, the .tgz extension is mapped to .tar.gz to allow the encoding and type to be recognized separately. This is initially a copy of the global suffix_map defined in the module. encodings_map Dictionary mapping filename extensions to encoding types. This is initially a copy of the global encodings_map defined in the module. types_map Tuple containing two dictionaries, mapping filename extensions to MIME types: the first dictionary is for the non-standards types and the second one is for the standard types. They are initialized by common_types and types_map. types_map_inv Tuple containing two dictionaries, mapping MIME types to a list of filename extensions: the first dictionary is for the non-standards types and the second one is for the standard types. They are initialized by common_types and types_map. guess_extension(type, strict=True) Similar to the guess_extension() function, using the tables stored as part of the object. guess_type(url, strict=True) Similar to the guess_type() function, using the tables stored as part of the object. guess_all_extensions(type, strict=True) Similar to the guess_all_extensions() function, using the tables stored as part of the object. read(filename, strict=True) Load MIME information from a file named filename. This uses readfp() to parse the file. If strict is True, information will be added to list of standard types, else to the list of non-standard types. readfp(fp, strict=True) Load MIME type information from an open file fp. The file must have the format of the standard mime.types files. If strict is True, information will be added to the list of standard types, else to the list of non-standard types. read_windows_registry(strict=True) Load MIME type information from the Windows registry. Availability: Windows. If strict is True, information will be added to the list of standard types, else to the list of non-standard types. New in version 3.2.
python.library.mimetypes#mimetypes.MimeTypes
encodings_map Dictionary mapping filename extensions to encoding types. This is initially a copy of the global encodings_map defined in the module.
python.library.mimetypes#mimetypes.MimeTypes.encodings_map
guess_all_extensions(type, strict=True) Similar to the guess_all_extensions() function, using the tables stored as part of the object.
python.library.mimetypes#mimetypes.MimeTypes.guess_all_extensions
guess_extension(type, strict=True) Similar to the guess_extension() function, using the tables stored as part of the object.
python.library.mimetypes#mimetypes.MimeTypes.guess_extension
guess_type(url, strict=True) Similar to the guess_type() function, using the tables stored as part of the object.
python.library.mimetypes#mimetypes.MimeTypes.guess_type
read(filename, strict=True) Load MIME information from a file named filename. This uses readfp() to parse the file. If strict is True, information will be added to list of standard types, else to the list of non-standard types.
python.library.mimetypes#mimetypes.MimeTypes.read
readfp(fp, strict=True) Load MIME type information from an open file fp. The file must have the format of the standard mime.types files. If strict is True, information will be added to the list of standard types, else to the list of non-standard types.
python.library.mimetypes#mimetypes.MimeTypes.readfp
read_windows_registry(strict=True) Load MIME type information from the Windows registry. Availability: Windows. If strict is True, information will be added to the list of standard types, else to the list of non-standard types. New in version 3.2.
python.library.mimetypes#mimetypes.MimeTypes.read_windows_registry