doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
class email.mime.nonmultipart.MIMENonMultipart Module: email.mime.nonmultipart A subclass of MIMEBase, this is an intermediate base class for MIME messages that are not multipart. The primary purpose of this class is to prevent the use of the attach() method, which only makes sense for multipart messages. If attach() is called, a MultipartConversionError exception is raised.
python.library.email.mime#email.mime.nonmultipart.MIMENonMultipart
class email.mime.text.MIMEText(_text, _subtype='plain', _charset=None, *, policy=compat32) Module: email.mime.text A subclass of MIMENonMultipart, the MIMEText class is used to create MIME objects of major type text. _text is the string for the payload. _subtype is the minor type and defaults to plain. _charset is the character set of the text and is passed as an argument to the MIMENonMultipart constructor; it defaults to us-ascii if the string contains only ascii code points, and utf-8 otherwise. The _charset parameter accepts either a string or a Charset instance. Unless the _charset argument is explicitly set to None, the MIMEText object created will have both a Content-Type header with a charset parameter, and a Content-Transfer-Encoding header. This means that a subsequent set_payload call will not result in an encoded payload, even if a charset is passed in the set_payload command. You can “reset” this behavior by deleting the Content-Transfer-Encoding header, after which a set_payload call will automatically encode the new payload (and add a new Content-Transfer-Encoding header). Optional policy argument defaults to compat32. Changed in version 3.5: _charset also accepts Charset instances. Changed in version 3.6: Added policy keyword-only parameter.
python.library.email.mime#email.mime.text.MIMEText
class email.parser.BytesFeedParser(_factory=None, *, policy=policy.compat32) Create a BytesFeedParser instance. Optional _factory is a no-argument callable; if not specified use the message_factory from the policy. Call _factory whenever a new message object is needed. If policy is specified use the rules it specifies to update the representation of the message. If policy is not set, use the compat32 policy, which maintains backward compatibility with the Python 3.2 version of the email package and provides Message as the default factory. All other policies provide EmailMessage as the default _factory. For more information on what else policy controls, see the policy documentation. Note: The policy keyword should always be specified; The default will change to email.policy.default in a future version of Python. New in version 3.2. Changed in version 3.3: Added the policy keyword. Changed in version 3.6: _factory defaults to the policy message_factory. feed(data) Feed the parser some more data. data should be a bytes-like object containing one or more lines. The lines can be partial and the parser will stitch such partial lines together properly. The lines can have any of the three common line endings: carriage return, newline, or carriage return and newline (they can even be mixed). close() Complete the parsing of all previously fed data and return the root message object. It is undefined what happens if feed() is called after this method has been called.
python.library.email.parser#email.parser.BytesFeedParser
close() Complete the parsing of all previously fed data and return the root message object. It is undefined what happens if feed() is called after this method has been called.
python.library.email.parser#email.parser.BytesFeedParser.close
feed(data) Feed the parser some more data. data should be a bytes-like object containing one or more lines. The lines can be partial and the parser will stitch such partial lines together properly. The lines can have any of the three common line endings: carriage return, newline, or carriage return and newline (they can even be mixed).
python.library.email.parser#email.parser.BytesFeedParser.feed
class email.parser.BytesHeaderParser(_class=None, *, policy=policy.compat32) Exactly like BytesParser, except that headersonly defaults to True. New in version 3.3.
python.library.email.parser#email.parser.BytesHeaderParser
class email.parser.BytesParser(_class=None, *, policy=policy.compat32) Create a BytesParser instance. The _class and policy arguments have the same meaning and semantics as the _factory and policy arguments of BytesFeedParser. Note: The policy keyword should always be specified; The default will change to email.policy.default in a future version of Python. Changed in version 3.3: Removed the strict argument that was deprecated in 2.4. Added the policy keyword. Changed in version 3.6: _class defaults to the policy message_factory. parse(fp, headersonly=False) Read all the data from the binary file-like object fp, parse the resulting bytes, and return the message object. fp must support both the readline() and the read() methods. The bytes contained in fp must be formatted as a block of RFC 5322 (or, if utf8 is True, RFC 6532) style headers and header continuation lines, optionally preceded by an envelope header. The header block is terminated either by the end of the data or by a blank line. Following the header block is the body of the message (which may contain MIME-encoded subparts, including subparts with a Content-Transfer-Encoding of 8bit). Optional headersonly is a flag specifying whether to stop parsing after reading the headers or not. The default is False, meaning it parses the entire contents of the file. parsebytes(bytes, headersonly=False) Similar to the parse() method, except it takes a bytes-like object instead of a file-like object. Calling this method on a bytes-like object is equivalent to wrapping bytes in a BytesIO instance first and calling parse(). Optional headersonly is as with the parse() method. New in version 3.2.
python.library.email.parser#email.parser.BytesParser
parse(fp, headersonly=False) Read all the data from the binary file-like object fp, parse the resulting bytes, and return the message object. fp must support both the readline() and the read() methods. The bytes contained in fp must be formatted as a block of RFC 5322 (or, if utf8 is True, RFC 6532) style headers and header continuation lines, optionally preceded by an envelope header. The header block is terminated either by the end of the data or by a blank line. Following the header block is the body of the message (which may contain MIME-encoded subparts, including subparts with a Content-Transfer-Encoding of 8bit). Optional headersonly is a flag specifying whether to stop parsing after reading the headers or not. The default is False, meaning it parses the entire contents of the file.
python.library.email.parser#email.parser.BytesParser.parse
parsebytes(bytes, headersonly=False) Similar to the parse() method, except it takes a bytes-like object instead of a file-like object. Calling this method on a bytes-like object is equivalent to wrapping bytes in a BytesIO instance first and calling parse(). Optional headersonly is as with the parse() method.
python.library.email.parser#email.parser.BytesParser.parsebytes
class email.parser.FeedParser(_factory=None, *, policy=policy.compat32) Works like BytesFeedParser except that the input to the feed() method must be a string. This is of limited utility, since the only way for such a message to be valid is for it to contain only ASCII text or, if utf8 is True, no binary attachments. Changed in version 3.3: Added the policy keyword.
python.library.email.parser#email.parser.FeedParser
class email.parser.HeaderParser(_class=None, *, policy=policy.compat32) Exactly like Parser, except that headersonly defaults to True.
python.library.email.parser#email.parser.HeaderParser
class email.parser.Parser(_class=None, *, policy=policy.compat32) This class is parallel to BytesParser, but handles string input. Changed in version 3.3: Removed the strict argument. Added the policy keyword. Changed in version 3.6: _class defaults to the policy message_factory. parse(fp, headersonly=False) Read all the data from the text-mode file-like object fp, parse the resulting text, and return the root message object. fp must support both the readline() and the read() methods on file-like objects. Other than the text mode requirement, this method operates like BytesParser.parse(). parsestr(text, headersonly=False) Similar to the parse() method, except it takes a string object instead of a file-like object. Calling this method on a string is equivalent to wrapping text in a StringIO instance first and calling parse(). Optional headersonly is as with the parse() method.
python.library.email.parser#email.parser.Parser
parse(fp, headersonly=False) Read all the data from the text-mode file-like object fp, parse the resulting text, and return the root message object. fp must support both the readline() and the read() methods on file-like objects. Other than the text mode requirement, this method operates like BytesParser.parse().
python.library.email.parser#email.parser.Parser.parse
parsestr(text, headersonly=False) Similar to the parse() method, except it takes a string object instead of a file-like object. Calling this method on a string is equivalent to wrapping text in a StringIO instance first and calling parse(). Optional headersonly is as with the parse() method.
python.library.email.parser#email.parser.Parser.parsestr
email.policy.compat32 An instance of Compat32, providing backward compatibility with the behavior of the email package in Python 3.2.
python.library.email.policy#email.policy.compat32
class email.policy.Compat32(**kw) This concrete Policy is the backward compatibility policy. It replicates the behavior of the email package in Python 3.2. The policy module also defines an instance of this class, compat32, that is used as the default policy. Thus the default behavior of the email package is to maintain compatibility with Python 3.2. The following attributes have values that are different from the Policy default: mangle_from_ The default is True. The class provides the following concrete implementations of the abstract methods of Policy: header_source_parse(sourcelines) The name is parsed as everything up to the ‘:’ and returned unmodified. The value is determined by stripping leading whitespace off the remainder of the first line, joining all subsequent lines together, and stripping any trailing carriage return or linefeed characters. header_store_parse(name, value) The name and value are returned unmodified. header_fetch_parse(name, value) If the value contains binary data, it is converted into a Header object using the unknown-8bit charset. Otherwise it is returned unmodified. fold(name, value) Headers are folded using the Header folding algorithm, which preserves existing line breaks in the value, and wraps each resulting line to the max_line_length. Non-ASCII binary data are CTE encoded using the unknown-8bit charset. fold_binary(name, value) Headers are folded using the Header folding algorithm, which preserves existing line breaks in the value, and wraps each resulting line to the max_line_length. If cte_type is 7bit, non-ascii binary data is CTE encoded using the unknown-8bit charset. Otherwise the original source header is used, with its existing line breaks and any (RFC invalid) binary data it may contain.
python.library.email.policy#email.policy.Compat32
fold(name, value) Headers are folded using the Header folding algorithm, which preserves existing line breaks in the value, and wraps each resulting line to the max_line_length. Non-ASCII binary data are CTE encoded using the unknown-8bit charset.
python.library.email.policy#email.policy.Compat32.fold
fold_binary(name, value) Headers are folded using the Header folding algorithm, which preserves existing line breaks in the value, and wraps each resulting line to the max_line_length. If cte_type is 7bit, non-ascii binary data is CTE encoded using the unknown-8bit charset. Otherwise the original source header is used, with its existing line breaks and any (RFC invalid) binary data it may contain.
python.library.email.policy#email.policy.Compat32.fold_binary
header_fetch_parse(name, value) If the value contains binary data, it is converted into a Header object using the unknown-8bit charset. Otherwise it is returned unmodified.
python.library.email.policy#email.policy.Compat32.header_fetch_parse
header_source_parse(sourcelines) The name is parsed as everything up to the ‘:’ and returned unmodified. The value is determined by stripping leading whitespace off the remainder of the first line, joining all subsequent lines together, and stripping any trailing carriage return or linefeed characters.
python.library.email.policy#email.policy.Compat32.header_source_parse
header_store_parse(name, value) The name and value are returned unmodified.
python.library.email.policy#email.policy.Compat32.header_store_parse
mangle_from_ The default is True.
python.library.email.policy#email.policy.Compat32.mangle_from_
email.policy.default An instance of EmailPolicy with all defaults unchanged. This policy uses the standard Python \n line endings rather than the RFC-correct \r\n.
python.library.email.policy#email.policy.default
class email.policy.EmailPolicy(**kw) This concrete Policy provides behavior that is intended to be fully compliant with the current email RFCs. These include (but are not limited to) RFC 5322, RFC 2047, and the current MIME RFCs. This policy adds new header parsing and folding algorithms. Instead of simple strings, headers are str subclasses with attributes that depend on the type of the field. The parsing and folding algorithm fully implement RFC 2047 and RFC 5322. The default value for the message_factory attribute is EmailMessage. In addition to the settable attributes listed above that apply to all policies, this policy adds the following additional attributes: New in version 3.6: 1 utf8 If False, follow RFC 5322, supporting non-ASCII characters in headers by encoding them as “encoded words”. If True, follow RFC 6532 and use utf-8 encoding for headers. Messages formatted in this way may be passed to SMTP servers that support the SMTPUTF8 extension (RFC 6531). refold_source If the value for a header in the Message object originated from a parser (as opposed to being set by a program), this attribute indicates whether or not a generator should refold that value when transforming the message back into serialized form. The possible values are: none all source values use original folding long source values that have any line that is longer than max_line_length will be refolded all all values are refolded. The default is long. header_factory A callable that takes two arguments, name and value, where name is a header field name and value is an unfolded header field value, and returns a string subclass that represents that header. A default header_factory (see headerregistry) is provided that supports custom parsing for the various address and date RFC 5322 header field types, and the major MIME header field stypes. Support for additional custom parsing will be added in the future. content_manager An object with at least two methods: get_content and set_content. When the get_content() or set_content() method of an EmailMessage object is called, it calls the corresponding method of this object, passing it the message object as its first argument, and any arguments or keywords that were passed to it as additional arguments. By default content_manager is set to raw_data_manager. New in version 3.4. The class provides the following concrete implementations of the abstract methods of Policy: header_max_count(name) Returns the value of the max_count attribute of the specialized class used to represent the header with the given name. header_source_parse(sourcelines) The name is parsed as everything up to the ‘:’ and returned unmodified. The value is determined by stripping leading whitespace off the remainder of the first line, joining all subsequent lines together, and stripping any trailing carriage return or linefeed characters. header_store_parse(name, value) The name is returned unchanged. If the input value has a name attribute and it matches name ignoring case, the value is returned unchanged. Otherwise the name and value are passed to header_factory, and the resulting header object is returned as the value. In this case a ValueError is raised if the input value contains CR or LF characters. header_fetch_parse(name, value) If the value has a name attribute, it is returned to unmodified. Otherwise the name, and the value with any CR or LF characters removed, are passed to the header_factory, and the resulting header object is returned. Any surrogateescaped bytes get turned into the unicode unknown-character glyph. fold(name, value) Header folding is controlled by the refold_source policy setting. A value is considered to be a ‘source value’ if and only if it does not have a name attribute (having a name attribute means it is a header object of some sort). If a source value needs to be refolded according to the policy, it is converted into a header object by passing the name and the value with any CR and LF characters removed to the header_factory. Folding of a header object is done by calling its fold method with the current policy. Source values are split into lines using splitlines(). If the value is not to be refolded, the lines are rejoined using the linesep from the policy and returned. The exception is lines containing non-ascii binary data. In that case the value is refolded regardless of the refold_source setting, which causes the binary data to be CTE encoded using the unknown-8bit charset. fold_binary(name, value) The same as fold() if cte_type is 7bit, except that the returned value is bytes. If cte_type is 8bit, non-ASCII binary data is converted back into bytes. Headers with binary data are not refolded, regardless of the refold_header setting, since there is no way to know whether the binary data consists of single byte characters or multibyte characters.
python.library.email.policy#email.policy.EmailPolicy
content_manager An object with at least two methods: get_content and set_content. When the get_content() or set_content() method of an EmailMessage object is called, it calls the corresponding method of this object, passing it the message object as its first argument, and any arguments or keywords that were passed to it as additional arguments. By default content_manager is set to raw_data_manager. New in version 3.4.
python.library.email.policy#email.policy.EmailPolicy.content_manager
fold(name, value) Header folding is controlled by the refold_source policy setting. A value is considered to be a ‘source value’ if and only if it does not have a name attribute (having a name attribute means it is a header object of some sort). If a source value needs to be refolded according to the policy, it is converted into a header object by passing the name and the value with any CR and LF characters removed to the header_factory. Folding of a header object is done by calling its fold method with the current policy. Source values are split into lines using splitlines(). If the value is not to be refolded, the lines are rejoined using the linesep from the policy and returned. The exception is lines containing non-ascii binary data. In that case the value is refolded regardless of the refold_source setting, which causes the binary data to be CTE encoded using the unknown-8bit charset.
python.library.email.policy#email.policy.EmailPolicy.fold
fold_binary(name, value) The same as fold() if cte_type is 7bit, except that the returned value is bytes. If cte_type is 8bit, non-ASCII binary data is converted back into bytes. Headers with binary data are not refolded, regardless of the refold_header setting, since there is no way to know whether the binary data consists of single byte characters or multibyte characters.
python.library.email.policy#email.policy.EmailPolicy.fold_binary
header_factory A callable that takes two arguments, name and value, where name is a header field name and value is an unfolded header field value, and returns a string subclass that represents that header. A default header_factory (see headerregistry) is provided that supports custom parsing for the various address and date RFC 5322 header field types, and the major MIME header field stypes. Support for additional custom parsing will be added in the future.
python.library.email.policy#email.policy.EmailPolicy.header_factory
header_fetch_parse(name, value) If the value has a name attribute, it is returned to unmodified. Otherwise the name, and the value with any CR or LF characters removed, are passed to the header_factory, and the resulting header object is returned. Any surrogateescaped bytes get turned into the unicode unknown-character glyph.
python.library.email.policy#email.policy.EmailPolicy.header_fetch_parse
header_max_count(name) Returns the value of the max_count attribute of the specialized class used to represent the header with the given name.
python.library.email.policy#email.policy.EmailPolicy.header_max_count
header_source_parse(sourcelines) The name is parsed as everything up to the ‘:’ and returned unmodified. The value is determined by stripping leading whitespace off the remainder of the first line, joining all subsequent lines together, and stripping any trailing carriage return or linefeed characters.
python.library.email.policy#email.policy.EmailPolicy.header_source_parse
header_store_parse(name, value) The name is returned unchanged. If the input value has a name attribute and it matches name ignoring case, the value is returned unchanged. Otherwise the name and value are passed to header_factory, and the resulting header object is returned as the value. In this case a ValueError is raised if the input value contains CR or LF characters.
python.library.email.policy#email.policy.EmailPolicy.header_store_parse
refold_source If the value for a header in the Message object originated from a parser (as opposed to being set by a program), this attribute indicates whether or not a generator should refold that value when transforming the message back into serialized form. The possible values are: none all source values use original folding long source values that have any line that is longer than max_line_length will be refolded all all values are refolded. The default is long.
python.library.email.policy#email.policy.EmailPolicy.refold_source
utf8 If False, follow RFC 5322, supporting non-ASCII characters in headers by encoding them as “encoded words”. If True, follow RFC 6532 and use utf-8 encoding for headers. Messages formatted in this way may be passed to SMTP servers that support the SMTPUTF8 extension (RFC 6531).
python.library.email.policy#email.policy.EmailPolicy.utf8
email.policy.HTTP Suitable for serializing headers with for use in HTTP traffic. Like SMTP except that max_line_length is set to None (unlimited).
python.library.email.policy#email.policy.HTTP
class email.policy.Policy(**kw) This is the abstract base class for all policy classes. It provides default implementations for a couple of trivial methods, as well as the implementation of the immutability property, the clone() method, and the constructor semantics. The constructor of a policy class can be passed various keyword arguments. The arguments that may be specified are any non-method properties on this class, plus any additional non-method properties on the concrete class. A value specified in the constructor will override the default value for the corresponding attribute. This class defines the following properties, and thus values for the following may be passed in the constructor of any policy class: max_line_length The maximum length of any line in the serialized output, not counting the end of line character(s). Default is 78, per RFC 5322. A value of 0 or None indicates that no line wrapping should be done at all. linesep The string to be used to terminate lines in serialized output. The default is \n because that’s the internal end-of-line discipline used by Python, though \r\n is required by the RFCs. cte_type Controls the type of Content Transfer Encodings that may be or are required to be used. The possible values are: 7bit all data must be “7 bit clean” (ASCII-only). This means that where necessary data will be encoded using either quoted-printable or base64 encoding. 8bit data is not constrained to be 7 bit clean. Data in headers is still required to be ASCII-only and so will be encoded (see fold_binary() and utf8 below for exceptions), but body parts may use the 8bit CTE. A cte_type value of 8bit only works with BytesGenerator, not Generator, because strings cannot contain binary data. If a Generator is operating under a policy that specifies cte_type=8bit, it will act as if cte_type is 7bit. raise_on_defect If True, any defects encountered will be raised as errors. If False (the default), defects will be passed to the register_defect() method. mangle_from_ If True, lines starting with “From “ in the body are escaped by putting a > in front of them. This parameter is used when the message is being serialized by a generator. Default: False. New in version 3.5: The mangle_from_ parameter. message_factory A factory function for constructing a new empty message object. Used by the parser when building messages. Defaults to None, in which case Message is used. New in version 3.6. The following Policy method is intended to be called by code using the email library to create policy instances with custom settings: clone(**kw) Return a new Policy instance whose attributes have the same values as the current instance, except where those attributes are given new values by the keyword arguments. The remaining Policy methods are called by the email package code, and are not intended to be called by an application using the email package. A custom policy must implement all of these methods. handle_defect(obj, defect) Handle a defect found on obj. When the email package calls this method, defect will always be a subclass of Defect. The default implementation checks the raise_on_defect flag. If it is True, defect is raised as an exception. If it is False (the default), obj and defect are passed to register_defect(). register_defect(obj, defect) Register a defect on obj. In the email package, defect will always be a subclass of Defect. The default implementation calls the append method of the defects attribute of obj. When the email package calls handle_defect, obj will normally have a defects attribute that has an append method. Custom object types used with the email package (for example, custom Message objects) should also provide such an attribute, otherwise defects in parsed messages will raise unexpected errors. header_max_count(name) Return the maximum allowed number of headers named name. Called when a header is added to an EmailMessage or Message object. If the returned value is not 0 or None, and there are already a number of headers with the name name greater than or equal to the value returned, a ValueError is raised. Because the default behavior of Message.__setitem__ is to append the value to the list of headers, it is easy to create duplicate headers without realizing it. This method allows certain headers to be limited in the number of instances of that header that may be added to a Message programmatically. (The limit is not observed by the parser, which will faithfully produce as many headers as exist in the message being parsed.) The default implementation returns None for all header names. header_source_parse(sourcelines) The email package calls this method with a list of strings, each string ending with the line separation characters found in the source being parsed. The first line includes the field header name and separator. All whitespace in the source is preserved. The method should return the (name, value) tuple that is to be stored in the Message to represent the parsed header. If an implementation wishes to retain compatibility with the existing email package policies, name should be the case preserved name (all characters up to the ‘:’ separator), while value should be the unfolded value (all line separator characters removed, but whitespace kept intact), stripped of leading whitespace. sourcelines may contain surrogateescaped binary data. There is no default implementation header_store_parse(name, value) The email package calls this method with the name and value provided by the application program when the application program is modifying a Message programmatically (as opposed to a Message created by a parser). The method should return the (name, value) tuple that is to be stored in the Message to represent the header. If an implementation wishes to retain compatibility with the existing email package policies, the name and value should be strings or string subclasses that do not change the content of the passed in arguments. There is no default implementation header_fetch_parse(name, value) The email package calls this method with the name and value currently stored in the Message when that header is requested by the application program, and whatever the method returns is what is passed back to the application as the value of the header being retrieved. Note that there may be more than one header with the same name stored in the Message; the method is passed the specific name and value of the header destined to be returned to the application. value may contain surrogateescaped binary data. There should be no surrogateescaped binary data in the value returned by the method. There is no default implementation fold(name, value) The email package calls this method with the name and value currently stored in the Message for a given header. The method should return a string that represents that header “folded” correctly (according to the policy settings) by composing the name with the value and inserting linesep characters at the appropriate places. See RFC 5322 for a discussion of the rules for folding email headers. value may contain surrogateescaped binary data. There should be no surrogateescaped binary data in the string returned by the method. fold_binary(name, value) The same as fold(), except that the returned value should be a bytes object rather than a string. value may contain surrogateescaped binary data. These could be converted back into binary data in the returned bytes object.
python.library.email.policy#email.policy.Policy
clone(**kw) Return a new Policy instance whose attributes have the same values as the current instance, except where those attributes are given new values by the keyword arguments.
python.library.email.policy#email.policy.Policy.clone
cte_type Controls the type of Content Transfer Encodings that may be or are required to be used. The possible values are: 7bit all data must be “7 bit clean” (ASCII-only). This means that where necessary data will be encoded using either quoted-printable or base64 encoding. 8bit data is not constrained to be 7 bit clean. Data in headers is still required to be ASCII-only and so will be encoded (see fold_binary() and utf8 below for exceptions), but body parts may use the 8bit CTE. A cte_type value of 8bit only works with BytesGenerator, not Generator, because strings cannot contain binary data. If a Generator is operating under a policy that specifies cte_type=8bit, it will act as if cte_type is 7bit.
python.library.email.policy#email.policy.Policy.cte_type
fold(name, value) The email package calls this method with the name and value currently stored in the Message for a given header. The method should return a string that represents that header “folded” correctly (according to the policy settings) by composing the name with the value and inserting linesep characters at the appropriate places. See RFC 5322 for a discussion of the rules for folding email headers. value may contain surrogateescaped binary data. There should be no surrogateescaped binary data in the string returned by the method.
python.library.email.policy#email.policy.Policy.fold
fold_binary(name, value) The same as fold(), except that the returned value should be a bytes object rather than a string. value may contain surrogateescaped binary data. These could be converted back into binary data in the returned bytes object.
python.library.email.policy#email.policy.Policy.fold_binary
handle_defect(obj, defect) Handle a defect found on obj. When the email package calls this method, defect will always be a subclass of Defect. The default implementation checks the raise_on_defect flag. If it is True, defect is raised as an exception. If it is False (the default), obj and defect are passed to register_defect().
python.library.email.policy#email.policy.Policy.handle_defect
header_fetch_parse(name, value) The email package calls this method with the name and value currently stored in the Message when that header is requested by the application program, and whatever the method returns is what is passed back to the application as the value of the header being retrieved. Note that there may be more than one header with the same name stored in the Message; the method is passed the specific name and value of the header destined to be returned to the application. value may contain surrogateescaped binary data. There should be no surrogateescaped binary data in the value returned by the method. There is no default implementation
python.library.email.policy#email.policy.Policy.header_fetch_parse
header_max_count(name) Return the maximum allowed number of headers named name. Called when a header is added to an EmailMessage or Message object. If the returned value is not 0 or None, and there are already a number of headers with the name name greater than or equal to the value returned, a ValueError is raised. Because the default behavior of Message.__setitem__ is to append the value to the list of headers, it is easy to create duplicate headers without realizing it. This method allows certain headers to be limited in the number of instances of that header that may be added to a Message programmatically. (The limit is not observed by the parser, which will faithfully produce as many headers as exist in the message being parsed.) The default implementation returns None for all header names.
python.library.email.policy#email.policy.Policy.header_max_count
header_source_parse(sourcelines) The email package calls this method with a list of strings, each string ending with the line separation characters found in the source being parsed. The first line includes the field header name and separator. All whitespace in the source is preserved. The method should return the (name, value) tuple that is to be stored in the Message to represent the parsed header. If an implementation wishes to retain compatibility with the existing email package policies, name should be the case preserved name (all characters up to the ‘:’ separator), while value should be the unfolded value (all line separator characters removed, but whitespace kept intact), stripped of leading whitespace. sourcelines may contain surrogateescaped binary data. There is no default implementation
python.library.email.policy#email.policy.Policy.header_source_parse
header_store_parse(name, value) The email package calls this method with the name and value provided by the application program when the application program is modifying a Message programmatically (as opposed to a Message created by a parser). The method should return the (name, value) tuple that is to be stored in the Message to represent the header. If an implementation wishes to retain compatibility with the existing email package policies, the name and value should be strings or string subclasses that do not change the content of the passed in arguments. There is no default implementation
python.library.email.policy#email.policy.Policy.header_store_parse
linesep The string to be used to terminate lines in serialized output. The default is \n because that’s the internal end-of-line discipline used by Python, though \r\n is required by the RFCs.
python.library.email.policy#email.policy.Policy.linesep
mangle_from_ If True, lines starting with “From “ in the body are escaped by putting a > in front of them. This parameter is used when the message is being serialized by a generator. Default: False. New in version 3.5: The mangle_from_ parameter.
python.library.email.policy#email.policy.Policy.mangle_from_
max_line_length The maximum length of any line in the serialized output, not counting the end of line character(s). Default is 78, per RFC 5322. A value of 0 or None indicates that no line wrapping should be done at all.
python.library.email.policy#email.policy.Policy.max_line_length
message_factory A factory function for constructing a new empty message object. Used by the parser when building messages. Defaults to None, in which case Message is used. New in version 3.6.
python.library.email.policy#email.policy.Policy.message_factory
raise_on_defect If True, any defects encountered will be raised as errors. If False (the default), defects will be passed to the register_defect() method.
python.library.email.policy#email.policy.Policy.raise_on_defect
register_defect(obj, defect) Register a defect on obj. In the email package, defect will always be a subclass of Defect. The default implementation calls the append method of the defects attribute of obj. When the email package calls handle_defect, obj will normally have a defects attribute that has an append method. Custom object types used with the email package (for example, custom Message objects) should also provide such an attribute, otherwise defects in parsed messages will raise unexpected errors.
python.library.email.policy#email.policy.Policy.register_defect
email.policy.SMTP Suitable for serializing messages in conformance with the email RFCs. Like default, but with linesep set to \r\n, which is RFC compliant.
python.library.email.policy#email.policy.SMTP
email.policy.SMTPUTF8 The same as SMTP except that utf8 is True. Useful for serializing messages to a message store without using encoded words in the headers. Should only be used for SMTP transmission if the sender or recipient addresses have non-ASCII characters (the smtplib.SMTP.send_message() method handles this automatically).
python.library.email.policy#email.policy.SMTPUTF8
email.policy.strict Convenience instance. The same as default except that raise_on_defect is set to True. This allows any policy to be made strict by writing: somepolicy + policy.strict
python.library.email.policy#email.policy.strict
email.utils.collapse_rfc2231_value(value, errors='replace', fallback_charset='us-ascii') When a header parameter is encoded in RFC 2231 format, Message.get_param may return a 3-tuple containing the character set, language, and value. collapse_rfc2231_value() turns this into a unicode string. Optional errors is passed to the errors argument of str’s encode() method; it defaults to 'replace'. Optional fallback_charset specifies the character set to use if the one in the RFC 2231 header is not known by Python; it defaults to 'us-ascii'. For convenience, if the value passed to collapse_rfc2231_value() is not a tuple, it should be a string and it is returned unquoted.
python.library.email.utils#email.utils.collapse_rfc2231_value
email.utils.decode_params(params) Decode parameters list according to RFC 2231. params is a sequence of 2-tuples containing elements of the form (content-type, string-value).
python.library.email.utils#email.utils.decode_params
email.utils.decode_rfc2231(s) Decode the string s according to RFC 2231.
python.library.email.utils#email.utils.decode_rfc2231
email.utils.encode_rfc2231(s, charset=None, language=None) Encode the string s according to RFC 2231. Optional charset and language, if given is the character set name and language name to use. If neither is given, s is returned as-is. If charset is given but language is not, the string is encoded using the empty string for language.
python.library.email.utils#email.utils.encode_rfc2231
email.utils.formataddr(pair, charset='utf-8') The inverse of parseaddr(), this takes a 2-tuple of the form (realname, email_address) and returns the string value suitable for a To or Cc header. If the first element of pair is false, then the second element is returned unmodified. Optional charset is the character set that will be used in the RFC 2047 encoding of the realname if the realname contains non-ASCII characters. Can be an instance of str or a Charset. Defaults to utf-8. Changed in version 3.3: Added the charset option.
python.library.email.utils#email.utils.formataddr
email.utils.formatdate(timeval=None, localtime=False, usegmt=False) Returns a date string as per RFC 2822, e.g.: Fri, 09 Nov 2001 01:08:47 -0000 Optional timeval if given is a floating point time value as accepted by time.gmtime() and time.localtime(), otherwise the current time is used. Optional localtime is a flag that when True, interprets timeval, and returns a date relative to the local timezone instead of UTC, properly taking daylight savings time into account. The default is False meaning UTC is used. Optional usegmt is a flag that when True, outputs a date string with the timezone as an ascii string GMT, rather than a numeric -0000. This is needed for some protocols (such as HTTP). This only applies when localtime is False. The default is False.
python.library.email.utils#email.utils.formatdate
email.utils.format_datetime(dt, usegmt=False) Like formatdate, but the input is a datetime instance. If it is a naive datetime, it is assumed to be “UTC with no information about the source timezone”, and the conventional -0000 is used for the timezone. If it is an aware datetime, then the numeric timezone offset is used. If it is an aware timezone with offset zero, then usegmt may be set to True, in which case the string GMT is used instead of the numeric timezone offset. This provides a way to generate standards conformant HTTP date headers. New in version 3.3.
python.library.email.utils#email.utils.format_datetime
email.utils.getaddresses(fieldvalues) This method returns a list of 2-tuples of the form returned by parseaddr(). fieldvalues is a sequence of header field values as might be returned by Message.get_all. Here’s a simple example that gets all the recipients of a message: from email.utils import getaddresses tos = msg.get_all('to', []) ccs = msg.get_all('cc', []) resent_tos = msg.get_all('resent-to', []) resent_ccs = msg.get_all('resent-cc', []) all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs)
python.library.email.utils#email.utils.getaddresses
email.utils.localtime(dt=None) Return local time as an aware datetime object. If called without arguments, return current time. Otherwise dt argument should be a datetime instance, and it is converted to the local time zone according to the system time zone database. If dt is naive (that is, dt.tzinfo is None), it is assumed to be in local time. In this case, a positive or zero value for isdst causes localtime to presume initially that summer time (for example, Daylight Saving Time) is or is not (respectively) in effect for the specified time. A negative value for isdst causes the localtime to attempt to divine whether summer time is in effect for the specified time. New in version 3.3.
python.library.email.utils#email.utils.localtime
email.utils.make_msgid(idstring=None, domain=None) Returns a string suitable for an RFC 2822-compliant Message-ID header. Optional idstring if given, is a string used to strengthen the uniqueness of the message id. Optional domain if given provides the portion of the msgid after the ‘@’. The default is the local hostname. It is not normally necessary to override this default, but may be useful certain cases, such as a constructing distributed system that uses a consistent domain name across multiple hosts. Changed in version 3.2: Added the domain keyword.
python.library.email.utils#email.utils.make_msgid
email.utils.mktime_tz(tuple) Turn a 10-tuple as returned by parsedate_tz() into a UTC timestamp (seconds since the Epoch). If the timezone item in the tuple is None, assume local time.
python.library.email.utils#email.utils.mktime_tz
email.utils.parseaddr(address) Parse address – which should be the value of some address-containing field such as To or Cc – into its constituent realname and email address parts. Returns a tuple of that information, unless the parse fails, in which case a 2-tuple of ('', '') is returned.
python.library.email.utils#email.utils.parseaddr
email.utils.parsedate(date) Attempts to parse a date according to the rules in RFC 2822. however, some mailers don’t follow that format as specified, so parsedate() tries to guess correctly in such cases. date is a string containing an RFC 2822 date, such as "Mon, 20 Nov 1995 19:12:08 -0500". If it succeeds in parsing the date, parsedate() returns a 9-tuple that can be passed directly to time.mktime(); otherwise None will be returned. Note that indexes 6, 7, and 8 of the result tuple are not usable.
python.library.email.utils#email.utils.parsedate
email.utils.parsedate_to_datetime(date) The inverse of format_datetime(). Performs the same function as parsedate(), but on success returns a datetime. If the input date has a timezone of -0000, the datetime will be a naive datetime, and if the date is conforming to the RFCs it will represent a time in UTC but with no indication of the actual source timezone of the message the date comes from. If the input date has any other valid timezone offset, the datetime will be an aware datetime with the corresponding a timezone tzinfo. New in version 3.3.
python.library.email.utils#email.utils.parsedate_to_datetime
email.utils.parsedate_tz(date) Performs the same function as parsedate(), but returns either None or a 10-tuple; the first 9 elements make up a tuple that can be passed directly to time.mktime(), and the tenth is the offset of the date’s timezone from UTC (which is the official term for Greenwich Mean Time) 1. If the input string has no timezone, the last element of the tuple returned is 0, which represents UTC. Note that indexes 6, 7, and 8 of the result tuple are not usable.
python.library.email.utils#email.utils.parsedate_tz
email.utils.quote(str) Return a new string with backslashes in str replaced by two backslashes, and double quotes replaced by backslash-double quote.
python.library.email.utils#email.utils.quote
email.utils.unquote(str) Return a new string which is an unquoted version of str. If str ends and begins with double quotes, they are stripped off. Likewise if str ends and begins with angle brackets, they are stripped off.
python.library.email.utils#email.utils.unquote
encodings.idna.nameprep(label) Return the nameprepped version of label. The implementation currently assumes query strings, so AllowUnassigned is true.
python.library.codecs#encodings.idna.nameprep
encodings.idna.ToASCII(label) Convert a label to ASCII, as specified in RFC 3490. UseSTD3ASCIIRules is assumed to be false.
python.library.codecs#encodings.idna.ToASCII
encodings.idna.ToUnicode(label) Convert a label to Unicode, as specified in RFC 3490.
python.library.codecs#encodings.idna.ToUnicode
ensurepip — Bootstrapping the pip installer New in version 3.4. The ensurepip package provides support for bootstrapping the pip installer into an existing Python installation or virtual environment. This bootstrapping approach reflects the fact that pip is an independent project with its own release cycle, and the latest available stable version is bundled with maintenance and feature releases of the CPython reference interpreter. In most cases, end users of Python shouldn’t need to invoke this module directly (as pip should be bootstrapped by default), but it may be needed if installing pip was skipped when installing Python (or when creating a virtual environment) or after explicitly uninstalling pip. Note This module does not access the internet. All of the components needed to bootstrap pip are included as internal parts of the package. See also Installing Python Modules The end user guide for installing Python packages PEP 453: Explicit bootstrapping of pip in Python installations The original rationale and specification for this module. Command line interface The command line interface is invoked using the interpreter’s -m switch. The simplest possible invocation is: python -m ensurepip This invocation will install pip if it is not already installed, but otherwise does nothing. To ensure the installed version of pip is at least as recent as the one bundled with ensurepip, pass the --upgrade option: python -m ensurepip --upgrade By default, pip is installed into the current virtual environment (if one is active) or into the system site packages (if there is no active virtual environment). The installation location can be controlled through two additional command line options: --root <dir>: Installs pip relative to the given root directory rather than the root of the currently active virtual environment (if any) or the default root for the current Python installation. --user: Installs pip into the user site packages directory rather than globally for the current Python installation (this option is not permitted inside an active virtual environment). By default, the scripts pipX and pipX.Y will be installed (where X.Y stands for the version of Python used to invoke ensurepip). The scripts installed can be controlled through two additional command line options: --altinstall: if an alternate installation is requested, the pipX script will not be installed. --default-pip: if a “default pip” installation is requested, the pip script will be installed in addition to the two regular scripts. Providing both of the script selection options will trigger an exception. Module API ensurepip exposes two functions for programmatic use: ensurepip.version() Returns a string specifying the bundled version of pip that will be installed when bootstrapping an environment. ensurepip.bootstrap(root=None, upgrade=False, user=False, altinstall=False, default_pip=False, verbosity=0) Bootstraps pip into the current or designated environment. root specifies an alternative root directory to install relative to. If root is None, then installation uses the default install location for the current environment. upgrade indicates whether or not to upgrade an existing installation of an earlier version of pip to the bundled version. user indicates whether to use the user scheme rather than installing globally. By default, the scripts pipX and pipX.Y will be installed (where X.Y stands for the current version of Python). If altinstall is set, then pipX will not be installed. If default_pip is set, then pip will be installed in addition to the two regular scripts. Setting both altinstall and default_pip will trigger ValueError. verbosity controls the level of output to sys.stdout from the bootstrapping operation. Raises an auditing event ensurepip.bootstrap with argument root. Note The bootstrapping process has side effects on both sys.path and os.environ. Invoking the command line interface in a subprocess instead allows these side effects to be avoided. Note The bootstrapping process may install additional modules required by pip, but other software should not assume those dependencies will always be present by default (as the dependencies may be removed in a future version of pip).
python.library.ensurepip
ensurepip.bootstrap(root=None, upgrade=False, user=False, altinstall=False, default_pip=False, verbosity=0) Bootstraps pip into the current or designated environment. root specifies an alternative root directory to install relative to. If root is None, then installation uses the default install location for the current environment. upgrade indicates whether or not to upgrade an existing installation of an earlier version of pip to the bundled version. user indicates whether to use the user scheme rather than installing globally. By default, the scripts pipX and pipX.Y will be installed (where X.Y stands for the current version of Python). If altinstall is set, then pipX will not be installed. If default_pip is set, then pip will be installed in addition to the two regular scripts. Setting both altinstall and default_pip will trigger ValueError. verbosity controls the level of output to sys.stdout from the bootstrapping operation. Raises an auditing event ensurepip.bootstrap with argument root. Note The bootstrapping process has side effects on both sys.path and os.environ. Invoking the command line interface in a subprocess instead allows these side effects to be avoided. Note The bootstrapping process may install additional modules required by pip, but other software should not assume those dependencies will always be present by default (as the dependencies may be removed in a future version of pip).
python.library.ensurepip#ensurepip.bootstrap
ensurepip.version() Returns a string specifying the bundled version of pip that will be installed when bootstrapping an environment.
python.library.ensurepip#ensurepip.version
enum — Support for enumerations New in version 3.4. Source code: Lib/enum.py An enumeration is a set of symbolic names (members) bound to unique, constant values. Within an enumeration, the members can be compared by identity, and the enumeration itself can be iterated over. Note Case of Enum Members Because Enums are used to represent constants we recommend using UPPER_CASE names for enum members, and will be using that style in our examples. Module Contents This module defines four enumeration classes that can be used to define unique sets of names and values: Enum, IntEnum, Flag, and IntFlag. It also defines one decorator, unique(), and one helper, auto. class enum.Enum Base class for creating enumerated constants. See section Functional API for an alternate construction syntax. class enum.IntEnum Base class for creating enumerated constants that are also subclasses of int. class enum.IntFlag Base class for creating enumerated constants that can be combined using the bitwise operators without losing their IntFlag membership. IntFlag members are also subclasses of int. class enum.Flag Base class for creating enumerated constants that can be combined using the bitwise operations without losing their Flag membership. enum.unique() Enum class decorator that ensures only one name is bound to any one value. class enum.auto Instances are replaced with an appropriate value for Enum members. By default, the initial value starts at 1. New in version 3.6: Flag, IntFlag, auto Creating an Enum Enumerations are created using the class syntax, which makes them easy to read and write. An alternative creation method is described in Functional API. To define an enumeration, subclass Enum as follows: >>> from enum import Enum >>> class Color(Enum): ... RED = 1 ... GREEN = 2 ... BLUE = 3 ... Note Enum member values Member values can be anything: int, str, etc.. If the exact value is unimportant you may use auto instances and an appropriate value will be chosen for you. Care must be taken if you mix auto with other values. Note Nomenclature The class Color is an enumeration (or enum) The attributes Color.RED, Color.GREEN, etc., are enumeration members (or enum members) and are functionally constants. The enum members have names and values (the name of Color.RED is RED, the value of Color.BLUE is 3, etc.) Note Even though we use the class syntax to create Enums, Enums are not normal Python classes. See How are Enums different? for more details. Enumeration members have human readable string representations: >>> print(Color.RED) Color.RED …while their repr has more information: >>> print(repr(Color.RED)) <Color.RED: 1> The type of an enumeration member is the enumeration it belongs to: >>> type(Color.RED) <enum 'Color'> >>> isinstance(Color.GREEN, Color) True >>> Enum members also have a property that contains just their item name: >>> print(Color.RED.name) RED Enumerations support iteration, in definition order: >>> class Shake(Enum): ... VANILLA = 7 ... CHOCOLATE = 4 ... COOKIES = 9 ... MINT = 3 ... >>> for shake in Shake: ... print(shake) ... Shake.VANILLA Shake.CHOCOLATE Shake.COOKIES Shake.MINT Enumeration members are hashable, so they can be used in dictionaries and sets: >>> apples = {} >>> apples[Color.RED] = 'red delicious' >>> apples[Color.GREEN] = 'granny smith' >>> apples == {Color.RED: 'red delicious', Color.GREEN: 'granny smith'} True Programmatic access to enumeration members and their attributes Sometimes it’s useful to access members in enumerations programmatically (i.e. situations where Color.RED won’t do because the exact color is not known at program-writing time). Enum allows such access: >>> Color(1) <Color.RED: 1> >>> Color(3) <Color.BLUE: 3> If you want to access enum members by name, use item access: >>> Color['RED'] <Color.RED: 1> >>> Color['GREEN'] <Color.GREEN: 2> If you have an enum member and need its name or value: >>> member = Color.RED >>> member.name 'RED' >>> member.value 1 Duplicating enum members and values Having two enum members with the same name is invalid: >>> class Shape(Enum): ... SQUARE = 2 ... SQUARE = 3 ... Traceback (most recent call last): ... TypeError: Attempted to reuse key: 'SQUARE' However, two enum members are allowed to have the same value. Given two members A and B with the same value (and A defined first), B is an alias to A. By-value lookup of the value of A and B will return A. By-name lookup of B will also return A: >>> class Shape(Enum): ... SQUARE = 2 ... DIAMOND = 1 ... CIRCLE = 3 ... ALIAS_FOR_SQUARE = 2 ... >>> Shape.SQUARE <Shape.SQUARE: 2> >>> Shape.ALIAS_FOR_SQUARE <Shape.SQUARE: 2> >>> Shape(2) <Shape.SQUARE: 2> Note Attempting to create a member with the same name as an already defined attribute (another member, a method, etc.) or attempting to create an attribute with the same name as a member is not allowed. Ensuring unique enumeration values By default, enumerations allow multiple names as aliases for the same value. When this behavior isn’t desired, the following decorator can be used to ensure each value is used only once in the enumeration: @enum.unique A class decorator specifically for enumerations. It searches an enumeration’s __members__ gathering any aliases it finds; if any are found ValueError is raised with the details: >>> from enum import Enum, unique >>> @unique ... class Mistake(Enum): ... ONE = 1 ... TWO = 2 ... THREE = 3 ... FOUR = 3 ... Traceback (most recent call last): ... ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE Using automatic values If the exact value is unimportant you can use auto: >>> from enum import Enum, auto >>> class Color(Enum): ... RED = auto() ... BLUE = auto() ... GREEN = auto() ... >>> list(Color) [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>] The values are chosen by _generate_next_value_(), which can be overridden: >>> class AutoName(Enum): ... def _generate_next_value_(name, start, count, last_values): ... return name ... >>> class Ordinal(AutoName): ... NORTH = auto() ... SOUTH = auto() ... EAST = auto() ... WEST = auto() ... >>> list(Ordinal) [<Ordinal.NORTH: 'NORTH'>, <Ordinal.SOUTH: 'SOUTH'>, <Ordinal.EAST: 'EAST'>, <Ordinal.WEST: 'WEST'>] Note The goal of the default _generate_next_value_() method is to provide the next int in sequence with the last int provided, but the way it does this is an implementation detail and may change. Note The _generate_next_value_() method must be defined before any members. Iteration Iterating over the members of an enum does not provide the aliases: >>> list(Shape) [<Shape.SQUARE: 2>, <Shape.DIAMOND: 1>, <Shape.CIRCLE: 3>] The special attribute __members__ is a read-only ordered mapping of names to members. It includes all names defined in the enumeration, including the aliases: >>> for name, member in Shape.__members__.items(): ... name, member ... ('SQUARE', <Shape.SQUARE: 2>) ('DIAMOND', <Shape.DIAMOND: 1>) ('CIRCLE', <Shape.CIRCLE: 3>) ('ALIAS_FOR_SQUARE', <Shape.SQUARE: 2>) The __members__ attribute can be used for detailed programmatic access to the enumeration members. For example, finding all the aliases: >>> [name for name, member in Shape.__members__.items() if member.name != name] ['ALIAS_FOR_SQUARE'] Comparisons Enumeration members are compared by identity: >>> Color.RED is Color.RED True >>> Color.RED is Color.BLUE False >>> Color.RED is not Color.BLUE True Ordered comparisons between enumeration values are not supported. Enum members are not integers (but see IntEnum below): >>> Color.RED < Color.BLUE Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: '<' not supported between instances of 'Color' and 'Color' Equality comparisons are defined though: >>> Color.BLUE == Color.RED False >>> Color.BLUE != Color.RED True >>> Color.BLUE == Color.BLUE True Comparisons against non-enumeration values will always compare not equal (again, IntEnum was explicitly designed to behave differently, see below): >>> Color.BLUE == 2 False Allowed members and attributes of enumerations The examples above use integers for enumeration values. Using integers is short and handy (and provided by default by the Functional API), but not strictly enforced. In the vast majority of use-cases, one doesn’t care what the actual value of an enumeration is. But if the value is important, enumerations can have arbitrary values. Enumerations are Python classes, and can have methods and special methods as usual. If we have this enumeration: >>> class Mood(Enum): ... FUNKY = 1 ... HAPPY = 3 ... ... def describe(self): ... # self is the member here ... return self.name, self.value ... ... def __str__(self): ... return 'my custom str! {0}'.format(self.value) ... ... @classmethod ... def favorite_mood(cls): ... # cls here is the enumeration ... return cls.HAPPY ... Then: >>> Mood.favorite_mood() <Mood.HAPPY: 3> >>> Mood.HAPPY.describe() ('HAPPY', 3) >>> str(Mood.FUNKY) 'my custom str! 1' The rules for what is allowed are as follows: names that start and end with a single underscore are reserved by enum and cannot be used; all other attributes defined within an enumeration will become members of this enumeration, with the exception of special methods (__str__(), __add__(), etc.), descriptors (methods are also descriptors), and variable names listed in _ignore_. Note: if your enumeration defines __new__() and/or __init__() then any value(s) given to the enum member will be passed into those methods. See Planet for an example. Restricted Enum subclassing A new Enum class must have one base Enum class, up to one concrete data type, and as many object-based mixin classes as needed. The order of these base classes is: class EnumName([mix-in, ...,] [data-type,] base-enum): pass Also, subclassing an enumeration is allowed only if the enumeration does not define any members. So this is forbidden: >>> class MoreColor(Color): ... PINK = 17 ... Traceback (most recent call last): ... TypeError: Cannot extend enumerations But this is allowed: >>> class Foo(Enum): ... def some_behavior(self): ... pass ... >>> class Bar(Foo): ... HAPPY = 1 ... SAD = 2 ... Allowing subclassing of enums that define members would lead to a violation of some important invariants of types and instances. On the other hand, it makes sense to allow sharing some common behavior between a group of enumerations. (See OrderedEnum for an example.) Pickling Enumerations can be pickled and unpickled: >>> from test.test_enum import Fruit >>> from pickle import dumps, loads >>> Fruit.TOMATO is loads(dumps(Fruit.TOMATO)) True The usual restrictions for pickling apply: picklable enums must be defined in the top level of a module, since unpickling requires them to be importable from that module. Note With pickle protocol version 4 it is possible to easily pickle enums nested in other classes. It is possible to modify how Enum members are pickled/unpickled by defining __reduce_ex__() in the enumeration class. Functional API The Enum class is callable, providing the following functional API: >>> Animal = Enum('Animal', 'ANT BEE CAT DOG') >>> Animal <enum 'Animal'> >>> Animal.ANT <Animal.ANT: 1> >>> Animal.ANT.value 1 >>> list(Animal) [<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>] The semantics of this API resemble namedtuple. The first argument of the call to Enum is the name of the enumeration. The second argument is the source of enumeration member names. It can be a whitespace-separated string of names, a sequence of names, a sequence of 2-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to values. The last two options enable assigning arbitrary values to enumerations; the others auto-assign increasing integers starting with 1 (use the start parameter to specify a different starting value). A new class derived from Enum is returned. In other words, the above assignment to Animal is equivalent to: >>> class Animal(Enum): ... ANT = 1 ... BEE = 2 ... CAT = 3 ... DOG = 4 ... The reason for defaulting to 1 as the starting number and not 0 is that 0 is False in a boolean sense, but enum members all evaluate to True. Pickling enums created with the functional API can be tricky as frame stack implementation details are used to try and figure out which module the enumeration is being created in (e.g. it will fail if you use a utility function in separate module, and also may not work on IronPython or Jython). The solution is to specify the module name explicitly as follows: >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', module=__name__) Warning If module is not supplied, and Enum cannot determine what it is, the new Enum members will not be unpicklable; to keep errors closer to the source, pickling will be disabled. The new pickle protocol 4 also, in some circumstances, relies on __qualname__ being set to the location where pickle will be able to find the class. For example, if the class was made available in class SomeData in the global scope: >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal') The complete signature is: Enum(value='NewEnumName', names=<...>, *, module='...', qualname='...', type=<mixed-in class>, start=1) value What the new Enum class will record as its name. names The Enum members. This can be a whitespace or comma separated string (values will start at 1 unless otherwise specified): 'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE' or an iterator of names: ['RED', 'GREEN', 'BLUE'] or an iterator of (name, value) pairs: [('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)] or a mapping: {'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42} module name of module where new Enum class can be found. qualname where in module new Enum class can be found. type type to mix in to new Enum class. start number to start counting at if only names are passed in. Changed in version 3.5: The start parameter was added. Derived Enumerations IntEnum The first variation of Enum that is provided is also a subclass of int. Members of an IntEnum can be compared to integers; by extension, integer enumerations of different types can also be compared to each other: >>> from enum import IntEnum >>> class Shape(IntEnum): ... CIRCLE = 1 ... SQUARE = 2 ... >>> class Request(IntEnum): ... POST = 1 ... GET = 2 ... >>> Shape == 1 False >>> Shape.CIRCLE == 1 True >>> Shape.CIRCLE == Request.POST True However, they still can’t be compared to standard Enum enumerations: >>> class Shape(IntEnum): ... CIRCLE = 1 ... SQUARE = 2 ... >>> class Color(Enum): ... RED = 1 ... GREEN = 2 ... >>> Shape.CIRCLE == Color.RED False IntEnum values behave like integers in other ways you’d expect: >>> int(Shape.CIRCLE) 1 >>> ['a', 'b', 'c'][Shape.CIRCLE] 'b' >>> [i for i in range(Shape.SQUARE)] [0, 1] IntFlag The next variation of Enum provided, IntFlag, is also based on int. The difference being IntFlag members can be combined using the bitwise operators (&, |, ^, ~) and the result is still an IntFlag member. However, as the name implies, IntFlag members also subclass int and can be used wherever an int is used. Any operation on an IntFlag member besides the bit-wise operations will lose the IntFlag membership. New in version 3.6. Sample IntFlag class: >>> from enum import IntFlag >>> class Perm(IntFlag): ... R = 4 ... W = 2 ... X = 1 ... >>> Perm.R | Perm.W <Perm.R|W: 6> >>> Perm.R + Perm.W 6 >>> RW = Perm.R | Perm.W >>> Perm.R in RW True It is also possible to name the combinations: >>> class Perm(IntFlag): ... R = 4 ... W = 2 ... X = 1 ... RWX = 7 >>> Perm.RWX <Perm.RWX: 7> >>> ~Perm.RWX <Perm.-8: -8> Another important difference between IntFlag and Enum is that if no flags are set (the value is 0), its boolean evaluation is False: >>> Perm.R & Perm.X <Perm.0: 0> >>> bool(Perm.R & Perm.X) False Because IntFlag members are also subclasses of int they can be combined with them: >>> Perm.X | 8 <Perm.8|X: 9> Flag The last variation is Flag. Like IntFlag, Flag members can be combined using the bitwise operators (&, |, ^, ~). Unlike IntFlag, they cannot be combined with, nor compared against, any other Flag enumeration, nor int. While it is possible to specify the values directly it is recommended to use auto as the value and let Flag select an appropriate value. New in version 3.6. Like IntFlag, if a combination of Flag members results in no flags being set, the boolean evaluation is False: >>> from enum import Flag, auto >>> class Color(Flag): ... RED = auto() ... BLUE = auto() ... GREEN = auto() ... >>> Color.RED & Color.GREEN <Color.0: 0> >>> bool(Color.RED & Color.GREEN) False Individual flags should have values that are powers of two (1, 2, 4, 8, …), while combinations of flags won’t: >>> class Color(Flag): ... RED = auto() ... BLUE = auto() ... GREEN = auto() ... WHITE = RED | BLUE | GREEN ... >>> Color.WHITE <Color.WHITE: 7> Giving a name to the “no flags set” condition does not change its boolean value: >>> class Color(Flag): ... BLACK = 0 ... RED = auto() ... BLUE = auto() ... GREEN = auto() ... >>> Color.BLACK <Color.BLACK: 0> >>> bool(Color.BLACK) False Note For the majority of new code, Enum and Flag are strongly recommended, since IntEnum and IntFlag break some semantic promises of an enumeration (by being comparable to integers, and thus by transitivity to other unrelated enumerations). IntEnum and IntFlag should be used only in cases where Enum and Flag will not do; for example, when integer constants are replaced with enumerations, or for interoperability with other systems. Others While IntEnum is part of the enum module, it would be very simple to implement independently: class IntEnum(int, Enum): pass This demonstrates how similar derived enumerations can be defined; for example a StrEnum that mixes in str instead of int. Some rules: When subclassing Enum, mix-in types must appear before Enum itself in the sequence of bases, as in the IntEnum example above. While Enum can have members of any type, once you mix in an additional type, all the members must have values of that type, e.g. int above. This restriction does not apply to mix-ins which only add methods and don’t specify another type. When another data type is mixed in, the value attribute is not the same as the enum member itself, although it is equivalent and will compare equal. %-style formatting: %s and %r call the Enum class’s __str__() and __repr__() respectively; other codes (such as %i or %h for IntEnum) treat the enum member as its mixed-in type. Formatted string literals, str.format(), and format() will use the mixed-in type’s __format__() unless __str__() or __format__() is overridden in the subclass, in which case the overridden methods or Enum methods will be used. Use the !s and !r format codes to force usage of the Enum class’s __str__() and __repr__() methods. When to use __new__() vs. __init__() __new__() must be used whenever you want to customize the actual value of the Enum member. Any other modifications may go in either __new__() or __init__(), with __init__() being preferred. For example, if you want to pass several items to the constructor, but only want one of them to be the value: >>> class Coordinate(bytes, Enum): ... """ ... Coordinate with binary codes that can be indexed by the int code. ... """ ... def __new__(cls, value, label, unit): ... obj = bytes.__new__(cls, [value]) ... obj._value_ = value ... obj.label = label ... obj.unit = unit ... return obj ... PX = (0, 'P.X', 'km') ... PY = (1, 'P.Y', 'km') ... VX = (2, 'V.X', 'km/s') ... VY = (3, 'V.Y', 'km/s') ... >>> print(Coordinate['PY']) Coordinate.PY >>> print(Coordinate(3)) Coordinate.VY Interesting examples While Enum, IntEnum, IntFlag, and Flag are expected to cover the majority of use-cases, they cannot cover them all. Here are recipes for some different types of enumerations that can be used directly, or as examples for creating one’s own. Omitting values In many use-cases one doesn’t care what the actual value of an enumeration is. There are several ways to define this type of simple enumeration: use instances of auto for the value use instances of object as the value use a descriptive string as the value use a tuple as the value and a custom __new__() to replace the tuple with an int value Using any of these methods signifies to the user that these values are not important, and also enables one to add, remove, or reorder members without having to renumber the remaining members. Whichever method you choose, you should provide a repr() that also hides the (unimportant) value: >>> class NoValue(Enum): ... def __repr__(self): ... return '<%s.%s>' % (self.__class__.__name__, self.name) ... Using auto Using auto would look like: >>> class Color(NoValue): ... RED = auto() ... BLUE = auto() ... GREEN = auto() ... >>> Color.GREEN <Color.GREEN> Using object Using object would look like: >>> class Color(NoValue): ... RED = object() ... GREEN = object() ... BLUE = object() ... >>> Color.GREEN <Color.GREEN> Using a descriptive string Using a string as the value would look like: >>> class Color(NoValue): ... RED = 'stop' ... GREEN = 'go' ... BLUE = 'too fast!' ... >>> Color.GREEN <Color.GREEN> >>> Color.GREEN.value 'go' Using a custom __new__() Using an auto-numbering __new__() would look like: >>> class AutoNumber(NoValue): ... def __new__(cls): ... value = len(cls.__members__) + 1 ... obj = object.__new__(cls) ... obj._value_ = value ... return obj ... >>> class Color(AutoNumber): ... RED = () ... GREEN = () ... BLUE = () ... >>> Color.GREEN <Color.GREEN> >>> Color.GREEN.value 2 To make a more general purpose AutoNumber, add *args to the signature: >>> class AutoNumber(NoValue): ... def __new__(cls, *args): # this is the only change from above ... value = len(cls.__members__) + 1 ... obj = object.__new__(cls) ... obj._value_ = value ... return obj ... Then when you inherit from AutoNumber you can write your own __init__ to handle any extra arguments: >>> class Swatch(AutoNumber): ... def __init__(self, pantone='unknown'): ... self.pantone = pantone ... AUBURN = '3497' ... SEA_GREEN = '1246' ... BLEACHED_CORAL = () # New color, no Pantone code yet! ... >>> Swatch.SEA_GREEN <Swatch.SEA_GREEN: 2> >>> Swatch.SEA_GREEN.pantone '1246' >>> Swatch.BLEACHED_CORAL.pantone 'unknown' Note The __new__() method, if defined, is used during creation of the Enum members; it is then replaced by Enum’s __new__() which is used after class creation for lookup of existing members. OrderedEnum An ordered enumeration that is not based on IntEnum and so maintains the normal Enum invariants (such as not being comparable to other enumerations): >>> class OrderedEnum(Enum): ... def __ge__(self, other): ... if self.__class__ is other.__class__: ... return self.value >= other.value ... return NotImplemented ... def __gt__(self, other): ... if self.__class__ is other.__class__: ... return self.value > other.value ... return NotImplemented ... def __le__(self, other): ... if self.__class__ is other.__class__: ... return self.value <= other.value ... return NotImplemented ... def __lt__(self, other): ... if self.__class__ is other.__class__: ... return self.value < other.value ... return NotImplemented ... >>> class Grade(OrderedEnum): ... A = 5 ... B = 4 ... C = 3 ... D = 2 ... F = 1 ... >>> Grade.C < Grade.A True DuplicateFreeEnum Raises an error if a duplicate member name is found instead of creating an alias: >>> class DuplicateFreeEnum(Enum): ... def __init__(self, *args): ... cls = self.__class__ ... if any(self.value == e.value for e in cls): ... a = self.name ... e = cls(self.value).name ... raise ValueError( ... "aliases not allowed in DuplicateFreeEnum: %r --> %r" ... % (a, e)) ... >>> class Color(DuplicateFreeEnum): ... RED = 1 ... GREEN = 2 ... BLUE = 3 ... GRENE = 2 ... Traceback (most recent call last): ... ValueError: aliases not allowed in DuplicateFreeEnum: 'GRENE' --> 'GREEN' Note This is a useful example for subclassing Enum to add or change other behaviors as well as disallowing aliases. If the only desired change is disallowing aliases, the unique() decorator can be used instead. Planet If __new__() or __init__() is defined the value of the enum member will be passed to those methods: >>> class Planet(Enum): ... MERCURY = (3.303e+23, 2.4397e6) ... VENUS = (4.869e+24, 6.0518e6) ... EARTH = (5.976e+24, 6.37814e6) ... MARS = (6.421e+23, 3.3972e6) ... JUPITER = (1.9e+27, 7.1492e7) ... SATURN = (5.688e+26, 6.0268e7) ... URANUS = (8.686e+25, 2.5559e7) ... NEPTUNE = (1.024e+26, 2.4746e7) ... def __init__(self, mass, radius): ... self.mass = mass # in kilograms ... self.radius = radius # in meters ... @property ... def surface_gravity(self): ... # universal gravitational constant (m3 kg-1 s-2) ... G = 6.67300E-11 ... return G * self.mass / (self.radius * self.radius) ... >>> Planet.EARTH.value (5.976e+24, 6378140.0) >>> Planet.EARTH.surface_gravity 9.802652743337129 TimePeriod An example to show the _ignore_ attribute in use: >>> from datetime import timedelta >>> class Period(timedelta, Enum): ... "different lengths of time" ... _ignore_ = 'Period i' ... Period = vars() ... for i in range(367): ... Period['day_%d' % i] = i ... >>> list(Period)[:2] [<Period.day_0: datetime.timedelta(0)>, <Period.day_1: datetime.timedelta(days=1)>] >>> list(Period)[-2:] [<Period.day_365: datetime.timedelta(days=365)>, <Period.day_366: datetime.timedelta(days=366)>] How are Enums different? Enums have a custom metaclass that affects many aspects of both derived Enum classes and their instances (members). Enum Classes The EnumMeta metaclass is responsible for providing the __contains__(), __dir__(), __iter__() and other methods that allow one to do things with an Enum class that fail on a typical class, such as list(Color) or some_enum_var in Color. EnumMeta is responsible for ensuring that various other methods on the final Enum class are correct (such as __new__(), __getnewargs__(), __str__() and __repr__()). Enum Members (aka instances) The most interesting thing about Enum members is that they are singletons. EnumMeta creates them all while it is creating the Enum class itself, and then puts a custom __new__() in place to ensure that no new ones are ever instantiated by returning only the existing member instances. Finer Points Supported __dunder__ names __members__ is a read-only ordered mapping of member_name:member items. It is only available on the class. __new__(), if specified, must create and return the enum members; it is also a very good idea to set the member’s _value_ appropriately. Once all the members are created it is no longer used. Supported _sunder_ names _name_ – name of the member _value_ – value of the member; can be set / modified in __new__ _missing_ – a lookup function used when a value is not found; may be overridden _ignore_ – a list of names, either as a list or a str, that will not be transformed into members, and will be removed from the final class _order_ – used in Python 2/3 code to ensure member order is consistent (class attribute, removed during class creation) _generate_next_value_ – used by the Functional API and by auto to get an appropriate value for an enum member; may be overridden New in version 3.6: _missing_, _order_, _generate_next_value_ New in version 3.7: _ignore_ To help keep Python 2 / Python 3 code in sync an _order_ attribute can be provided. It will be checked against the actual order of the enumeration and raise an error if the two do not match: >>> class Color(Enum): ... _order_ = 'RED GREEN BLUE' ... RED = 1 ... BLUE = 3 ... GREEN = 2 ... Traceback (most recent call last): ... TypeError: member order does not match _order_ Note In Python 2 code the _order_ attribute is necessary as definition order is lost before it can be recorded. _Private__names Private names will be normal attributes in Python 3.10 instead of either an error or a member (depending on if the name ends with an underscore). Using these names in 3.9 will issue a DeprecationWarning. Enum member type Enum members are instances of their Enum class, and are normally accessed as EnumClass.member. Under certain circumstances they can also be accessed as EnumClass.member.member, but you should never do this as that lookup may fail or, worse, return something besides the Enum member you are looking for (this is another good reason to use all-uppercase names for members): >>> class FieldTypes(Enum): ... name = 0 ... value = 1 ... size = 2 ... >>> FieldTypes.value.size <FieldTypes.size: 2> >>> FieldTypes.size.value 2 Changed in version 3.5. Boolean value of Enum classes and members Enum members that are mixed with non-Enum types (such as int, str, etc.) are evaluated according to the mixed-in type’s rules; otherwise, all members evaluate as True. To make your own Enum’s boolean evaluation depend on the member’s value add the following to your class: def __bool__(self): return bool(self.value) Enum classes always evaluate as True. Enum classes with methods If you give your Enum subclass extra methods, like the Planet class above, those methods will show up in a dir() of the member, but not of the class: >>> dir(Planet) ['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', '__class__', '__doc__', '__members__', '__module__'] >>> dir(Planet.EARTH) ['__class__', '__doc__', '__module__', 'name', 'surface_gravity', 'value'] Combining members of Flag If a combination of Flag members is not named, the repr() will include all named flags and all named combinations of flags that are in the value: >>> class Color(Flag): ... RED = auto() ... GREEN = auto() ... BLUE = auto() ... MAGENTA = RED | BLUE ... YELLOW = RED | GREEN ... CYAN = GREEN | BLUE ... >>> Color(3) # named combination <Color.YELLOW: 3> >>> Color(7) # not named combination <Color.CYAN|MAGENTA|BLUE|YELLOW|GREEN|RED: 7>
python.library.enum
class enum.auto Instances are replaced with an appropriate value for Enum members. By default, the initial value starts at 1.
python.library.enum#enum.auto
class enum.Enum Base class for creating enumerated constants. See section Functional API for an alternate construction syntax.
python.library.enum#enum.Enum
class enum.Flag Base class for creating enumerated constants that can be combined using the bitwise operations without losing their Flag membership.
python.library.enum#enum.Flag
class enum.IntEnum Base class for creating enumerated constants that are also subclasses of int.
python.library.enum#enum.IntEnum
class enum.IntFlag Base class for creating enumerated constants that can be combined using the bitwise operators without losing their IntFlag membership. IntFlag members are also subclasses of int.
python.library.enum#enum.IntFlag
@enum.unique
python.library.enum#enum.unique
enumerate(iterable, start=0) Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable. >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')] Equivalent to: def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1
python.library.functions#enumerate
exception EnvironmentError
python.library.exceptions#EnvironmentError
exception EOFError Raised when the input() function hits an end-of-file condition (EOF) without reading any data. (N.B.: the io.IOBase.read() and io.IOBase.readline() methods return an empty string when they hit EOF.)
python.library.exceptions#EOFError
errno — Standard errno system symbols This module makes available standard errno system symbols. The value of each symbol is the corresponding integer value. The names and descriptions are borrowed from linux/include/errno.h, which should be pretty all-inclusive. errno.errorcode Dictionary providing a mapping from the errno value to the string name in the underlying system. For instance, errno.errorcode[errno.EPERM] maps to 'EPERM'. To translate a numeric error code to an error message, use os.strerror(). Of the following list, symbols that are not used on the current platform are not defined by the module. The specific list of defined symbols is available as errno.errorcode.keys(). Symbols available can include: errno.EPERM Operation not permitted errno.ENOENT No such file or directory errno.ESRCH No such process errno.EINTR Interrupted system call. See also This error is mapped to the exception InterruptedError. errno.EIO I/O error errno.ENXIO No such device or address errno.E2BIG Arg list too long errno.ENOEXEC Exec format error errno.EBADF Bad file number errno.ECHILD No child processes errno.EAGAIN Try again errno.ENOMEM Out of memory errno.EACCES Permission denied errno.EFAULT Bad address errno.ENOTBLK Block device required errno.EBUSY Device or resource busy errno.EEXIST File exists errno.EXDEV Cross-device link errno.ENODEV No such device errno.ENOTDIR Not a directory errno.EISDIR Is a directory errno.EINVAL Invalid argument errno.ENFILE File table overflow errno.EMFILE Too many open files errno.ENOTTY Not a typewriter errno.ETXTBSY Text file busy errno.EFBIG File too large errno.ENOSPC No space left on device errno.ESPIPE Illegal seek errno.EROFS Read-only file system errno.EMLINK Too many links errno.EPIPE Broken pipe errno.EDOM Math argument out of domain of func errno.ERANGE Math result not representable errno.EDEADLK Resource deadlock would occur errno.ENAMETOOLONG File name too long errno.ENOLCK No record locks available errno.ENOSYS Function not implemented errno.ENOTEMPTY Directory not empty errno.ELOOP Too many symbolic links encountered errno.EWOULDBLOCK Operation would block errno.ENOMSG No message of desired type errno.EIDRM Identifier removed errno.ECHRNG Channel number out of range errno.EL2NSYNC Level 2 not synchronized errno.EL3HLT Level 3 halted errno.EL3RST Level 3 reset errno.ELNRNG Link number out of range errno.EUNATCH Protocol driver not attached errno.ENOCSI No CSI structure available errno.EL2HLT Level 2 halted errno.EBADE Invalid exchange errno.EBADR Invalid request descriptor errno.EXFULL Exchange full errno.ENOANO No anode errno.EBADRQC Invalid request code errno.EBADSLT Invalid slot errno.EDEADLOCK File locking deadlock error errno.EBFONT Bad font file format errno.ENOSTR Device not a stream errno.ENODATA No data available errno.ETIME Timer expired errno.ENOSR Out of streams resources errno.ENONET Machine is not on the network errno.ENOPKG Package not installed errno.EREMOTE Object is remote errno.ENOLINK Link has been severed errno.EADV Advertise error errno.ESRMNT Srmount error errno.ECOMM Communication error on send errno.EPROTO Protocol error errno.EMULTIHOP Multihop attempted errno.EDOTDOT RFS specific error errno.EBADMSG Not a data message errno.EOVERFLOW Value too large for defined data type errno.ENOTUNIQ Name not unique on network errno.EBADFD File descriptor in bad state errno.EREMCHG Remote address changed errno.ELIBACC Can not access a needed shared library errno.ELIBBAD Accessing a corrupted shared library errno.ELIBSCN .lib section in a.out corrupted errno.ELIBMAX Attempting to link in too many shared libraries errno.ELIBEXEC Cannot exec a shared library directly errno.EILSEQ Illegal byte sequence errno.ERESTART Interrupted system call should be restarted errno.ESTRPIPE Streams pipe error errno.EUSERS Too many users errno.ENOTSOCK Socket operation on non-socket errno.EDESTADDRREQ Destination address required errno.EMSGSIZE Message too long errno.EPROTOTYPE Protocol wrong type for socket errno.ENOPROTOOPT Protocol not available errno.EPROTONOSUPPORT Protocol not supported errno.ESOCKTNOSUPPORT Socket type not supported errno.EOPNOTSUPP Operation not supported on transport endpoint errno.EPFNOSUPPORT Protocol family not supported errno.EAFNOSUPPORT Address family not supported by protocol errno.EADDRINUSE Address already in use errno.EADDRNOTAVAIL Cannot assign requested address errno.ENETDOWN Network is down errno.ENETUNREACH Network is unreachable errno.ENETRESET Network dropped connection because of reset errno.ECONNABORTED Software caused connection abort errno.ECONNRESET Connection reset by peer errno.ENOBUFS No buffer space available errno.EISCONN Transport endpoint is already connected errno.ENOTCONN Transport endpoint is not connected errno.ESHUTDOWN Cannot send after transport endpoint shutdown errno.ETOOMANYREFS Too many references: cannot splice errno.ETIMEDOUT Connection timed out errno.ECONNREFUSED Connection refused errno.EHOSTDOWN Host is down errno.EHOSTUNREACH No route to host errno.EALREADY Operation already in progress errno.EINPROGRESS Operation now in progress errno.ESTALE Stale NFS file handle errno.EUCLEAN Structure needs cleaning errno.ENOTNAM Not a XENIX named type file errno.ENAVAIL No XENIX semaphores available errno.EISNAM Is a named type file errno.EREMOTEIO Remote I/O error errno.EDQUOT Quota exceeded
python.library.errno
eval(expression[, globals[, locals]]) The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object. The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. If the globals dictionary is present and does not contain a value for the key __builtins__, a reference to the dictionary of the built-in module builtins is inserted under that key before expression is parsed. This means that expression normally has full access to the standard builtins module and restricted environments are propagated. If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed with the globals and locals in the environment where eval() is called. Note, eval() does not have access to the nested scopes (non-locals) in the enclosing environment. The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example: >>> x = 1 >>> eval('x+1') 2 This function can also be used to execute arbitrary code objects (such as those created by compile()). In this case pass a code object instead of a string. If the code object has been compiled with 'exec' as the mode argument, eval()’s return value will be None. Hints: dynamic execution of statements is supported by the exec() function. The globals() and locals() functions returns the current global and local dictionary, respectively, which may be useful to pass around for use by eval() or exec(). See ast.literal_eval() for a function that can safely evaluate strings with expressions containing only literals. Raises an auditing event exec with the code object as the argument. Code compilation events may also be raised.
python.library.functions#eval
exception Exception All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class.
python.library.exceptions#Exception
Exceptions Source code: Lib/asyncio/exceptions.py exception asyncio.TimeoutError The operation has exceeded the given deadline. Important This exception is different from the builtin TimeoutError exception. exception asyncio.CancelledError The operation has been cancelled. This exception can be caught to perform custom operations when asyncio Tasks are cancelled. In almost all situations the exception must be re-raised. Changed in version 3.8: CancelledError is now a subclass of BaseException. exception asyncio.InvalidStateError Invalid internal state of Task or Future. Can be raised in situations like setting a result value for a Future object that already has a result value set. exception asyncio.SendfileNotAvailableError The “sendfile” syscall is not available for the given socket or file type. A subclass of RuntimeError. exception asyncio.IncompleteReadError The requested read operation did not complete fully. Raised by the asyncio stream APIs. This exception is a subclass of EOFError. expected The total number (int) of expected bytes. partial A string of bytes read before the end of stream was reached. exception asyncio.LimitOverrunError Reached the buffer size limit while looking for a separator. Raised by the asyncio stream APIs. consumed The total number of to be consumed bytes.
python.library.asyncio-exceptions
Built-in Exceptions In Python, all exceptions must be instances of a class that derives from BaseException. In a try statement with an except clause that mentions a particular class, that clause also handles any exception classes derived from that class (but not exception classes from which it is derived). Two exception classes that are not related via subclassing are never equivalent, even if they have the same name. The built-in exceptions listed below can be generated by the interpreter or built-in functions. Except where mentioned, they have an “associated value” indicating the detailed cause of the error. This may be a string or a tuple of several items of information (e.g., an error code and a string explaining the code). The associated value is usually passed as arguments to the exception class’s constructor. User code can raise built-in exceptions. This can be used to test an exception handler or to report an error condition “just like” the situation in which the interpreter raises the same exception; but beware that there is nothing to prevent user code from raising an inappropriate error. The built-in exception classes can be subclassed to define new exceptions; programmers are encouraged to derive new exceptions from the Exception class or one of its subclasses, and not from BaseException. More information on defining exceptions is available in the Python Tutorial under User-defined Exceptions. When raising (or re-raising) an exception in an except or finally clause __context__ is automatically set to the last exception caught; if the new exception is not handled the traceback that is eventually displayed will include the originating exception(s) and the final exception. When raising a new exception (rather than using a bare raise to re-raise the exception currently being handled), the implicit exception context can be supplemented with an explicit cause by using from with raise: raise new_exc from original_exc The expression following from must be an exception or None. It will be set as __cause__ on the raised exception. Setting __cause__ also implicitly sets the __suppress_context__ attribute to True, so that using raise new_exc from None effectively replaces the old exception with the new one for display purposes (e.g. converting KeyError to AttributeError), while leaving the old exception available in __context__ for introspection when debugging. The default traceback display code shows these chained exceptions in addition to the traceback for the exception itself. An explicitly chained exception in __cause__ is always shown when present. An implicitly chained exception in __context__ is shown only if __cause__ is None and __suppress_context__ is false. In either case, the exception itself is always shown after any chained exceptions so that the final line of the traceback always shows the last exception that was raised. Base classes The following exceptions are used mostly as base classes for other exceptions. exception BaseException The base class for all built-in exceptions. It is not meant to be directly inherited by user-defined classes (for that, use Exception). If str() is called on an instance of this class, the representation of the argument(s) to the instance are returned, or the empty string when there were no arguments. args The tuple of arguments given to the exception constructor. Some built-in exceptions (like OSError) expect a certain number of arguments and assign a special meaning to the elements of this tuple, while others are usually called only with a single string giving an error message. with_traceback(tb) This method sets tb as the new traceback for the exception and returns the exception object. It is usually used in exception handling code like this: try: ... except SomeException: tb = sys.exc_info()[2] raise OtherException(...).with_traceback(tb) exception Exception All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class. exception ArithmeticError The base class for those built-in exceptions that are raised for various arithmetic errors: OverflowError, ZeroDivisionError, FloatingPointError. exception BufferError Raised when a buffer related operation cannot be performed. exception LookupError The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid: IndexError, KeyError. This can be raised directly by codecs.lookup(). Concrete exceptions The following exceptions are the exceptions that are usually raised. exception AssertionError Raised when an assert statement fails. exception AttributeError Raised when an attribute reference (see Attribute references) or assignment fails. (When an object does not support attribute references or attribute assignments at all, TypeError is raised.) exception EOFError Raised when the input() function hits an end-of-file condition (EOF) without reading any data. (N.B.: the io.IOBase.read() and io.IOBase.readline() methods return an empty string when they hit EOF.) exception FloatingPointError Not currently used. exception GeneratorExit Raised when a generator or coroutine is closed; see generator.close() and coroutine.close(). It directly inherits from BaseException instead of Exception since it is technically not an error. exception ImportError Raised when the import statement has troubles trying to load a module. Also raised when the “from list” in from ... import has a name that cannot be found. The name and path attributes can be set using keyword-only arguments to the constructor. When set they represent the name of the module that was attempted to be imported and the path to any file which triggered the exception, respectively. Changed in version 3.3: Added the name and path attributes. exception ModuleNotFoundError 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. exception IndexError Raised when a sequence subscript is out of range. (Slice indices are silently truncated to fall in the allowed range; if an index is not an integer, TypeError is raised.) exception KeyError Raised when a mapping (dictionary) key is not found in the set of existing keys. exception KeyboardInterrupt Raised when the user hits the interrupt key (normally Control-C or Delete). During execution, a check for interrupts is made regularly. The exception inherits from BaseException so as to not be accidentally caught by code that catches Exception and thus prevent the interpreter from exiting. exception MemoryError Raised when an operation runs out of memory but the situation may still be rescued (by deleting some objects). The associated value is a string indicating what kind of (internal) operation ran out of memory. Note that because of the underlying memory management architecture (C’s malloc() function), the interpreter may not always be able to completely recover from this situation; it nevertheless raises an exception so that a stack traceback can be printed, in case a run-away program was the cause. exception NameError Raised when a local or global name is not found. This applies only to unqualified names. The associated value is an error message that includes the name that could not be found. exception NotImplementedError This exception is derived from RuntimeError. In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method, or while the class is being developed to indicate that the real implementation still needs to be added. Note It should not be used to indicate that an operator or method is not meant to be supported at all – in that case either leave the operator / method undefined or, if a subclass, set it to None. Note NotImplementedError and NotImplemented are not interchangeable, even though they have similar names and purposes. See NotImplemented for details on when to use it. exception OSError([arg]) exception OSError(errno, strerror[, filename[, winerror[, filename2]]]) This exception is raised when a system function returns a system-related error, including I/O failures such as “file not found” or “disk full” (not for illegal argument types or other incidental errors). The second form of the constructor sets the corresponding attributes, described below. The attributes default to None if not specified. For backwards compatibility, if three arguments are passed, the args attribute contains only a 2-tuple of the first two constructor arguments. The constructor often actually returns a subclass of OSError, as described in OS exceptions below. The particular subclass depends on the final errno value. This behaviour only occurs when constructing OSError directly or via an alias, and is not inherited when subclassing. errno A numeric error code from the C variable errno. winerror Under Windows, this gives you the native Windows error code. The errno attribute is then an approximate translation, in POSIX terms, of that native error code. Under Windows, if the winerror constructor argument is an integer, the errno attribute is determined from the Windows error code, and the errno argument is ignored. On other platforms, the winerror argument is ignored, and the winerror attribute does not exist. strerror The corresponding error message, as provided by the operating system. It is formatted by the C functions perror() under POSIX, and FormatMessage() under Windows. filename filename2 For exceptions that involve a file system path (such as open() or os.unlink()), filename is the file name passed to the function. For functions that involve two file system paths (such as os.rename()), filename2 corresponds to the second file name passed to the function. Changed in version 3.3: EnvironmentError, IOError, WindowsError, socket.error, select.error and mmap.error have been merged into OSError, and the constructor may return a subclass. Changed in version 3.4: The filename attribute is now the original file name passed to the function, instead of the name encoded to or decoded from the filesystem encoding. Also, the filename2 constructor argument and attribute was added. exception OverflowError Raised when the result of an arithmetic operation is too large to be represented. This cannot occur for integers (which would rather raise MemoryError than give up). However, for historical reasons, OverflowError is sometimes raised for integers that are outside a required range. Because of the lack of standardization of floating point exception handling in C, most floating point operations are not checked. exception RecursionError This exception is derived from RuntimeError. It is raised when the interpreter detects that the maximum recursion depth (see sys.getrecursionlimit()) is exceeded. New in version 3.5: Previously, a plain RuntimeError was raised. exception ReferenceError This exception is raised when a weak reference proxy, created by the weakref.proxy() function, is used to access an attribute of the referent after it has been garbage collected. For more information on weak references, see the weakref module. exception RuntimeError Raised when an error is detected that doesn’t fall in any of the other categories. The associated value is a string indicating what precisely went wrong. exception StopIteration Raised by built-in function next() and an iterator’s __next__() method to signal that there are no further items produced by the iterator. The exception object has a single attribute value, which is given as an argument when constructing the exception, and defaults to None. When a generator or coroutine function returns, a new StopIteration instance is raised, and the value returned by the function is used as the value parameter to the constructor of the exception. If a generator code directly or indirectly raises StopIteration, it is converted into a RuntimeError (retaining the StopIteration as the new exception’s cause). Changed in version 3.3: Added value attribute and the ability for generator functions to use it to return a value. Changed in version 3.5: Introduced the RuntimeError transformation via from __future__ import generator_stop, see PEP 479. Changed in version 3.7: Enable PEP 479 for all code by default: a StopIteration error raised in a generator is transformed into a RuntimeError. exception StopAsyncIteration Must be raised by __anext__() method of an asynchronous iterator object to stop the iteration. New in version 3.5. exception SyntaxError Raised when the parser encounters a syntax error. This may occur in an import statement, in a call to the built-in functions exec() or eval(), or when reading the initial script or standard input (also interactively). The str() of the exception instance returns only the error message. filename The name of the file the syntax error occurred in. lineno Which line number in the file the error occurred in. This is 1-indexed: the first line in the file has a lineno of 1. offset The column in the line where the error occurred. This is 1-indexed: the first character in the line has an offset of 1. text The source code text involved in the error. exception IndentationError Base class for syntax errors related to incorrect indentation. This is a subclass of SyntaxError. exception TabError Raised when indentation contains an inconsistent use of tabs and spaces. This is a subclass of IndentationError. exception SystemError Raised when the interpreter finds an internal error, but the situation does not look so serious to cause it to abandon all hope. The associated value is a string indicating what went wrong (in low-level terms). You should report this to the author or maintainer of your Python interpreter. Be sure to report the version of the Python interpreter (sys.version; it is also printed at the start of an interactive Python session), the exact error message (the exception’s associated value) and if possible the source of the program that triggered the error. exception SystemExit This exception is raised by the sys.exit() function. It inherits from BaseException instead of Exception so that it is not accidentally caught by code that catches Exception. This allows the exception to properly propagate up and cause the interpreter to exit. When it is not handled, the Python interpreter exits; no stack traceback is printed. The constructor accepts the same optional argument passed to sys.exit(). If the value is an integer, it specifies the system exit status (passed to C’s exit() function); if it is None, the exit status is zero; if it has another type (such as a string), the object’s value is printed and the exit status is one. A call to sys.exit() is translated into an exception so that clean-up handlers (finally clauses of try statements) can be executed, and so that a debugger can execute a script without running the risk of losing control. The os._exit() function can be used if it is absolutely positively necessary to exit immediately (for example, in the child process after a call to os.fork()). code The exit status or error message that is passed to the constructor. (Defaults to None.) exception TypeError Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch. This exception may be raised by user code to indicate that an attempted operation on an object is not supported, and is not meant to be. If an object is meant to support a given operation but has not yet provided an implementation, NotImplementedError is the proper exception to raise. Passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError, but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a ValueError. exception UnboundLocalError Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable. This is a subclass of NameError. exception UnicodeError Raised when a Unicode-related encoding or decoding error occurs. It is a subclass of ValueError. UnicodeError has attributes that describe the encoding or decoding error. For example, err.object[err.start:err.end] gives the particular invalid input that the codec failed on. encoding The name of the encoding that raised the error. reason A string describing the specific codec error. object The object the codec was attempting to encode or decode. start The first index of invalid data in object. end The index after the last invalid data in object. exception UnicodeEncodeError Raised when a Unicode-related error occurs during encoding. It is a subclass of UnicodeError. exception UnicodeDecodeError Raised when a Unicode-related error occurs during decoding. It is a subclass of UnicodeError. exception UnicodeTranslateError Raised when a Unicode-related error occurs during translating. It is a subclass of UnicodeError. exception ValueError Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError. exception ZeroDivisionError Raised when the second argument of a division or modulo operation is zero. The associated value is a string indicating the type of the operands and the operation. The following exceptions are kept for compatibility with previous versions; starting from Python 3.3, they are aliases of OSError. exception EnvironmentError exception IOError exception WindowsError Only available on Windows. OS exceptions The following exceptions are subclasses of OSError, they get raised depending on the system error code. exception BlockingIOError Raised when an operation would block on an object (e.g. socket) set for non-blocking operation. Corresponds to errno EAGAIN, EALREADY, EWOULDBLOCK and EINPROGRESS. In addition to those of OSError, BlockingIOError can have one more attribute: characters_written An integer containing the number of characters written to the stream before it blocked. This attribute is available when using the buffered I/O classes from the io module. exception ChildProcessError Raised when an operation on a child process failed. Corresponds to errno ECHILD. exception ConnectionError A base class for connection-related issues. Subclasses are BrokenPipeError, ConnectionAbortedError, ConnectionRefusedError and ConnectionResetError. exception BrokenPipeError A subclass of ConnectionError, raised when trying to write on a pipe while the other end has been closed, or trying to write on a socket which has been shutdown for writing. Corresponds to errno EPIPE and ESHUTDOWN. exception ConnectionAbortedError A subclass of ConnectionError, raised when a connection attempt is aborted by the peer. Corresponds to errno ECONNABORTED. exception ConnectionRefusedError A subclass of ConnectionError, raised when a connection attempt is refused by the peer. Corresponds to errno ECONNREFUSED. exception ConnectionResetError A subclass of ConnectionError, raised when a connection is reset by the peer. Corresponds to errno ECONNRESET. exception FileExistsError Raised when trying to create a file or directory which already exists. Corresponds to errno EEXIST. exception FileNotFoundError Raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT. exception InterruptedError Raised when a system call is interrupted by an incoming signal. Corresponds to errno EINTR. Changed in version 3.5: Python now retries system calls when a syscall is interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale), instead of raising InterruptedError. exception IsADirectoryError Raised when a file operation (such as os.remove()) is requested on a directory. Corresponds to errno EISDIR. exception NotADirectoryError Raised when a directory operation (such as os.listdir()) is requested on something which is not a directory. Corresponds to errno ENOTDIR. exception PermissionError Raised when trying to run an operation without the adequate access rights - for example filesystem permissions. Corresponds to errno EACCES and EPERM. exception ProcessLookupError Raised when a given process doesn’t exist. Corresponds to errno ESRCH. exception TimeoutError Raised when a system function timed out at the system level. Corresponds to errno ETIMEDOUT. New in version 3.3: All the above OSError subclasses were added. See also PEP 3151 - Reworking the OS and IO exception hierarchy Warnings The following exceptions are used as warning categories; see the Warning Categories documentation for more details. exception Warning Base class for warning categories. exception UserWarning Base class for warnings generated by user code. exception DeprecationWarning Base class for warnings about deprecated features when those warnings are intended for other Python developers. Ignored by the default warning filters, except in the __main__ module (PEP 565). Enabling the Python Development Mode shows this warning. exception PendingDeprecationWarning Base class for warnings about features which are obsolete and expected to be deprecated in the future, but are not deprecated at the moment. This class is rarely used as emitting a warning about a possible upcoming deprecation is unusual, and DeprecationWarning is preferred for already active deprecations. Ignored by the default warning filters. Enabling the Python Development Mode shows this warning. exception SyntaxWarning Base class for warnings about dubious syntax. exception RuntimeWarning Base class for warnings about dubious runtime behavior. exception FutureWarning Base class for warnings about deprecated features when those warnings are intended for end users of applications that are written in Python. exception ImportWarning Base class for warnings about probable mistakes in module imports. Ignored by the default warning filters. Enabling the Python Development Mode shows this warning. exception UnicodeWarning Base class for warnings related to Unicode. exception BytesWarning Base class for warnings related to bytes and bytearray. exception ResourceWarning Base class for warnings related to resource usage. Ignored by the default warning filters. Enabling the Python Development Mode shows this warning. New in version 3.2. Exception hierarchy The class hierarchy for built-in exceptions is: BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- StopAsyncIteration +-- ArithmeticError | +-- FloatingPointError | +-- OverflowError | +-- ZeroDivisionError +-- AssertionError +-- AttributeError +-- BufferError +-- EOFError +-- ImportError | +-- ModuleNotFoundError +-- LookupError | +-- IndexError | +-- KeyError +-- MemoryError +-- NameError | +-- UnboundLocalError +-- OSError | +-- BlockingIOError | +-- ChildProcessError | +-- ConnectionError | | +-- BrokenPipeError | | +-- ConnectionAbortedError | | +-- ConnectionRefusedError | | +-- ConnectionResetError | +-- FileExistsError | +-- FileNotFoundError | +-- InterruptedError | +-- IsADirectoryError | +-- NotADirectoryError | +-- PermissionError | +-- ProcessLookupError | +-- TimeoutError +-- ReferenceError +-- RuntimeError | +-- NotImplementedError | +-- RecursionError +-- SyntaxError | +-- IndentationError | +-- TabError +-- SystemError +-- TypeError +-- ValueError | +-- UnicodeError | +-- UnicodeDecodeError | +-- UnicodeEncodeError | +-- UnicodeTranslateError +-- Warning +-- DeprecationWarning +-- PendingDeprecationWarning +-- RuntimeWarning +-- SyntaxWarning +-- UserWarning +-- FutureWarning +-- ImportWarning +-- UnicodeWarning +-- BytesWarning +-- ResourceWarning
python.library.exceptions
exec(object[, globals[, locals]]) This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). 1 If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section “File input” in the Reference Manual). Be aware that the nonlocal, yield, and return statements may not be used outside of function definitions even within the context of code passed to the exec() function. The return value is None. In all cases, if the optional parts are omitted, the code is executed in the current scope. If only globals is provided, it must be a dictionary (and not a subclass of dictionary), which will be used for both the global and the local variables. If globals and locals are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition. If the globals dictionary does not contain a value for the key __builtins__, a reference to the dictionary of the built-in module builtins is inserted under that key. That way you can control what builtins are available to the executed code by inserting your own __builtins__ dictionary into globals before passing it to exec(). Raises an auditing event exec with the code object as the argument. Code compilation events may also be raised. Note The built-in functions globals() and locals() return the current global and local dictionary, respectively, which may be useful to pass around for use as the second and third argument to exec(). Note The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.
python.library.functions#exec
quit(code=None) exit(code=None) Objects that when printed, print a message like “Use quit() or Ctrl-D (i.e. EOF) to exit”, and when called, raise SystemExit with the specified exit code.
python.library.constants#exit
False The false value of the bool type. Assignments to False are illegal and raise a SyntaxError.
python.library.constants#False
faulthandler — Dump the Python traceback New in version 3.3. This module contains functions to dump Python tracebacks explicitly, on a fault, after a timeout, or on a user signal. Call faulthandler.enable() to install fault handlers for the SIGSEGV, SIGFPE, SIGABRT, SIGBUS, and SIGILL signals. You can also enable them at startup by setting the PYTHONFAULTHANDLER environment variable or by using the -X faulthandler command line option. The fault handler is compatible with system fault handlers like Apport or the Windows fault handler. The module uses an alternative stack for signal handlers if the sigaltstack() function is available. This allows it to dump the traceback even on a stack overflow. The fault handler is called on catastrophic cases and therefore can only use signal-safe functions (e.g. it cannot allocate memory on the heap). Because of this limitation traceback dumping is minimal compared to normal Python tracebacks: Only ASCII is supported. The backslashreplace error handler is used on encoding. Each string is limited to 500 characters. Only the filename, the function name and the line number are displayed. (no source code) It is limited to 100 frames and 100 threads. The order is reversed: the most recent call is shown first. By default, the Python traceback is written to sys.stderr. To see tracebacks, applications must be run in the terminal. A log file can alternatively be passed to faulthandler.enable(). The module is implemented in C, so tracebacks can be dumped on a crash or when Python is deadlocked. The Python Development Mode calls faulthandler.enable() at Python startup. Dumping the traceback faulthandler.dump_traceback(file=sys.stderr, all_threads=True) Dump the tracebacks of all threads into file. If all_threads is False, dump only the current thread. Changed in version 3.5: Added support for passing file descriptor to this function. Fault handler state faulthandler.enable(file=sys.stderr, all_threads=True) Enable the fault handler: install handlers for the SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL signals to dump the Python traceback. If all_threads is True, produce tracebacks for every running thread. Otherwise, dump only the current thread. The file must be kept open until the fault handler is disabled: see issue with file descriptors. Changed in version 3.5: Added support for passing file descriptor to this function. Changed in version 3.6: On Windows, a handler for Windows exception is also installed. faulthandler.disable() Disable the fault handler: uninstall the signal handlers installed by enable(). faulthandler.is_enabled() Check if the fault handler is enabled. Dumping the tracebacks after a timeout faulthandler.dump_traceback_later(timeout, repeat=False, file=sys.stderr, exit=False) Dump the tracebacks of all threads, after a timeout of timeout seconds, or every timeout seconds if repeat is True. If exit is True, call _exit() with status=1 after dumping the tracebacks. (Note _exit() exits the process immediately, which means it doesn’t do any cleanup like flushing file buffers.) If the function is called twice, the new call replaces previous parameters and resets the timeout. The timer has a sub-second resolution. The file must be kept open until the traceback is dumped or cancel_dump_traceback_later() is called: see issue with file descriptors. This function is implemented using a watchdog thread. Changed in version 3.7: This function is now always available. Changed in version 3.5: Added support for passing file descriptor to this function. faulthandler.cancel_dump_traceback_later() Cancel the last call to dump_traceback_later(). Dumping the traceback on a user signal faulthandler.register(signum, file=sys.stderr, all_threads=True, chain=False) Register a user signal: install a handler for the signum signal to dump the traceback of all threads, or of the current thread if all_threads is False, into file. Call the previous handler if chain is True. The file must be kept open until the signal is unregistered by unregister(): see issue with file descriptors. Not available on Windows. Changed in version 3.5: Added support for passing file descriptor to this function. faulthandler.unregister(signum) Unregister a user signal: uninstall the handler of the signum signal installed by register(). Return True if the signal was registered, False otherwise. Not available on Windows. Issue with file descriptors enable(), dump_traceback_later() and register() keep the file descriptor of their file argument. If the file is closed and its file descriptor is reused by a new file, or if os.dup2() is used to replace the file descriptor, the traceback will be written into a different file. Call these functions again each time that the file is replaced. Example Example of a segmentation fault on Linux with and without enabling the fault handler: $ python3 -c "import ctypes; ctypes.string_at(0)" Segmentation fault $ python3 -q -X faulthandler >>> import ctypes >>> ctypes.string_at(0) Fatal Python error: Segmentation fault Current thread 0x00007fb899f39700 (most recent call first): File "/home/python/cpython/Lib/ctypes/__init__.py", line 486 in string_at File "<stdin>", line 1 in <module> Segmentation fault
python.library.faulthandler
faulthandler.cancel_dump_traceback_later() Cancel the last call to dump_traceback_later().
python.library.faulthandler#faulthandler.cancel_dump_traceback_later
faulthandler.disable() Disable the fault handler: uninstall the signal handlers installed by enable().
python.library.faulthandler#faulthandler.disable
faulthandler.dump_traceback(file=sys.stderr, all_threads=True) Dump the tracebacks of all threads into file. If all_threads is False, dump only the current thread. Changed in version 3.5: Added support for passing file descriptor to this function.
python.library.faulthandler#faulthandler.dump_traceback
faulthandler.dump_traceback_later(timeout, repeat=False, file=sys.stderr, exit=False) Dump the tracebacks of all threads, after a timeout of timeout seconds, or every timeout seconds if repeat is True. If exit is True, call _exit() with status=1 after dumping the tracebacks. (Note _exit() exits the process immediately, which means it doesn’t do any cleanup like flushing file buffers.) If the function is called twice, the new call replaces previous parameters and resets the timeout. The timer has a sub-second resolution. The file must be kept open until the traceback is dumped or cancel_dump_traceback_later() is called: see issue with file descriptors. This function is implemented using a watchdog thread. Changed in version 3.7: This function is now always available. Changed in version 3.5: Added support for passing file descriptor to this function.
python.library.faulthandler#faulthandler.dump_traceback_later