A subclass of Mailbox for mailboxes in MH format. Parameter factory is a callable object that accepts a file-like message representation (which behaves as if opened in binary mode) and returns a custom representation. If factory is None, MHMessage is used as the default message representation. If create is True, the mailbox is created if it does not exist.
MH is a directory-based mailbox format invented for the MH Message Handling System, a mail user agent. Each message in an MH mailbox resides in its own file. An MH mailbox may contain other MH mailboxes (called folders) in addition to messages. Folders may be nested indefinitely. MH mailboxes also support sequences, which are named lists used to logically group messages without moving them to sub-folders. Sequences are defined in a file called .mh_sequences in each folder.
The MH class manipulates MH mailboxes, but it does not attempt to emulate all of mh’s behaviors. In particular, it does not modify and is not affected by the context or .mh_profile files that are used by mh to store its state and configuration.
MH instances have all of the methods of Mailbox in addition to the following:
Return a list of the names of all folders.
Return an MH instance representing the folder whose name is folder. A NoSuchMailboxError exception is raised if the folder does not exist.
Create a folder whose name is folder and return an MH instance representing it.
Delete the folder whose name is folder. If the folder contains any messages, a NotEmptyError exception will be raised and the folder will not be deleted.
Return a dictionary of sequence names mapped to key lists. If there are no sequences, the empty dictionary is returned.
Re-define the sequences that exist in the mailbox based upon sequences, a dictionary of names mapped to key lists, like returned by get_sequences().
Rename messages in the mailbox as necessary to eliminate gaps in numbering. Entries in the sequences list are updated correspondingly.
Note
Already-issued keys are invalidated by this operation and should not be subsequently used.
Some Mailbox methods implemented by MH deserve special remarks:
These methods immediately delete the message. The MH convention of marking a message for deletion by prepending a comma to its name is not used.
Three locking mechanisms are used—dot locking and, if available, the flock() and lockf() system calls. For MH mailboxes, locking the mailbox means locking the .mh_sequences file and, only for the duration of any operations that affect them, locking individual message files.
Depending upon the host platform, it may not be possible to remove the underlying message while the returned file remains open.
All changes to MH mailboxes are immediately applied, so this method does nothing.
MH instances do not keep any open files, so this method is equivalent to unlock().


Create a folder whose name is folder and return an MH instance representing it.


MH instances do not keep any open files, so this method is equivalent to unlock().


These methods immediately delete the message. The MH convention of marking a message for deletion by prepending a comma to its name is not used.


All changes to MH mailboxes are immediately applied, so this method does nothing.


Depending upon the host platform, it may not be possible to remove the underlying message while the returned file remains open.


Return an MH instance representing the folder whose name is folder. A NoSuchMailboxError exception is raised if the folder does not exist.


Return a dictionary of sequence names mapped to key lists. If there are no sequences, the empty dictionary is returned.


Return a list of the names of all folders.


Three locking mechanisms are used—dot locking and, if available, the flock() and lockf() system calls. For MH mailboxes, locking the mailbox means locking the .mh_sequences file and, only for the duration of any operations that affect them, locking individual message files.


Rename messages in the mailbox as necessary to eliminate gaps in numbering. Entries in the sequences list are updated correspondingly.
Note
Already-issued keys are invalidated by this operation and should not be subsequently used.


Delete the folder whose name is folder. If the folder contains any messages, a NotEmptyError exception will be raised and the folder will not be deleted.


Re-define the sequences that exist in the mailbox based upon sequences, a dictionary of names mapped to key lists, like returned by get_sequences().


A message with MH-specific behaviors. Parameter message has the same meaning as with the Message constructor.
MH messages do not support marks or flags in the traditional sense, but they do support sequences, which are logical groupings of arbitrary messages. Some mail reading programs (although not the standard mh and nmh) use sequences in much the same way flags are used with other formats, as follows:
Sequence
Explanation
unseen
Not read, but previously detected by MUA
replied
Replied to
flagged
Marked as important
MHMessage instances offer the following methods:
Return a list of the names of sequences that include this message.
Set the list of sequences that include this message.
Add sequence to the list of sequences that include this message.
Remove sequence from the list of sequences that include this message.


Add sequence to the list of sequences that include this message.


Return a list of the names of sequences that include this message.


Remove sequence from the list of sequences that include this message.


Set the list of sequences that include this message.


A subclass of Mailbox for mailboxes in MMDF format. Parameter factory is a callable object that accepts a file-like message representation (which behaves as if opened in binary mode) and returns a custom representation. If factory is None, MMDFMessage is used as the default message representation. If create is True, the mailbox is created if it does not exist.
MMDF is a single-file mailbox format invented for the Multichannel Memorandum Distribution Facility, a mail transfer agent. Each message is in the same form as an mbox message but is bracketed before and after by lines containing four Control-A ('\001') characters. As with the mbox format, the beginning of each message is indicated by a line whose first five characters are “From “, but additional occurrences of “From ” are not transformed to “>From ” when storing messages because the extra message separator lines prevent mistaking such occurrences for the starts of subsequent messages.
Some Mailbox methods implemented by MMDF deserve special remarks:
Using the file after calling flush() or close() on the MMDF instance may yield unpredictable results or raise an exception.
Three locking mechanisms are used—dot locking and, if available, the flock() and lockf() system calls.


Using the file after calling flush() or close() on the MMDF instance may yield unpredictable results or raise an exception.


Three locking mechanisms are used—dot locking and, if available, the flock() and lockf() system calls.


A message with MMDF-specific behaviors. Parameter message has the same meaning as with the Message constructor.
As with message in an mbox mailbox, MMDF messages are stored with the sender’s address and the delivery date in an initial line beginning with “From “. Likewise, flags that indicate the state of the message are typically stored in Status and X-Status headers.
Conventional flags for MMDF messages are identical to those of mbox message and are as follows:
Flag
Meaning
Explanation
R
Read
Read
O
Old
Previously detected by MUA
D
Deleted
Marked for subsequent deletion
F
Flagged
Marked as important
A
Answered
Replied to
The “R” and “O” flags are stored in the Status header, and the “D”, “F”, and “A” flags are stored in the X-Status header. The flags and headers typically appear in the order mentioned.
MMDFMessage instances offer the following methods, which are identical to those offered by mboxMessage:
Return a string representing the “From ” line that marks the start of the message in an mbox mailbox. The leading “From ” and the trailing newline are excluded.
Set the “From ” line to from_, which should be specified without a leading “From ” or trailing newline. For convenience, time_ may be specified and will be formatted appropriately and appended to from_. If time_ is specified, it should be a time.struct_time instance, a tuple suitable for passing to time.strftime(), or True (to use time.gmtime()).
Return a string specifying the flags that are currently set. If the message complies with the conventional format, the result is the concatenation in the following order of zero or one occurrence of each of 'R', 'O', 'D', 'F', and 'A'.
Set the flags specified by flags and unset all others. Parameter flags should be the concatenation in any order of zero or more occurrences of each of 'R', 'O', 'D', 'F', and 'A'.
Set the flag(s) specified by flag without changing other flags. To add more than one flag at a time, flag may be a string of more than one character.
Unset the flag(s) specified by flag without changing other flags. To remove more than one flag at a time, flag maybe a string of more than one character.


Set the flag(s) specified by flag without changing other flags. To add more than one flag at a time, flag may be a string of more than one character.


Return a string specifying the flags that are currently set. If the message complies with the conventional format, the result is the concatenation in the following order of zero or one occurrence of each of 'R', 'O', 'D', 'F', and 'A'.


Return a string representing the “From ” line that marks the start of the message in an mbox mailbox. The leading “From ” and the trailing newline are excluded.


Unset the flag(s) specified by flag without changing other flags. To remove more than one flag at a time, flag maybe a string of more than one character.


Set the flags specified by flags and unset all others. Parameter flags should be the concatenation in any order of zero or more occurrences of each of 'R', 'O', 'D', 'F', and 'A'.


Set the “From ” line to from_, which should be specified without a leading “From ” or trailing newline. For convenience, time_ may be specified and will be formatted appropriately and appended to from_. If time_ is specified, it should be a time.struct_time instance, a tuple suitable for passing to time.strftime(), or True (to use time.gmtime()).


Raised when a mailbox is expected but is not found, such as when instantiating a Mailbox subclass with a path that does not exist (and with the create parameter set to False), or when opening a folder that does not exist.


Raised when a mailbox is not empty but is expected to be, such as when deleting a folder that contains messages.


Source code: Lib/mailcap.py
Mailcap files are used to configure how MIME-aware applications such as mail readers and Web browsers react to files with different MIME types. (The name “mailcap” is derived from the phrase “mail capability”.) For example, a mailcap file might contain a line like video/mpeg; xmpeg %s. Then, if the user encounters an email message or Web document with the MIME type video/mpeg, %s will be replaced by a filename (usually one belonging to a temporary file) and the xmpeg program can be automatically started to view the file.
The mailcap format is documented in RFC 1524, “A User Agent Configuration Mechanism For Multimedia Mail Format Information”, but is not an Internet standard. However, mailcap files are supported on most Unix systems.
Return a 2-tuple; the first element is a string containing the command line to be executed (which can be passed to os.system()), and the second element is the mailcap entry for a given MIME type. If no matching MIME type can be found, (None, None) is returned.
key is the name of the field desired, which represents the type of activity to be performed; the default value is ‘view’, since in the most common case you simply want to view the body of the MIME-typed data. Other possible values might be ‘compose’ and ‘edit’, if you wanted to create a new body of the given MIME type or alter the existing body data. See RFC 1524 for a complete list of these fields.
filename is the filename to be substituted for %s in the command line; the default value is '/dev/null' which is almost certainly not what you want, so usually you’ll override it by specifying a filename.
plist can be a list containing named parameters; the default value is simply an empty list. Each entry in the list must be a string containing the parameter name, an equals sign ('='), and the parameter’s value. Mailcap entries can contain named parameters like %{foo}, which will be replaced by the value of the parameter named ‘foo’. For example, if the command line showpartial
%{id} %{number} %{total} was in a mailcap file, and plist was set to ['id=1', 'number=2', 'total=3'], the resulting command line would be 'showpartial 1 2 3'.
In a mailcap file, the “test” field can optionally be specified to test some external condition (such as the machine architecture, or the window system in use) to determine whether or not the mailcap line applies. findmatch() will automatically check such conditions and skip the entry if the check fails.
Returns a dictionary mapping MIME types to a list of mailcap file entries. This dictionary must be passed to the findmatch() function. An entry is stored as a list of dictionaries, but it shouldn’t be necessary to know the details of this representation.
The information is derived from all of the mailcap files found on the system. Settings in the user’s mailcap file $HOME/.mailcap will override settings in the system mailcap files /etc/mailcap, /usr/etc/mailcap, and /usr/local/etc/mailcap.
An example usage:


Return a 2-tuple; the first element is a string containing the command line to be executed (which can be passed to os.system()), and the second element is the mailcap entry for a given MIME type. If no matching MIME type can be found, (None, None) is returned.
key is the name of the field desired, which represents the type of activity to be performed; the default value is ‘view’, since in the most common case you simply want to view the body of the MIME-typed data. Other possible values might be ‘compose’ and ‘edit’, if you wanted to create a new body of the given MIME type or alter the existing body data. See RFC 1524 for a complete list of these fields.
filename is the filename to be substituted for %s in the command line; the default value is '/dev/null' which is almost certainly not what you want, so usually you’ll override it by specifying a filename.
plist can be a list containing named parameters; the default value is simply an empty list. Each entry in the list must be a string containing the parameter name, an equals sign ('='), and the parameter’s value. Mailcap entries can contain named parameters like %{foo}, which will be replaced by the value of the parameter named ‘foo’. For example, if the command line showpartial
%{id} %{number} %{total} was in a mailcap file, and plist was set to ['id=1', 'number=2', 'total=3'], the resulting command line would be 'showpartial 1 2 3'.
In a mailcap file, the “test” field can optionally be specified to test some external condition (such as the machine architecture, or the window system in use) to determine whether or not the mailcap line applies. findmatch() will automatically check such conditions and skip the entry if the check fails.


Returns a dictionary mapping MIME types to a list of mailcap file entries. This dictionary must be passed to the findmatch() function. An entry is stored as a list of dictionaries, but it shouldn’t be necessary to know the details of this representation.
The information is derived from all of the mailcap files found on the system. Settings in the user’s mailcap file $HOME/.mailcap will override settings in the system mailcap files /etc/mailcap, /usr/etc/mailcap, and /usr/local/etc/mailcap.


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


This module contains functions that can read and write Python values in a binary format. The format is specific to Python, but independent of machine architecture issues (e.g., you can write a Python value to a file on a PC, transport the file to a Sun, and read it back there). Details of the format are undocumented on purpose; it may change between Python versions (although it rarely does). 1
This is not a general “persistence” module. For general persistence and transfer of Python objects through RPC calls, see the modules pickle and shelve. The marshal module exists mainly to support reading and writing the “pseudo-compiled” code for Python modules of .pyc files. Therefore, the Python maintainers reserve the right to modify the marshal format in backward incompatible ways should the need arise. If you’re serializing and de-serializing Python objects, use the pickle module instead – the performance is comparable, version independence is guaranteed, and pickle supports a substantially wider range of objects than marshal.
Warning
The marshal module is not intended to be secure against erroneous or maliciously constructed data. Never unmarshal data received from an untrusted or unauthenticated source.
Not all Python object types are supported; in general, only objects whose value is independent from a particular invocation of Python can be written and read by this module. The following types are supported: booleans, integers, floating point numbers, complex numbers, strings, bytes, bytearrays, tuples, lists, sets, frozensets, dictionaries, and code objects, where it should be understood that tuples, lists, sets, frozensets and dictionaries are only supported as long as the values contained therein are themselves supported. The singletons None, Ellipsis and StopIteration can also be marshalled and unmarshalled. For format version lower than 3, recursive lists, sets and dictionaries cannot be written (see below).
There are functions that read/write files as well as functions operating on bytes-like objects.
The module defines these functions:
Write the value on the open file. The value must be a supported type. The file must be a writeable binary file.
If the value has (or contains an object that has) an unsupported type, a ValueError exception is raised — but garbage data will also be written to the file. The object will not be properly read back by load().
The version argument indicates the data format that dump should use (see below).
Read one value from the open file and return it. If no valid value is read (e.g. because the data has a different Python version’s incompatible marshal format), raise EOFError, ValueError or TypeError. The file must be a readable binary file.
Note
If an object containing an unsupported type was marshalled with dump(), load() will substitute None for the unmarshallable type.
Return the bytes object that would be written to a file by dump(value, file). The value must be a supported type. Raise a ValueError exception if value has (or contains an object that has) an unsupported type.
The version argument indicates the data format that dumps should use (see below).
Convert the bytes-like object to a value. If no valid value is found, raise EOFError, ValueError or TypeError. Extra bytes in the input are ignored.
In addition, the following constants are defined:
Indicates the format that the module uses. Version 0 is the historical format, version 1 shares interned strings and version 2 uses a binary format for floating point numbers. Version 3 adds support for object instancing and recursion. The current version is 4.
The name of this module stems from a bit of terminology used by the designers of Modula-3 (amongst others), who use the term “marshalling” for shipping of data around in a self-contained form. Strictly speaking, “to marshal” means to convert some data from internal to external form (in an RPC buffer for instance) and “unmarshalling” for the reverse process.


Write the value on the open file. The value must be a supported type. The file must be a writeable binary file.
If the value has (or contains an object that has) an unsupported type, a ValueError exception is raised — but garbage data will also be written to the file. The object will not be properly read back by load().
The version argument indicates the data format that dump should use (see below).


Return the bytes object that would be written to a file by dump(value, file). The value must be a supported type. Raise a ValueError exception if value has (or contains an object that has) an unsupported type.
The version argument indicates the data format that dumps should use (see below).


Read one value from the open file and return it. If no valid value is read (e.g. because the data has a different Python version’s incompatible marshal format), raise EOFError, ValueError or TypeError. The file must be a readable binary file.
Note
If an object containing an unsupported type was marshalled with dump(), load() will substitute None for the unmarshallable type.


Convert the bytes-like object to a value. If no valid value is found, raise EOFError, ValueError or TypeError. Extra bytes in the input are ignored.


Indicates the format that the module uses. Version 0 is the historical format, version 1 shares interned strings and version 2 uses a binary format for floating point numbers. Version 3 adds support for object instancing and recursion. The current version is 4.


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.
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.
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.
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.
Return the absolute value of 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.
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.
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.
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.
Return an accurate floating point sum of values in the iterable. Avoids loss of precision by tracking multiple intermediate partial sums:
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.
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.
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
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.
Return True if x is a positive or negative infinity, and False otherwise.
Return True if x is a NaN (not a number), and False otherwise.
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.
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.
Return x * (2**i). This is essentially the inverse of function frexp().
Return the fractional and integer parts of x. Both results carry the sign of x and are floats.
Return the next floating-point value after x towards y.
If x is equal to y, return y.
Examples:
See also math.ulp().
New in version 3.9.
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.
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.
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.
Return the Real value x truncated to an Integral (usually an integer). Delegates to x.__trunc__().
Return the value of the least significant bit of the float 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.
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).
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:
New in version 3.2.
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).
Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.
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.
Return the base-10 logarithm of x. This is usually more accurate than log(x, 10).
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.
Return the square root of x.
Return the arc cosine of x, in radians. The result is between 0 and pi.
Return the arc sine of x, in radians. The result is between -pi/2 and pi/2.
Return the arc tangent of x, in radians. The result is between -pi/2 and pi/2.
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.
Return the cosine of x radians.
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:
New in version 3.8.
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.
Return the sine of x radians.
Return the tangent of x radians.
Convert angle x from radians to degrees.
Convert angle x from degrees to radians.
Hyperbolic functions are analogs of trigonometric functions that are based on hyperbolas instead of circles.
Return the inverse hyperbolic cosine of x.
Return the inverse hyperbolic sine of x.
Return the inverse hyperbolic tangent of x.
Return the hyperbolic cosine of x.
Return the hyperbolic sine of x.
Return the hyperbolic tangent of 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:
New in version 3.2.
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.
Return the Gamma function at x.
New in version 3.2.
Return the natural logarithm of the absolute value of the Gamma function at x.
New in version 3.2.
The mathematical constant π = 3.141592…, to available precision.
The mathematical constant e = 2.718281…, to available precision.
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.
A floating-point positive infinity. (For negative infinity, use -math.inf.) Equivalent to the output of float('inf').
New in version 3.5.
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
Complex number versions of many of these functions.


Return the arc cosine of x, in radians. The result is between 0 and pi.


Return the inverse hyperbolic cosine of x.


Return the arc sine of x, in radians. The result is between -pi/2 and pi/2.


Return the inverse hyperbolic sine of x.


Return the arc tangent of x, in radians. The result is between -pi/2 and pi/2.


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.


Return the inverse hyperbolic tangent of 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.


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.


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.


Convert angle x from radians to degrees.


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


The mathematical constant e = 2.718281…, to available precision.


Return the error function at x.
The erf() function can be used to compute traditional statistical functions such as the cumulative standard normal distribution:
New in version 3.2.


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.


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).


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


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.


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.


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.


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.


Return an accurate floating point sum of values in the iterable. Avoids loss of precision by tracking multiple intermediate partial sums:
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.


Return the Gamma function at x.
New in version 3.2.


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.


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.


A floating-point positive infinity. (For negative infinity, use -math.inf.) Equivalent to the output of float('inf').
New in version 3.5.


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


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.


Return True if x is a positive or negative infinity, and False otherwise.


Return True if x is a NaN (not a number), and False otherwise.


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.


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.


Return x * (2**i). This is essentially the inverse of function frexp().


Return the natural logarithm of the absolute value of the Gamma function at x.
New in version 3.2.


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).


Return the base-10 logarithm of x. This is usually more accurate than log(x, 10).


Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.


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.


Return the fractional and integer parts of x. Both results carry the sign of x and are floats.


A floating-point “not a number” (NaN) value. Equivalent to the output of float('nan').
New in version 3.5.


Return the next floating-point value after x towards y.
If x is equal to y, return y.
Examples:
See also math.ulp().
New in version 3.9.


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.


The mathematical constant π = 3.141592…, to available precision.


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.


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.


Convert angle x from degrees to radians.


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.


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.


Return the Real value x truncated to an Integral (usually an integer). Delegates to x.__trunc__().


Return the value of the least significant bit of the float x:
ULP stands for “Unit in the Last Place”.
See also math.nextafter() and sys.float_info.epsilon.
New in version 3.9.


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.


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.


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:
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:
If the underlying object is writable, the memoryview supports one-dimensional slice assignment. Resizing is not allowed:
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()):
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:
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():
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):
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.
Return the data in the buffer as a bytestring. This is equivalent to calling the bytes constructor on the memoryview.
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’.
Return a string object containing two hexadecimal digits for each byte in the buffer.
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.
Return the data in the buffer as a list of elements.
Changed in version 3.3: tolist() now supports all single character native formats in struct module syntax as well as multi-dimensional representations.
Return a readonly version of the memoryview object. The original memoryview object is unchanged.
New in version 3.8.
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):
The context management protocol can be used for a similar effect, using the with statement:
New in version 3.2.
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:
Cast 1D/unsigned bytes to 1D/char:
Cast 1D/bytes to 3D/ints to 1D/signed char:
Cast 1D/unsigned long to 2D/unsigned long:
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:
The underlying object of the memoryview:
New in version 3.3.
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):
Multi-dimensional arrays:
New in version 3.3.
A bool indicating whether the memory is read only.
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.
The size in bytes of each element of the memoryview:
An integer indicating how many dimensions of a multi-dimensional array the memory represents.
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.
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.
Used internally for PIL-style arrays. The value is informational only.
A bool indicating whether the memory is C-contiguous.
New in version 3.3.
A bool indicating whether the memory is Fortran contiguous.
New in version 3.3.
A bool indicating whether the memory is contiguous.
New in version 3.3.


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


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:
Cast 1D/unsigned bytes to 1D/char:
Cast 1D/bytes to 3D/ints to 1D/signed char:
Cast 1D/unsigned long to 2D/unsigned long:
New in version 3.3.
Changed in version 3.5: The source format is no longer restricted when casting to a byte view.


A bool indicating whether the memory is contiguous.
New in version 3.3.


A bool indicating whether the memory is C-contiguous.
New in version 3.3.


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.


A bool indicating whether the memory is Fortran contiguous.
New in version 3.3.


Return a string object containing two hexadecimal digits for each byte in the buffer.
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.


The size in bytes of each element of the memoryview:


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):
Multi-dimensional arrays:
New in version 3.3.


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


The underlying object of the memoryview:
New in version 3.3.


A bool indicating whether the memory is read only.


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):
The context management protocol can be used for a similar effect, using the with statement:
New in version 3.2.


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.


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.


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


Return the data in the buffer as a bytestring. This is equivalent to calling the bytes constructor on the memoryview.
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’.


Return the data in the buffer as a list of elements.
Changed in version 3.3: tolist() now supports all single character native formats in struct module syntax as well as multi-dimensional representations.


Return a readonly version of the memoryview object. The original memoryview object is unchanged.
New in version 3.8.


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():
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):
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.


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.
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.
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.
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.
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.
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.
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.
Flag indicating whether or not the global data structures have been initialized. This is set to True by init().
List of type map file names commonly installed. These files are typically named mime.types and are installed in different locations by different packages.
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.
Dictionary mapping filename extensions to encoding types.
Dictionary mapping filename extensions to MIME types.
Dictionary mapping filename extensions to non-standard, but commonly found MIME types.
An example usage of the module:
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.
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.
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.
Dictionary mapping filename extensions to encoding types. This is initially a copy of the global encodings_map defined in the module.
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.
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.
Similar to the guess_extension() function, using the tables stored as part of the object.
Similar to the guess_type() function, using the tables stored as part of the object.
Similar to the guess_all_extensions() function, using the tables stored as part of the object.
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.
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.
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.


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.


Dictionary mapping filename extensions to non-standard, but commonly found MIME types.


Dictionary mapping filename extensions to encoding types.


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.


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.


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.


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.


Flag indicating whether or not the global data structures have been initialized. This is set to True by init().


List of type map file names commonly installed. These files are typically named mime.types and are installed in different locations by different packages.


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.
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.
Dictionary mapping filename extensions to encoding types. This is initially a copy of the global encodings_map defined in the module.
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.
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.
Similar to the guess_extension() function, using the tables stored as part of the object.
Similar to the guess_type() function, using the tables stored as part of the object.
Similar to the guess_all_extensions() function, using the tables stored as part of the object.
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.
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.
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.


Dictionary mapping filename extensions to encoding types. This is initially a copy of the global encodings_map defined in the module.


Similar to the guess_all_extensions() function, using the tables stored as part of the object.


Similar to the guess_extension() function, using the tables stored as part of the object.


Similar to the guess_type() function, using the tables stored as part of the object.


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.


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.


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.


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.


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.


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.


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.


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.


Dictionary mapping filename extensions to MIME types.


Return the smallest item in an iterable or the smallest of two or more arguments.
If one positional argument is provided, it should be an iterable. The smallest item in the iterable is returned. If two or more positional arguments are provided, the smallest 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 minimal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc)[0] and heapq.nsmallest(1,
iterable, key=keyfunc).
New in version 3.4: The default keyword-only argument.
Changed in version 3.8: The key can be None.


Memory-mapped file objects behave like both bytearray and like file objects. You can use mmap objects in most places where bytearray are expected; for example, you can use the re module to search through a memory-mapped file. You can also change a single byte by doing obj[index] = 97, or change a subsequence by assigning to a slice: obj[i1:i2] = b'...'. You can also read and write data starting at the current file position, and seek() through the file to different positions.
A memory-mapped file is created by the mmap constructor, which is different on Unix and on Windows. In either case you must provide a file descriptor for a file opened for update. If you wish to map an existing Python file object, use its fileno() method to obtain the correct value for the fileno parameter. Otherwise, you can open the file using the os.open() function, which returns a file descriptor directly (the file still needs to be closed when done).
Note
If you want to create a memory-mapping for a writable, buffered file, you should flush() the file first. This is necessary to ensure that local modifications to the buffers are actually available to the mapping.
For both the Unix and Windows versions of the constructor, access may be specified as an optional keyword parameter. access accepts one of four values: ACCESS_READ, ACCESS_WRITE, or ACCESS_COPY to specify read-only, write-through or copy-on-write memory respectively, or ACCESS_DEFAULT to defer to prot. access can be used on both Unix and Windows. If access is not specified, Windows mmap returns a write-through mapping. The initial memory values for all three access types are taken from the specified file. Assignment to an ACCESS_READ memory map raises a TypeError exception. Assignment to an ACCESS_WRITE memory map affects both memory and the underlying file. Assignment to an ACCESS_COPY memory map affects memory but does not update the underlying file.
Changed in version 3.7: Added ACCESS_DEFAULT constant.
To map anonymous memory, -1 should be passed as the fileno along with the length.
(Windows version) Maps length bytes from the file specified by the file handle fileno, and creates a mmap object. If length is larger than the current size of the file, the file is extended to contain length bytes. If length is 0, the maximum length of the map is the current size of the file, except that if the file is empty Windows raises an exception (you cannot create an empty mapping on Windows).
tagname, if specified and not None, is a string giving a tag name for the mapping. Windows allows you to have many different mappings against the same file. If you specify the name of an existing tag, that tag is opened, otherwise a new tag of this name is created. If this parameter is omitted or None, the mapping is created without a name. Avoiding the use of the tag parameter will assist in keeping your code portable between Unix and Windows.
offset may be specified as a non-negative integer offset. mmap references will be relative to the offset from the beginning of the file. offset defaults to 0. offset must be a multiple of the ALLOCATIONGRANULARITY.
Raises an auditing event mmap.__new__ with arguments fileno, length, access, offset.
(Unix version) Maps length bytes from the file specified by the file descriptor fileno, and returns a mmap object. If length is 0, the maximum length of the map will be the current size of the file when mmap is called.
flags specifies the nature of the mapping. MAP_PRIVATE creates a private copy-on-write mapping, so changes to the contents of the mmap object will be private to this process, and MAP_SHARED creates a mapping that’s shared with all other processes mapping the same areas of the file. The default value is MAP_SHARED.
prot, if specified, gives the desired memory protection; the two most useful values are PROT_READ and PROT_WRITE, to specify that the pages may be read or written. prot defaults to PROT_READ | PROT_WRITE.
access may be specified in lieu of flags and prot as an optional keyword parameter. It is an error to specify both flags, prot and access. See the description of access above for information on how to use this parameter.
offset may be specified as a non-negative integer offset. mmap references will be relative to the offset from the beginning of the file. offset defaults to 0. offset must be a multiple of ALLOCATIONGRANULARITY which is equal to PAGESIZE on Unix systems.
To ensure validity of the created memory mapping the file specified by the descriptor fileno is internally automatically synchronized with physical backing store on Mac OS X and OpenVMS.
This example shows a simple way of using mmap:
mmap can also be used as a context manager in a with statement:
New in version 3.2: Context manager support.
The next example demonstrates how to create an anonymous map and exchange data between the parent and child processes:
Raises an auditing event mmap.__new__ with arguments fileno, length, access, offset.
Memory-mapped file objects support the following methods:
Closes the mmap. Subsequent calls to other methods of the object will result in a ValueError exception being raised. This will not close the open file.
True if the file is closed.
New in version 3.2.
Returns the lowest index in the object where the subsequence sub is found, such that sub is contained in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Returns -1 on failure.
Changed in version 3.5: Writable bytes-like object is now accepted.
Flushes changes made to the in-memory copy of a file back to disk. Without use of this call there is no guarantee that changes are written back before the object is destroyed. If offset and size are specified, only changes to the given range of bytes will be flushed to disk; otherwise, the whole extent of the mapping is flushed. offset must be a multiple of the PAGESIZE or ALLOCATIONGRANULARITY.
None is returned to indicate success. An exception is raised when the call failed.
Changed in version 3.8: Previously, a nonzero value was returned on success; zero was returned on error under Windows. A zero value was returned on success; an exception was raised on error under Unix.
Send advice option to the kernel about the memory region beginning at start and extending length bytes. option must be one of the MADV_* constants available on the system. If start and length are omitted, the entire mapping is spanned. On some systems (including Linux), start must be a multiple of the PAGESIZE.
Availability: Systems with the madvise() system call.
New in version 3.8.
Copy the count bytes starting at offset src to the destination index dest. If the mmap was created with ACCESS_READ, then calls to move will raise a TypeError exception.
Return a bytes containing up to n bytes starting from the current file position. If the argument is omitted, None or negative, return all bytes from the current file position to the end of the mapping. The file position is updated to point after the bytes that were returned.
Changed in version 3.3: Argument can be omitted or None.
Returns a byte at the current file position as an integer, and advances the file position by 1.
Returns a single line, starting at the current file position and up to the next newline. The file position is updated to point after the bytes that were returned.
Resizes the map and the underlying file, if any. If the mmap was created with ACCESS_READ or ACCESS_COPY, resizing the map will raise a TypeError exception.
Returns the highest index in the object where the subsequence sub is found, such that sub is contained in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Returns -1 on failure.
Changed in version 3.5: Writable bytes-like object is now accepted.
Set the file’s current position. whence argument is optional and defaults to os.SEEK_SET or 0 (absolute file positioning); other values are os.SEEK_CUR or 1 (seek relative to the current position) and os.SEEK_END or 2 (seek relative to the file’s end).
Return the length of the file, which can be larger than the size of the memory-mapped area.
Returns the current position of the file pointer.
Write the bytes in bytes into memory at the current position of the file pointer and return the number of bytes written (never less than len(bytes), since if the write fails, a ValueError will be raised). The file position is updated to point after the bytes that were written. If the mmap was created with ACCESS_READ, then writing to it will raise a TypeError exception.
Changed in version 3.5: Writable bytes-like object is now accepted.
Changed in version 3.6: The number of bytes written is now returned.
Write the integer byte into memory at the current position of the file pointer; the file position is advanced by 1. If the mmap was created with ACCESS_READ, then writing to it will raise a TypeError exception.
These options can be passed to mmap.madvise(). Not every option will be present on every system.
Availability: Systems with the madvise() system call.
New in version 3.8.


These options can be passed to mmap.madvise(). Not every option will be present on every system.
Availability: Systems with the madvise() system call.
New in version 3.8.


(Windows version) Maps length bytes from the file specified by the file handle fileno, and creates a mmap object. If length is larger than the current size of the file, the file is extended to contain length bytes. If length is 0, the maximum length of the map is the current size of the file, except that if the file is empty Windows raises an exception (you cannot create an empty mapping on Windows).
tagname, if specified and not None, is a string giving a tag name for the mapping. Windows allows you to have many different mappings against the same file. If you specify the name of an existing tag, that tag is opened, otherwise a new tag of this name is created. If this parameter is omitted or None, the mapping is created without a name. Avoiding the use of the tag parameter will assist in keeping your code portable between Unix and Windows.
offset may be specified as a non-negative integer offset. mmap references will be relative to the offset from the beginning of the file. offset defaults to 0. offset must be a multiple of the ALLOCATIONGRANULARITY.
Raises an auditing event mmap.__new__ with arguments fileno, length, access, offset.


Closes the mmap. Subsequent calls to other methods of the object will result in a ValueError exception being raised. This will not close the open file.


True if the file is closed.
New in version 3.2.


Returns the lowest index in the object where the subsequence sub is found, such that sub is contained in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Returns -1 on failure.
Changed in version 3.5: Writable bytes-like object is now accepted.


Flushes changes made to the in-memory copy of a file back to disk. Without use of this call there is no guarantee that changes are written back before the object is destroyed. If offset and size are specified, only changes to the given range of bytes will be flushed to disk; otherwise, the whole extent of the mapping is flushed. offset must be a multiple of the PAGESIZE or ALLOCATIONGRANULARITY.
None is returned to indicate success. An exception is raised when the call failed.
Changed in version 3.8: Previously, a nonzero value was returned on success; zero was returned on error under Windows. A zero value was returned on success; an exception was raised on error under Unix.


Send advice option to the kernel about the memory region beginning at start and extending length bytes. option must be one of the MADV_* constants available on the system. If start and length are omitted, the entire mapping is spanned. On some systems (including Linux), start must be a multiple of the PAGESIZE.
Availability: Systems with the madvise() system call.
New in version 3.8.


Copy the count bytes starting at offset src to the destination index dest. If the mmap was created with ACCESS_READ, then calls to move will raise a TypeError exception.


Return a bytes containing up to n bytes starting from the current file position. If the argument is omitted, None or negative, return all bytes from the current file position to the end of the mapping. The file position is updated to point after the bytes that were returned.
Changed in version 3.3: Argument can be omitted or None.


Returns a single line, starting at the current file position and up to the next newline. The file position is updated to point after the bytes that were returned.


Returns a byte at the current file position as an integer, and advances the file position by 1.


Resizes the map and the underlying file, if any. If the mmap was created with ACCESS_READ or ACCESS_COPY, resizing the map will raise a TypeError exception.


Returns the highest index in the object where the subsequence sub is found, such that sub is contained in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Returns -1 on failure.
Changed in version 3.5: Writable bytes-like object is now accepted.


Set the file’s current position. whence argument is optional and defaults to os.SEEK_SET or 0 (absolute file positioning); other values are os.SEEK_CUR or 1 (seek relative to the current position) and os.SEEK_END or 2 (seek relative to the file’s end).


Return the length of the file, which can be larger than the size of the memory-mapped area.


Returns the current position of the file pointer.


Write the bytes in bytes into memory at the current position of the file pointer and return the number of bytes written (never less than len(bytes), since if the write fails, a ValueError will be raised). The file position is updated to point after the bytes that were written. If the mmap was created with ACCESS_READ, then writing to it will raise a TypeError exception.
Changed in version 3.5: Writable bytes-like object is now accepted.
Changed in version 3.6: The number of bytes written is now returned.


Write the integer byte into memory at the current position of the file pointer; the file position is advanced by 1. If the mmap was created with ACCESS_READ, then writing to it will raise a TypeError exception.


Source code: Lib/modulefinder.py
This module provides a ModuleFinder class that can be used to determine the set of modules imported by a script. modulefinder.py can also be run as a script, giving the filename of a Python script as its argument, after which a report of the imported modules will be printed.
Record that the package named pkg_name can be found in the specified path.
Allows specifying that the module named oldname is in fact the package named newname.
This class provides run_script() and report() methods to determine the set of modules imported by a script. path can be a list of directories to search for modules; if not specified, sys.path is used. debug sets the debugging level; higher values make the class print debugging messages about what it’s doing. excludes is a list of module names to exclude from the analysis. replace_paths is a list of (oldpath, newpath) tuples that will be replaced in module paths.
Print a report to standard output that lists the modules imported by the script and their paths, as well as modules that are missing or seem to be missing.
Analyze the contents of the pathname file, which must contain Python code.
A dictionary mapping module names to modules. See Example usage of ModuleFinder.
The script that is going to get analyzed later on (bacon.py):
The script that will output the report of bacon.py:
Sample output (may vary depending on the architecture):


Record that the package named pkg_name can be found in the specified path.


This class provides run_script() and report() methods to determine the set of modules imported by a script. path can be a list of directories to search for modules; if not specified, sys.path is used. debug sets the debugging level; higher values make the class print debugging messages about what it’s doing. excludes is a list of module names to exclude from the analysis. replace_paths is a list of (oldpath, newpath) tuples that will be replaced in module paths.
Print a report to standard output that lists the modules imported by the script and their paths, as well as modules that are missing or seem to be missing.
Analyze the contents of the pathname file, which must contain Python code.
A dictionary mapping module names to modules. See Example usage of ModuleFinder.


A dictionary mapping module names to modules. See Example usage of ModuleFinder.


Print a report to standard output that lists the modules imported by the script and their paths, as well as modules that are missing or seem to be missing.


Analyze the contents of the pathname file, which must contain Python code.


Allows specifying that the module named oldname is in fact the package named newname.


A subclass of ImportError which is raised by import when a module could not be located. It is also raised when None is found in sys.modules.
New in version 3.6.