base64 — Base16, Base32, Base64, Base85 Data Encodings Source code: Lib/base64.py This module provides functions for encoding binary data to printable ASCII characters and decoding such encodings back to binary data. It provides encoding and decoding functions for the encodings specified in RFC 3548, which defines the Base16, Base32, and Base64 algorithms, and for the de-facto standard Ascii85 and Base85 encodings. The RFC 3548 encodings are suitable for encoding binary data so that it can safely sent by email, used as parts of URLs, or included as part of an HTTP POST request. The encoding algorithm is not the same as the uuencode program. There are two interfaces provided by this module. The modern interface supports encoding bytes-like objects to ASCII bytes, and decoding bytes-like objects or strings containing ASCII to bytes. Both base-64 alphabets defined in RFC 3548 (normal, and URL- and filesystem-safe) are supported. The legacy interface does not support decoding from strings, but it does provide functions for encoding and decoding to and from file objects. It only supports the Base64 standard alphabet, and it adds newlines every 76 characters as per RFC 2045. Note that if you are looking for RFC 2045 support you probably want to be looking at the email package instead.  Changed in version 3.3: ASCII-only Unicode strings are now accepted by the decoding functions of the modern interface.   Changed in version 3.4: Any bytes-like objects are now accepted by all encoding and decoding functions in this module. Ascii85/Base85 support added.  The modern interface provides:
base64.b64encode(s, altchars=None)
Encode the bytes-like object s using Base64 and return the encoded bytes. Optional altchars must be a bytes-like object of at least length 2 (additional characters are ignored) which specifies an alternative alphabet for the + and / characters. This allows an application to e.g. generate URL or filesystem safe Base64 strings. The default is None, for which the standard Base64 alphabet is used.

base64.b64decode(s, altchars=None, validate=False)
Decode the Base64 encoded bytes-like object or ASCII string s and return the decoded bytes. Optional altchars must be a bytes-like object or ASCII string of at least length 2 (additional characters are ignored) which specifies the alternative alphabet used instead of the + and / characters. A binascii.Error exception is raised if s is incorrectly padded. If validate is False (the default), characters that are neither in the normal base-64 alphabet nor the alternative alphabet are discarded prior to the padding check. If validate is True, these non-alphabet characters in the input result in a binascii.Error.

base64.standard_b64encode(s)
Encode bytes-like object s using the standard Base64 alphabet and return the encoded bytes.

base64.standard_b64decode(s)
Decode bytes-like object or ASCII string s using the standard Base64 alphabet and return the decoded bytes.

base64.urlsafe_b64encode(s)
Encode bytes-like object s using the URL- and filesystem-safe alphabet, which substitutes - instead of + and _ instead of / in the standard Base64 alphabet, and return the encoded bytes. The result can still contain =.

base64.urlsafe_b64decode(s)
Decode bytes-like object or ASCII string s using the URL- and filesystem-safe alphabet, which substitutes - instead of + and _ instead of / in the standard Base64 alphabet, and return the decoded bytes.

base64.b32encode(s)
Encode the bytes-like object s using Base32 and return the encoded bytes.

base64.b32decode(s, casefold=False, map01=None)
Decode the Base32 encoded bytes-like object or ASCII string s and return the decoded bytes. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. RFC 3548 allows for optional mapping of the digit 0 (zero) to the letter O (oh), and for optional mapping of the digit 1 (one) to either the letter I (eye) or letter L (el). The optional argument map01 when not None, specifies which letter the digit 1 should be mapped to (when map01 is not None, the digit 0 is always mapped to the letter O). For security purposes the default is None, so that 0 and 1 are not allowed in the input. A binascii.Error is raised if s is incorrectly padded or if there are non-alphabet characters present in the input.

base64.b16encode(s)
Encode the bytes-like object s using Base16 and return the encoded bytes.

base64.b16decode(s, casefold=False)
Decode the Base16 encoded bytes-like object or ASCII string s and return the decoded bytes. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. A binascii.Error is raised if s is incorrectly padded or if there are non-alphabet characters present in the input.

base64.a85encode(b, *, foldspaces=False, wrapcol=0, pad=False, adobe=False)
Encode the bytes-like object b using Ascii85 and return the encoded bytes. foldspaces is an optional flag that uses the special short sequence ‘y’ instead of 4 consecutive spaces (ASCII 0x20) as supported by ‘btoa’. This feature is not supported by the “standard” Ascii85 encoding. wrapcol controls whether the output should have newline (b'\n') characters added to it. If this is non-zero, each output line will be at most this many characters long. pad controls whether the input is padded to a multiple of 4 before encoding. Note that the btoa implementation always pads. adobe controls whether the encoded byte sequence is framed with <~ and ~>, which is used by the Adobe implementation.  New in version 3.4.

base64.a85decode(b, *, foldspaces=False, adobe=False, ignorechars=b' \t\n\r\v')
Decode the Ascii85 encoded bytes-like object or ASCII string b and return the decoded bytes. foldspaces is a flag that specifies whether the ‘y’ short sequence should be accepted as shorthand for 4 consecutive spaces (ASCII 0x20). This feature is not supported by the “standard” Ascii85 encoding. adobe controls whether the input sequence is in Adobe Ascii85 format (i.e. is framed with <~ and ~>). ignorechars should be a bytes-like object or ASCII string containing characters to ignore from the input. This should only contain whitespace characters, and by default contains all whitespace characters in ASCII.  New in version 3.4.

base64.b85encode(b, pad=False)
Encode the bytes-like object b using base85 (as used in e.g. git-style binary diffs) and return the encoded bytes. If pad is true, the input is padded with b'\0' so its length is a multiple of 4 bytes before encoding.  New in version 3.4.

base64.b85decode(b)
Decode the base85-encoded bytes-like object or ASCII string b and return the decoded bytes. Padding is implicitly removed, if necessary.  New in version 3.4.
 The legacy interface:
base64.decode(input, output)
Decode the contents of the binary input file and write the resulting binary data to the output file. input and output must be file objects. input will be read until input.readline() returns an empty bytes object.

base64.decodebytes(s)
Decode the bytes-like object s, which must contain one or more lines of base64 encoded data, and return the decoded bytes.  New in version 3.1.

base64.encode(input, output)
Encode the contents of the binary input file and write the resulting base64 encoded data to the output file. input and output must be file objects. input will be read until input.read() returns an empty bytes object. encode() inserts a newline character (b'\n') after every 76 bytes of the output, as well as ensuring that the output always ends with a newline, as per RFC 2045 (MIME).

base64.encodebytes(s)
Encode the bytes-like object s, which can contain arbitrary binary data, and return bytes containing the base64-encoded data, with newlines (b'\n') inserted after every 76 bytes of output, and ensuring that there is a trailing newline, as per RFC 2045 (MIME).  New in version 3.1.
 An example usage of the module: >>> import base64
>>> encoded = base64.b64encode(b'data to be encoded')
>>> encoded
b'ZGF0YSB0byBiZSBlbmNvZGVk'
>>> data = base64.b64decode(encoded)
>>> data
b'data to be encoded'
  See also
Module binascii

Support module containing ASCII-to-binary and binary-to-ASCII conversions.
RFC 1521 - MIME (Multipurpose Internet Mail Extensions) Part One: Mechanisms for Specifying and Describing the Format of Internet Message Bodies

Section 5.2, “Base64 Content-Transfer-Encoding,” provides the definition of the base64 encoding.


base64.a85decode(b, *, foldspaces=False, adobe=False, ignorechars=b' \t\n\r\v')
Decode the Ascii85 encoded bytes-like object or ASCII string b and return the decoded bytes. foldspaces is a flag that specifies whether the ‘y’ short sequence should be accepted as shorthand for 4 consecutive spaces (ASCII 0x20). This feature is not supported by the “standard” Ascii85 encoding. adobe controls whether the input sequence is in Adobe Ascii85 format (i.e. is framed with <~ and ~>). ignorechars should be a bytes-like object or ASCII string containing characters to ignore from the input. This should only contain whitespace characters, and by default contains all whitespace characters in ASCII.  New in version 3.4.


base64.a85encode(b, *, foldspaces=False, wrapcol=0, pad=False, adobe=False)
Encode the bytes-like object b using Ascii85 and return the encoded bytes. foldspaces is an optional flag that uses the special short sequence ‘y’ instead of 4 consecutive spaces (ASCII 0x20) as supported by ‘btoa’. This feature is not supported by the “standard” Ascii85 encoding. wrapcol controls whether the output should have newline (b'\n') characters added to it. If this is non-zero, each output line will be at most this many characters long. pad controls whether the input is padded to a multiple of 4 before encoding. Note that the btoa implementation always pads. adobe controls whether the encoded byte sequence is framed with <~ and ~>, which is used by the Adobe implementation.  New in version 3.4.


base64.b16decode(s, casefold=False)
Decode the Base16 encoded bytes-like object or ASCII string s and return the decoded bytes. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. A binascii.Error is raised if s is incorrectly padded or if there are non-alphabet characters present in the input.


base64.b16encode(s)
Encode the bytes-like object s using Base16 and return the encoded bytes.


base64.b32decode(s, casefold=False, map01=None)
Decode the Base32 encoded bytes-like object or ASCII string s and return the decoded bytes. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. RFC 3548 allows for optional mapping of the digit 0 (zero) to the letter O (oh), and for optional mapping of the digit 1 (one) to either the letter I (eye) or letter L (el). The optional argument map01 when not None, specifies which letter the digit 1 should be mapped to (when map01 is not None, the digit 0 is always mapped to the letter O). For security purposes the default is None, so that 0 and 1 are not allowed in the input. A binascii.Error is raised if s is incorrectly padded or if there are non-alphabet characters present in the input.


base64.b32encode(s)
Encode the bytes-like object s using Base32 and return the encoded bytes.


base64.b64decode(s, altchars=None, validate=False)
Decode the Base64 encoded bytes-like object or ASCII string s and return the decoded bytes. Optional altchars must be a bytes-like object or ASCII string of at least length 2 (additional characters are ignored) which specifies the alternative alphabet used instead of the + and / characters. A binascii.Error exception is raised if s is incorrectly padded. If validate is False (the default), characters that are neither in the normal base-64 alphabet nor the alternative alphabet are discarded prior to the padding check. If validate is True, these non-alphabet characters in the input result in a binascii.Error.


base64.b64encode(s, altchars=None)
Encode the bytes-like object s using Base64 and return the encoded bytes. Optional altchars must be a bytes-like object of at least length 2 (additional characters are ignored) which specifies an alternative alphabet for the + and / characters. This allows an application to e.g. generate URL or filesystem safe Base64 strings. The default is None, for which the standard Base64 alphabet is used.


base64.b85decode(b)
Decode the base85-encoded bytes-like object or ASCII string b and return the decoded bytes. Padding is implicitly removed, if necessary.  New in version 3.4.


base64.b85encode(b, pad=False)
Encode the bytes-like object b using base85 (as used in e.g. git-style binary diffs) and return the encoded bytes. If pad is true, the input is padded with b'\0' so its length is a multiple of 4 bytes before encoding.  New in version 3.4.


base64.decode(input, output)
Decode the contents of the binary input file and write the resulting binary data to the output file. input and output must be file objects. input will be read until input.readline() returns an empty bytes object.


base64.decodebytes(s)
Decode the bytes-like object s, which must contain one or more lines of base64 encoded data, and return the decoded bytes.  New in version 3.1.


base64.encode(input, output)
Encode the contents of the binary input file and write the resulting base64 encoded data to the output file. input and output must be file objects. input will be read until input.read() returns an empty bytes object. encode() inserts a newline character (b'\n') after every 76 bytes of the output, as well as ensuring that the output always ends with a newline, as per RFC 2045 (MIME).


base64.encodebytes(s)
Encode the bytes-like object s, which can contain arbitrary binary data, and return bytes containing the base64-encoded data, with newlines (b'\n') inserted after every 76 bytes of output, and ensuring that there is a trailing newline, as per RFC 2045 (MIME).  New in version 3.1.


base64.standard_b64decode(s)
Decode bytes-like object or ASCII string s using the standard Base64 alphabet and return the decoded bytes.


base64.standard_b64encode(s)
Encode bytes-like object s using the standard Base64 alphabet and return the encoded bytes.


base64.urlsafe_b64decode(s)
Decode bytes-like object or ASCII string s using the URL- and filesystem-safe alphabet, which substitutes - instead of + and _ instead of / in the standard Base64 alphabet, and return the decoded bytes.


base64.urlsafe_b64encode(s)
Encode bytes-like object s using the URL- and filesystem-safe alphabet, which substitutes - instead of + and _ instead of / in the standard Base64 alphabet, and return the encoded bytes. The result can still contain =.


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)


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)


bdb — Debugger framework Source code: Lib/bdb.py The bdb module handles basic debugger functions, like setting breakpoints or managing execution via the debugger. The following exception is defined:
exception bdb.BdbQuit
Exception raised by the Bdb class for quitting the debugger.
 The bdb module also defines two classes:
class bdb.Breakpoint(self, file, line, temporary=0, cond=None, funcname=None)
This class implements temporary breakpoints, ignore counts, disabling and (re-)enabling, and conditionals. Breakpoints are indexed by number through a list called bpbynumber and by (file, line) pairs through bplist. The former points to a single instance of class Breakpoint. The latter points to a list of such instances since there may be more than one breakpoint per line. When creating a breakpoint, its associated filename should be in canonical form. If a funcname is defined, a breakpoint hit will be counted when the first line of that function is executed. A conditional breakpoint always counts a hit. Breakpoint instances have the following methods:
deleteMe()
Delete the breakpoint from the list associated to a file/line. If it is the last breakpoint in that position, it also deletes the entry for the file/line.

enable()
Mark the breakpoint as enabled.

disable()
Mark the breakpoint as disabled.

bpformat()
Return a string with all the information about the breakpoint, nicely formatted:  The breakpoint number. If it is temporary or not. Its file,line position. The condition that causes a break. If it must be ignored the next N times. The breakpoint hit count.   New in version 3.2.

bpprint(out=None)
Print the output of bpformat() to the file out, or if it is None, to standard output.

class bdb.Bdb(skip=None)
The Bdb class acts as a generic Python debugger base class. This class takes care of the details of the trace facility; a derived class should implement user interaction. The standard debugger class (pdb.Pdb) is an example. The skip argument, if given, must be an iterable of glob-style module name patterns. The debugger will not step into frames that originate in a module that matches one of these patterns. Whether a frame is considered to originate in a certain module is determined by the __name__ in the frame globals.  New in version 3.1: The skip argument.  The following methods of Bdb normally don’t need to be overridden.
canonic(filename)
Auxiliary method for getting a filename in a canonical form, that is, as a case-normalized (on case-insensitive filesystems) absolute path, stripped of surrounding angle brackets.

reset()
Set the botframe, stopframe, returnframe and quitting attributes with values ready to start debugging.

trace_dispatch(frame, event, arg)
This function is installed as the trace function of debugged frames. Its return value is the new trace function (in most cases, that is, itself). The default implementation decides how to dispatch a frame, depending on the type of event (passed as a string) that is about to be executed. event can be one of the following:
"line": A new line of code is going to be executed.
"call": A function is about to be called, or another code block entered.
"return": A function or other code block is about to return.
"exception": An exception has occurred.
"c_call": A C function is about to be called.
"c_return": A C function has returned.
"c_exception": A C function has raised an exception.  For the Python events, specialized functions (see below) are called. For the C events, no action is taken. The arg parameter depends on the previous event. See the documentation for sys.settrace() for more information on the trace function. For more information on code and frame objects, refer to The standard type hierarchy.

dispatch_line(frame)
If the debugger should stop on the current line, invoke the user_line() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_line()). Return a reference to the trace_dispatch() method for further tracing in that scope.

dispatch_call(frame, arg)
If the debugger should stop on this function call, invoke the user_call() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_call()). Return a reference to the trace_dispatch() method for further tracing in that scope.

dispatch_return(frame, arg)
If the debugger should stop on this function return, invoke the user_return() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_return()). Return a reference to the trace_dispatch() method for further tracing in that scope.

dispatch_exception(frame, arg)
If the debugger should stop at this exception, invokes the user_exception() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_exception()). Return a reference to the trace_dispatch() method for further tracing in that scope.
 Normally derived classes don’t override the following methods, but they may if they want to redefine the definition of stopping and breakpoints.
stop_here(frame)
This method checks if the frame is somewhere below botframe in the call stack. botframe is the frame in which debugging started.

break_here(frame)
This method checks if there is a breakpoint in the filename and line belonging to frame or, at least, in the current function. If the breakpoint is a temporary one, this method deletes it.

break_anywhere(frame)
This method checks if there is a breakpoint in the filename of the current frame.
 Derived classes should override these methods to gain control over debugger operation.
user_call(frame, argument_list)
This method is called from dispatch_call() when there is the possibility that a break might be necessary anywhere inside the called function.

user_line(frame)
This method is called from dispatch_line() when either stop_here() or break_here() yields True.

user_return(frame, return_value)
This method is called from dispatch_return() when stop_here() yields True.

user_exception(frame, exc_info)
This method is called from dispatch_exception() when stop_here() yields True.

do_clear(arg)
Handle how a breakpoint must be removed when it is a temporary one. This method must be implemented by derived classes.
 Derived classes and clients can call the following methods to affect the stepping state.
set_step()
Stop after one line of code.

set_next(frame)
Stop on the next line in or below the given frame.

set_return(frame)
Stop when returning from the given frame.

set_until(frame)
Stop when the line with the line no greater than the current one is reached or when returning from current frame.

set_trace([frame])
Start debugging from frame. If frame is not specified, debugging starts from caller’s frame.

set_continue()
Stop only at breakpoints or when finished. If there are no breakpoints, set the system trace function to None.

set_quit()
Set the quitting attribute to True. This raises BdbQuit in the next call to one of the dispatch_*() methods.
 Derived classes and clients can call the following methods to manipulate breakpoints. These methods return a string containing an error message if something went wrong, or None if all is well.
set_break(filename, lineno, temporary=0, cond, funcname)
Set a new breakpoint. If the lineno line doesn’t exist for the filename passed as argument, return an error message. The filename should be in canonical form, as described in the canonic() method.

clear_break(filename, lineno)
Delete the breakpoints in filename and lineno. If none were set, an error message is returned.

clear_bpbynumber(arg)
Delete the breakpoint which has the index arg in the Breakpoint.bpbynumber. If arg is not numeric or out of range, return an error message.

clear_all_file_breaks(filename)
Delete all breakpoints in filename. If none were set, an error message is returned.

clear_all_breaks()
Delete all existing breakpoints.

get_bpbynumber(arg)
Return a breakpoint specified by the given number. If arg is a string, it will be converted to a number. If arg is a non-numeric string, if the given breakpoint never existed or has been deleted, a ValueError is raised.  New in version 3.2.

get_break(filename, lineno)
Check if there is a breakpoint for lineno of filename.

get_breaks(filename, lineno)
Return all breakpoints for lineno in filename, or an empty list if none are set.

get_file_breaks(filename)
Return all breakpoints in filename, or an empty list if none are set.

get_all_breaks()
Return all breakpoints that are set.
 Derived classes and clients can call the following methods to get a data structure representing a stack trace.
get_stack(f, t)
Get a list of records for a frame and all higher (calling) and lower frames, and the size of the higher part.

format_stack_entry(frame_lineno, lprefix=': ')
Return a string with information about a stack entry, identified by a (frame, lineno) tuple:  The canonical form of the filename which contains the frame. The function name, or "<lambda>". The input arguments. The return value. The line of code (if it exists).
 The following two methods can be called by clients to use a debugger to debug a statement, given as a string.
run(cmd, globals=None, locals=None)
Debug a statement executed via the exec() function. globals defaults to __main__.__dict__, locals defaults to globals.

runeval(expr, globals=None, locals=None)
Debug an expression executed via the eval() function. globals and locals have the same meaning as in run().

runctx(cmd, globals, locals)
For backwards compatibility. Calls the run() method.

runcall(func, /, *args, **kwds)
Debug a single function call, and return its result.

 Finally, the module defines the following functions:
bdb.checkfuncname(b, frame)
Check whether we should break here, depending on the way the breakpoint b was set. If it was set via line number, it checks if b.line is the same as the one in the frame also passed as argument. If the breakpoint was set via function name, we have to check we are in the right frame (the right function) and if we are in its first executable line.

bdb.effective(file, line, frame)
Determine if there is an effective (active) breakpoint at this line of code. Return a tuple of the breakpoint and a boolean that indicates if it is ok to delete a temporary breakpoint. Return (None, None) if there is no matching breakpoint.

bdb.set_trace()
Start debugging with a Bdb instance from caller’s frame.


class bdb.Bdb(skip=None)
The Bdb class acts as a generic Python debugger base class. This class takes care of the details of the trace facility; a derived class should implement user interaction. The standard debugger class (pdb.Pdb) is an example. The skip argument, if given, must be an iterable of glob-style module name patterns. The debugger will not step into frames that originate in a module that matches one of these patterns. Whether a frame is considered to originate in a certain module is determined by the __name__ in the frame globals.  New in version 3.1: The skip argument.  The following methods of Bdb normally don’t need to be overridden.
canonic(filename)
Auxiliary method for getting a filename in a canonical form, that is, as a case-normalized (on case-insensitive filesystems) absolute path, stripped of surrounding angle brackets.

reset()
Set the botframe, stopframe, returnframe and quitting attributes with values ready to start debugging.

trace_dispatch(frame, event, arg)
This function is installed as the trace function of debugged frames. Its return value is the new trace function (in most cases, that is, itself). The default implementation decides how to dispatch a frame, depending on the type of event (passed as a string) that is about to be executed. event can be one of the following:
"line": A new line of code is going to be executed.
"call": A function is about to be called, or another code block entered.
"return": A function or other code block is about to return.
"exception": An exception has occurred.
"c_call": A C function is about to be called.
"c_return": A C function has returned.
"c_exception": A C function has raised an exception.  For the Python events, specialized functions (see below) are called. For the C events, no action is taken. The arg parameter depends on the previous event. See the documentation for sys.settrace() for more information on the trace function. For more information on code and frame objects, refer to The standard type hierarchy.

dispatch_line(frame)
If the debugger should stop on the current line, invoke the user_line() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_line()). Return a reference to the trace_dispatch() method for further tracing in that scope.

dispatch_call(frame, arg)
If the debugger should stop on this function call, invoke the user_call() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_call()). Return a reference to the trace_dispatch() method for further tracing in that scope.

dispatch_return(frame, arg)
If the debugger should stop on this function return, invoke the user_return() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_return()). Return a reference to the trace_dispatch() method for further tracing in that scope.

dispatch_exception(frame, arg)
If the debugger should stop at this exception, invokes the user_exception() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_exception()). Return a reference to the trace_dispatch() method for further tracing in that scope.
 Normally derived classes don’t override the following methods, but they may if they want to redefine the definition of stopping and breakpoints.
stop_here(frame)
This method checks if the frame is somewhere below botframe in the call stack. botframe is the frame in which debugging started.

break_here(frame)
This method checks if there is a breakpoint in the filename and line belonging to frame or, at least, in the current function. If the breakpoint is a temporary one, this method deletes it.

break_anywhere(frame)
This method checks if there is a breakpoint in the filename of the current frame.
 Derived classes should override these methods to gain control over debugger operation.
user_call(frame, argument_list)
This method is called from dispatch_call() when there is the possibility that a break might be necessary anywhere inside the called function.

user_line(frame)
This method is called from dispatch_line() when either stop_here() or break_here() yields True.

user_return(frame, return_value)
This method is called from dispatch_return() when stop_here() yields True.

user_exception(frame, exc_info)
This method is called from dispatch_exception() when stop_here() yields True.

do_clear(arg)
Handle how a breakpoint must be removed when it is a temporary one. This method must be implemented by derived classes.
 Derived classes and clients can call the following methods to affect the stepping state.
set_step()
Stop after one line of code.

set_next(frame)
Stop on the next line in or below the given frame.

set_return(frame)
Stop when returning from the given frame.

set_until(frame)
Stop when the line with the line no greater than the current one is reached or when returning from current frame.

set_trace([frame])
Start debugging from frame. If frame is not specified, debugging starts from caller’s frame.

set_continue()
Stop only at breakpoints or when finished. If there are no breakpoints, set the system trace function to None.

set_quit()
Set the quitting attribute to True. This raises BdbQuit in the next call to one of the dispatch_*() methods.
 Derived classes and clients can call the following methods to manipulate breakpoints. These methods return a string containing an error message if something went wrong, or None if all is well.
set_break(filename, lineno, temporary=0, cond, funcname)
Set a new breakpoint. If the lineno line doesn’t exist for the filename passed as argument, return an error message. The filename should be in canonical form, as described in the canonic() method.

clear_break(filename, lineno)
Delete the breakpoints in filename and lineno. If none were set, an error message is returned.

clear_bpbynumber(arg)
Delete the breakpoint which has the index arg in the Breakpoint.bpbynumber. If arg is not numeric or out of range, return an error message.

clear_all_file_breaks(filename)
Delete all breakpoints in filename. If none were set, an error message is returned.

clear_all_breaks()
Delete all existing breakpoints.

get_bpbynumber(arg)
Return a breakpoint specified by the given number. If arg is a string, it will be converted to a number. If arg is a non-numeric string, if the given breakpoint never existed or has been deleted, a ValueError is raised.  New in version 3.2.

get_break(filename, lineno)
Check if there is a breakpoint for lineno of filename.

get_breaks(filename, lineno)
Return all breakpoints for lineno in filename, or an empty list if none are set.

get_file_breaks(filename)
Return all breakpoints in filename, or an empty list if none are set.

get_all_breaks()
Return all breakpoints that are set.
 Derived classes and clients can call the following methods to get a data structure representing a stack trace.
get_stack(f, t)
Get a list of records for a frame and all higher (calling) and lower frames, and the size of the higher part.

format_stack_entry(frame_lineno, lprefix=': ')
Return a string with information about a stack entry, identified by a (frame, lineno) tuple:  The canonical form of the filename which contains the frame. The function name, or "<lambda>". The input arguments. The return value. The line of code (if it exists).
 The following two methods can be called by clients to use a debugger to debug a statement, given as a string.
run(cmd, globals=None, locals=None)
Debug a statement executed via the exec() function. globals defaults to __main__.__dict__, locals defaults to globals.

runeval(expr, globals=None, locals=None)
Debug an expression executed via the eval() function. globals and locals have the same meaning as in run().

runctx(cmd, globals, locals)
For backwards compatibility. Calls the run() method.

runcall(func, /, *args, **kwds)
Debug a single function call, and return its result.


break_anywhere(frame)
This method checks if there is a breakpoint in the filename of the current frame.


break_here(frame)
This method checks if there is a breakpoint in the filename and line belonging to frame or, at least, in the current function. If the breakpoint is a temporary one, this method deletes it.


canonic(filename)
Auxiliary method for getting a filename in a canonical form, that is, as a case-normalized (on case-insensitive filesystems) absolute path, stripped of surrounding angle brackets.


clear_all_breaks()
Delete all existing breakpoints.


clear_all_file_breaks(filename)
Delete all breakpoints in filename. If none were set, an error message is returned.


clear_bpbynumber(arg)
Delete the breakpoint which has the index arg in the Breakpoint.bpbynumber. If arg is not numeric or out of range, return an error message.


clear_break(filename, lineno)
Delete the breakpoints in filename and lineno. If none were set, an error message is returned.


dispatch_call(frame, arg)
If the debugger should stop on this function call, invoke the user_call() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_call()). Return a reference to the trace_dispatch() method for further tracing in that scope.


dispatch_exception(frame, arg)
If the debugger should stop at this exception, invokes the user_exception() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_exception()). Return a reference to the trace_dispatch() method for further tracing in that scope.


dispatch_line(frame)
If the debugger should stop on the current line, invoke the user_line() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_line()). Return a reference to the trace_dispatch() method for further tracing in that scope.


dispatch_return(frame, arg)
If the debugger should stop on this function return, invoke the user_return() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_return()). Return a reference to the trace_dispatch() method for further tracing in that scope.


do_clear(arg)
Handle how a breakpoint must be removed when it is a temporary one. This method must be implemented by derived classes.


format_stack_entry(frame_lineno, lprefix=': ')
Return a string with information about a stack entry, identified by a (frame, lineno) tuple:  The canonical form of the filename which contains the frame. The function name, or "<lambda>". The input arguments. The return value. The line of code (if it exists).


get_all_breaks()
Return all breakpoints that are set.


get_bpbynumber(arg)
Return a breakpoint specified by the given number. If arg is a string, it will be converted to a number. If arg is a non-numeric string, if the given breakpoint never existed or has been deleted, a ValueError is raised.  New in version 3.2.


get_break(filename, lineno)
Check if there is a breakpoint for lineno of filename.


get_breaks(filename, lineno)
Return all breakpoints for lineno in filename, or an empty list if none are set.


get_file_breaks(filename)
Return all breakpoints in filename, or an empty list if none are set.


get_stack(f, t)
Get a list of records for a frame and all higher (calling) and lower frames, and the size of the higher part.


reset()
Set the botframe, stopframe, returnframe and quitting attributes with values ready to start debugging.


run(cmd, globals=None, locals=None)
Debug a statement executed via the exec() function. globals defaults to __main__.__dict__, locals defaults to globals.


runcall(func, /, *args, **kwds)
Debug a single function call, and return its result.


runctx(cmd, globals, locals)
For backwards compatibility. Calls the run() method.


runeval(expr, globals=None, locals=None)
Debug an expression executed via the eval() function. globals and locals have the same meaning as in run().


set_break(filename, lineno, temporary=0, cond, funcname)
Set a new breakpoint. If the lineno line doesn’t exist for the filename passed as argument, return an error message. The filename should be in canonical form, as described in the canonic() method.


set_continue()
Stop only at breakpoints or when finished. If there are no breakpoints, set the system trace function to None.


set_next(frame)
Stop on the next line in or below the given frame.


set_quit()
Set the quitting attribute to True. This raises BdbQuit in the next call to one of the dispatch_*() methods.


set_return(frame)
Stop when returning from the given frame.


set_trace([frame])
Start debugging from frame. If frame is not specified, debugging starts from caller’s frame.


set_until(frame)
Stop when the line with the line no greater than the current one is reached or when returning from current frame.


stop_here(frame)
This method checks if the frame is somewhere below botframe in the call stack. botframe is the frame in which debugging started.


trace_dispatch(frame, event, arg)
This function is installed as the trace function of debugged frames. Its return value is the new trace function (in most cases, that is, itself). The default implementation decides how to dispatch a frame, depending on the type of event (passed as a string) that is about to be executed. event can be one of the following:
"line": A new line of code is going to be executed.
"call": A function is about to be called, or another code block entered.
"return": A function or other code block is about to return.
"exception": An exception has occurred.
"c_call": A C function is about to be called.
"c_return": A C function has returned.
"c_exception": A C function has raised an exception.  For the Python events, specialized functions (see below) are called. For the C events, no action is taken. The arg parameter depends on the previous event. See the documentation for sys.settrace() for more information on the trace function. For more information on code and frame objects, refer to The standard type hierarchy.


user_call(frame, argument_list)
This method is called from dispatch_call() when there is the possibility that a break might be necessary anywhere inside the called function.


user_exception(frame, exc_info)
This method is called from dispatch_exception() when stop_here() yields True.


user_line(frame)
This method is called from dispatch_line() when either stop_here() or break_here() yields True.


user_return(frame, return_value)
This method is called from dispatch_return() when stop_here() yields True.


exception bdb.BdbQuit
Exception raised by the Bdb class for quitting the debugger.


class bdb.Breakpoint(self, file, line, temporary=0, cond=None, funcname=None)
This class implements temporary breakpoints, ignore counts, disabling and (re-)enabling, and conditionals. Breakpoints are indexed by number through a list called bpbynumber and by (file, line) pairs through bplist. The former points to a single instance of class Breakpoint. The latter points to a list of such instances since there may be more than one breakpoint per line. When creating a breakpoint, its associated filename should be in canonical form. If a funcname is defined, a breakpoint hit will be counted when the first line of that function is executed. A conditional breakpoint always counts a hit. Breakpoint instances have the following methods:
deleteMe()
Delete the breakpoint from the list associated to a file/line. If it is the last breakpoint in that position, it also deletes the entry for the file/line.

enable()
Mark the breakpoint as enabled.

disable()
Mark the breakpoint as disabled.

bpformat()
Return a string with all the information about the breakpoint, nicely formatted:  The breakpoint number. If it is temporary or not. Its file,line position. The condition that causes a break. If it must be ignored the next N times. The breakpoint hit count.   New in version 3.2.

bpprint(out=None)
Print the output of bpformat() to the file out, or if it is None, to standard output.


bpformat()
Return a string with all the information about the breakpoint, nicely formatted:  The breakpoint number. If it is temporary or not. Its file,line position. The condition that causes a break. If it must be ignored the next N times. The breakpoint hit count.   New in version 3.2.


bpprint(out=None)
Print the output of bpformat() to the file out, or if it is None, to standard output.


deleteMe()
Delete the breakpoint from the list associated to a file/line. If it is the last breakpoint in that position, it also deletes the entry for the file/line.


disable()
Mark the breakpoint as disabled.


enable()
Mark the breakpoint as enabled.


bdb.checkfuncname(b, frame)
Check whether we should break here, depending on the way the breakpoint b was set. If it was set via line number, it checks if b.line is the same as the one in the frame also passed as argument. If the breakpoint was set via function name, we have to check we are in the right frame (the right function) and if we are in its first executable line.


bdb.effective(file, line, frame)
Determine if there is an effective (active) breakpoint at this line of code. Return a tuple of the breakpoint and a boolean that indicates if it is ok to delete a temporary breakpoint. Return (None, None) if there is no matching breakpoint.


bdb.set_trace()
Start debugging with a Bdb instance from caller’s frame.


bin(x)
Convert an integer number to a binary string prefixed with “0b”. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer. Some examples: >>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
 If prefix “0b” is desired or not, you can use either of the following ways. >>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
 See also format() for more information.


binascii — Convert between binary and ASCII The binascii module contains a number of methods to convert between binary and various ASCII-encoded binary representations. Normally, you will not use these functions directly but use wrapper modules like uu, base64, or binhex instead. The binascii module contains low-level functions written in C for greater speed that are used by the higher-level modules.  Note a2b_* functions accept Unicode strings containing only ASCII characters. Other functions only accept bytes-like objects (such as bytes, bytearray and other objects that support the buffer protocol).  Changed in version 3.3: ASCII-only unicode strings are now accepted by the a2b_* functions.   The binascii module defines the following functions:
binascii.a2b_uu(string)
Convert a single line of uuencoded data back to binary and return the binary data. Lines normally contain 45 (binary) bytes, except for the last line. Line data may be followed by whitespace.

binascii.b2a_uu(data, *, backtick=False)
Convert binary data to a line of ASCII characters, the return value is the converted line, including a newline char. The length of data should be at most 45. If backtick is true, zeros are represented by '`' instead of spaces.  Changed in version 3.7: Added the backtick parameter.

binascii.a2b_base64(string)
Convert a block of base64 data back to binary and return the binary data. More than one line may be passed at a time.

binascii.b2a_base64(data, *, newline=True)
Convert binary data to a line of ASCII characters in base64 coding. The return value is the converted line, including a newline char if newline is true. The output of this function conforms to RFC 3548.  Changed in version 3.6: Added the newline parameter.

binascii.a2b_qp(data, header=False)
Convert a block of quoted-printable data back to binary and return the binary data. More than one line may be passed at a time. If the optional argument header is present and true, underscores will be decoded as spaces.

binascii.b2a_qp(data, quotetabs=False, istext=True, header=False)
Convert binary data to a line(s) of ASCII characters in quoted-printable encoding. The return value is the converted line(s). If the optional argument quotetabs is present and true, all tabs and spaces will be encoded. If the optional argument istext is present and true, newlines are not encoded but trailing whitespace will be encoded. If the optional argument header is present and true, spaces will be encoded as underscores per RFC 1522. If the optional argument header is present and false, newline characters will be encoded as well; otherwise linefeed conversion might corrupt the binary data stream.

binascii.a2b_hqx(string)
Convert binhex4 formatted ASCII data to binary, without doing RLE-decompression. The string should contain a complete number of binary bytes, or (in case of the last portion of the binhex4 data) have the remaining bits zero.  Deprecated since version 3.9.

binascii.rledecode_hqx(data)
Perform RLE-decompression on the data, as per the binhex4 standard. The algorithm uses 0x90 after a byte as a repeat indicator, followed by a count. A count of 0 specifies a byte value of 0x90. The routine returns the decompressed data, unless data input data ends in an orphaned repeat indicator, in which case the Incomplete exception is raised.  Changed in version 3.2: Accept only bytestring or bytearray objects as input.   Deprecated since version 3.9.

binascii.rlecode_hqx(data)
Perform binhex4 style RLE-compression on data and return the result.  Deprecated since version 3.9.

binascii.b2a_hqx(data)
Perform hexbin4 binary-to-ASCII translation and return the resulting string. The argument should already be RLE-coded, and have a length divisible by 3 (except possibly the last fragment).  Deprecated since version 3.9.

binascii.crc_hqx(data, value)
Compute a 16-bit CRC value of data, starting with value as the initial CRC, and return the result. This uses the CRC-CCITT polynomial x16 + x12 + x5 + 1, often represented as 0x1021. This CRC is used in the binhex4 format.

binascii.crc32(data[, value])
Compute CRC-32, the 32-bit checksum of data, starting with an initial CRC of value. The default initial CRC is zero. The algorithm is consistent with the ZIP file checksum. Since the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm. Use as follows: print(binascii.crc32(b"hello world"))
# Or, in two pieces:
crc = binascii.crc32(b"hello")
crc = binascii.crc32(b" world", crc)
print('crc32 = {:#010x}'.format(crc))
  Changed in version 3.0: The result is always unsigned. To generate the same numeric value across all Python versions and platforms, use crc32(data) & 0xffffffff.

binascii.b2a_hex(data[, sep[, bytes_per_sep=1]])
binascii.hexlify(data[, sep[, bytes_per_sep=1]])
Return the hexadecimal representation of the binary data. Every byte of data is converted into the corresponding 2-digit hex representation. The returned bytes object is therefore twice as long as the length of data. Similar functionality (but returning a text string) is also conveniently accessible using the bytes.hex() method. If sep is specified, it must be a single character str or bytes object. It will be inserted in the output after every bytes_per_sep input bytes. Separator placement is counted from the right end of the output by default, if you wish to count from the left, supply a negative bytes_per_sep value. >>> import binascii
>>> binascii.b2a_hex(b'\xb9\x01\xef')
b'b901ef'
>>> binascii.hexlify(b'\xb9\x01\xef', '-')
b'b9-01-ef'
>>> binascii.b2a_hex(b'\xb9\x01\xef', b'_', 2)
b'b9_01ef'
>>> binascii.b2a_hex(b'\xb9\x01\xef', b' ', -2)
b'b901 ef'
  Changed in version 3.8: The sep and bytes_per_sep parameters were added.

binascii.a2b_hex(hexstr)
binascii.unhexlify(hexstr)
Return the binary data represented by the hexadecimal string hexstr. This function is the inverse of b2a_hex(). hexstr must contain an even number of hexadecimal digits (which can be upper or lower case), otherwise an Error exception is raised. Similar functionality (accepting only text string arguments, but more liberal towards whitespace) is also accessible using the bytes.fromhex() class method.

exception binascii.Error
Exception raised on errors. These are usually programming errors.

exception binascii.Incomplete
Exception raised on incomplete data. These are usually not programming errors, but may be handled by reading a little more data and trying again.
  See also
Module base64

Support for RFC compliant base64-style encoding in base 16, 32, 64, and 85.
Module binhex

Support for the binhex format used on the Macintosh.
Module uu

Support for UU encoding used on Unix.
Module quopri

Support for quoted-printable encoding used in MIME email messages.


binascii.a2b_base64(string)
Convert a block of base64 data back to binary and return the binary data. More than one line may be passed at a time.


binascii.a2b_hex(hexstr)
binascii.unhexlify(hexstr)
Return the binary data represented by the hexadecimal string hexstr. This function is the inverse of b2a_hex(). hexstr must contain an even number of hexadecimal digits (which can be upper or lower case), otherwise an Error exception is raised. Similar functionality (accepting only text string arguments, but more liberal towards whitespace) is also accessible using the bytes.fromhex() class method.


binascii.a2b_hqx(string)
Convert binhex4 formatted ASCII data to binary, without doing RLE-decompression. The string should contain a complete number of binary bytes, or (in case of the last portion of the binhex4 data) have the remaining bits zero.  Deprecated since version 3.9.


binascii.a2b_qp(data, header=False)
Convert a block of quoted-printable data back to binary and return the binary data. More than one line may be passed at a time. If the optional argument header is present and true, underscores will be decoded as spaces.


binascii.a2b_uu(string)
Convert a single line of uuencoded data back to binary and return the binary data. Lines normally contain 45 (binary) bytes, except for the last line. Line data may be followed by whitespace.


binascii.b2a_base64(data, *, newline=True)
Convert binary data to a line of ASCII characters in base64 coding. The return value is the converted line, including a newline char if newline is true. The output of this function conforms to RFC 3548.  Changed in version 3.6: Added the newline parameter.


binascii.b2a_hex(data[, sep[, bytes_per_sep=1]])
binascii.hexlify(data[, sep[, bytes_per_sep=1]])
Return the hexadecimal representation of the binary data. Every byte of data is converted into the corresponding 2-digit hex representation. The returned bytes object is therefore twice as long as the length of data. Similar functionality (but returning a text string) is also conveniently accessible using the bytes.hex() method. If sep is specified, it must be a single character str or bytes object. It will be inserted in the output after every bytes_per_sep input bytes. Separator placement is counted from the right end of the output by default, if you wish to count from the left, supply a negative bytes_per_sep value. >>> import binascii
>>> binascii.b2a_hex(b'\xb9\x01\xef')
b'b901ef'
>>> binascii.hexlify(b'\xb9\x01\xef', '-')
b'b9-01-ef'
>>> binascii.b2a_hex(b'\xb9\x01\xef', b'_', 2)
b'b9_01ef'
>>> binascii.b2a_hex(b'\xb9\x01\xef', b' ', -2)
b'b901 ef'
  Changed in version 3.8: The sep and bytes_per_sep parameters were added.


binascii.b2a_hqx(data)
Perform hexbin4 binary-to-ASCII translation and return the resulting string. The argument should already be RLE-coded, and have a length divisible by 3 (except possibly the last fragment).  Deprecated since version 3.9.


binascii.b2a_qp(data, quotetabs=False, istext=True, header=False)
Convert binary data to a line(s) of ASCII characters in quoted-printable encoding. The return value is the converted line(s). If the optional argument quotetabs is present and true, all tabs and spaces will be encoded. If the optional argument istext is present and true, newlines are not encoded but trailing whitespace will be encoded. If the optional argument header is present and true, spaces will be encoded as underscores per RFC 1522. If the optional argument header is present and false, newline characters will be encoded as well; otherwise linefeed conversion might corrupt the binary data stream.


binascii.b2a_uu(data, *, backtick=False)
Convert binary data to a line of ASCII characters, the return value is the converted line, including a newline char. The length of data should be at most 45. If backtick is true, zeros are represented by '`' instead of spaces.  Changed in version 3.7: Added the backtick parameter.


binascii.crc32(data[, value])
Compute CRC-32, the 32-bit checksum of data, starting with an initial CRC of value. The default initial CRC is zero. The algorithm is consistent with the ZIP file checksum. Since the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm. Use as follows: print(binascii.crc32(b"hello world"))
# Or, in two pieces:
crc = binascii.crc32(b"hello")
crc = binascii.crc32(b" world", crc)
print('crc32 = {:#010x}'.format(crc))
  Changed in version 3.0: The result is always unsigned. To generate the same numeric value across all Python versions and platforms, use crc32(data) & 0xffffffff.


binascii.crc_hqx(data, value)
Compute a 16-bit CRC value of data, starting with value as the initial CRC, and return the result. This uses the CRC-CCITT polynomial x16 + x12 + x5 + 1, often represented as 0x1021. This CRC is used in the binhex4 format.


exception binascii.Error
Exception raised on errors. These are usually programming errors.


exception binascii.Incomplete
Exception raised on incomplete data. These are usually not programming errors, but may be handled by reading a little more data and trying again.


binascii.rlecode_hqx(data)
Perform binhex4 style RLE-compression on data and return the result.  Deprecated since version 3.9.


binascii.rledecode_hqx(data)
Perform RLE-decompression on the data, as per the binhex4 standard. The algorithm uses 0x90 after a byte as a repeat indicator, followed by a count. A count of 0 specifies a byte value of 0x90. The routine returns the decompressed data, unless data input data ends in an orphaned repeat indicator, in which case the Incomplete exception is raised.  Changed in version 3.2: Accept only bytestring or bytearray objects as input.   Deprecated since version 3.9.


binhex — Encode and decode binhex4 files Source code: Lib/binhex.py  Deprecated since version 3.9.  This module encodes and decodes files in binhex4 format, a format allowing representation of Macintosh files in ASCII. Only the data fork is handled. The binhex module defines the following functions:
binhex.binhex(input, output)
Convert a binary file with filename input to binhex file output. The output parameter can either be a filename or a file-like object (any object supporting a write() and close() method).

binhex.hexbin(input, output)
Decode a binhex file input. input may be a filename or a file-like object supporting read() and close() methods. The resulting file is written to a file named output, unless the argument is None in which case the output filename is read from the binhex file.
 The following exception is also defined:
exception binhex.Error
Exception raised when something can’t be encoded using the binhex format (for example, a filename is too long to fit in the filename field), or when input is not properly encoded binhex data.
  See also
Module binascii

Support module containing ASCII-to-binary and binary-to-ASCII conversions.    Notes There is an alternative, more powerful interface to the coder and decoder, see the source for details. If you code or decode textfiles on non-Macintosh platforms they will still use the old Macintosh newline convention (carriage-return as end of line).


binhex.binhex(input, output)
Convert a binary file with filename input to binhex file output. The output parameter can either be a filename or a file-like object (any object supporting a write() and close() method).


exception binhex.Error
Exception raised when something can’t be encoded using the binhex format (for example, a filename is too long to fit in the filename field), or when input is not properly encoded binhex data.


binhex.hexbin(input, output)
Decode a binhex file input. input may be a filename or a file-like object supporting read() and close() methods. The resulting file is written to a file named output, unless the argument is None in which case the output filename is read from the binhex file.


bisect — Array bisection algorithm Source code: Lib/bisect.py This module provides support for maintaining a list in sorted order without having to sort the list after each insertion. For long lists of items with expensive comparison operations, this can be an improvement over the more common approach. The module is called bisect because it uses a basic bisection algorithm to do its work. The source code may be most useful as a working example of the algorithm (the boundary conditions are already right!). The following functions are provided:
bisect.bisect_left(a, x, lo=0, hi=len(a))
Locate the insertion point for x in a to maintain sorted order. The parameters lo and hi may be used to specify a subset of the list which should be considered; by default the entire list is used. If x is already present in a, the insertion point will be before (to the left of) any existing entries. The return value is suitable for use as the first parameter to list.insert() assuming that a is already sorted. The returned insertion point i partitions the array a into two halves so that all(val < x for val in a[lo:i]) for the left side and all(val >= x for val in a[i:hi]) for the right side.

bisect.bisect_right(a, x, lo=0, hi=len(a))
bisect.bisect(a, x, lo=0, hi=len(a))
Similar to bisect_left(), but returns an insertion point which comes after (to the right of) any existing entries of x in a. The returned insertion point i partitions the array a into two halves so that all(val <= x for val in a[lo:i]) for the left side and all(val > x for val in a[i:hi]) for the right side.

bisect.insort_left(a, x, lo=0, hi=len(a))
Insert x in a in sorted order. This is equivalent to a.insert(bisect.bisect_left(a, x, lo, hi), x) assuming that a is already sorted. Keep in mind that the O(log n) search is dominated by the slow O(n) insertion step.

bisect.insort_right(a, x, lo=0, hi=len(a))
bisect.insort(a, x, lo=0, hi=len(a))
Similar to insort_left(), but inserting x in a after any existing entries of x.
  See also SortedCollection recipe that uses bisect to build a full-featured collection class with straight-forward search methods and support for a key-function. The keys are precomputed to save unnecessary calls to the key function during searches.  Searching Sorted Lists The above bisect() functions are useful for finding insertion points but can be tricky or awkward to use for common searching tasks. The following five functions show how to transform them into the standard lookups for sorted lists: def index(a, x):
    'Locate the leftmost value exactly equal to x'
    i = bisect_left(a, x)
    if i != len(a) and a[i] == x:
        return i
    raise ValueError

def find_lt(a, x):
    'Find rightmost value less than x'
    i = bisect_left(a, x)
    if i:
        return a[i-1]
    raise ValueError

def find_le(a, x):
    'Find rightmost value less than or equal to x'
    i = bisect_right(a, x)
    if i:
        return a[i-1]
    raise ValueError

def find_gt(a, x):
    'Find leftmost value greater than x'
    i = bisect_right(a, x)
    if i != len(a):
        return a[i]
    raise ValueError

def find_ge(a, x):
    'Find leftmost item greater than or equal to x'
    i = bisect_left(a, x)
    if i != len(a):
        return a[i]
    raise ValueError
 Other Examples The bisect() function can be useful for numeric table lookups. This example uses bisect() to look up a letter grade for an exam score (say) based on a set of ordered numeric breakpoints: 90 and up is an ‘A’, 80 to 89 is a ‘B’, and so on: >>> def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
...     i = bisect(breakpoints, score)
...     return grades[i]
...
>>> [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]
['F', 'A', 'C', 'C', 'B', 'A', 'A']
 Unlike the sorted() function, it does not make sense for the bisect() functions to have key or reversed arguments because that would lead to an inefficient design (successive calls to bisect functions would not “remember” all of the previous key lookups). Instead, it is better to search a list of precomputed keys to find the index of the record in question: >>> data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)]
>>> data.sort(key=lambda r: r[1])
>>> keys = [r[1] for r in data]         # precomputed list of keys
>>> data[bisect_left(keys, 0)]
('black', 0)
>>> data[bisect_left(keys, 1)]
('blue', 1)
>>> data[bisect_left(keys, 5)]
('red', 5)
>>> data[bisect_left(keys, 8)]
('yellow', 8)


bisect.bisect_right(a, x, lo=0, hi=len(a))
bisect.bisect(a, x, lo=0, hi=len(a))
Similar to bisect_left(), but returns an insertion point which comes after (to the right of) any existing entries of x in a. The returned insertion point i partitions the array a into two halves so that all(val <= x for val in a[lo:i]) for the left side and all(val > x for val in a[i:hi]) for the right side.


bisect.bisect_left(a, x, lo=0, hi=len(a))
Locate the insertion point for x in a to maintain sorted order. The parameters lo and hi may be used to specify a subset of the list which should be considered; by default the entire list is used. If x is already present in a, the insertion point will be before (to the left of) any existing entries. The return value is suitable for use as the first parameter to list.insert() assuming that a is already sorted. The returned insertion point i partitions the array a into two halves so that all(val < x for val in a[lo:i]) for the left side and all(val >= x for val in a[i:hi]) for the right side.


bisect.insort_right(a, x, lo=0, hi=len(a))
bisect.insort(a, x, lo=0, hi=len(a))
Similar to insort_left(), but inserting x in a after any existing entries of x.


bisect.insort_left(a, x, lo=0, hi=len(a))
Insert x in a in sorted order. This is equivalent to a.insert(bisect.bisect_left(a, x, lo, hi), x) assuming that a is already sorted. Keep in mind that the O(log n) search is dominated by the slow O(n) insertion step.


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.


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.


class bool([x])
Return a Boolean value, i.e. one of True or False. x is converted using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise it returns True. The bool class is a subclass of int (see Numeric Types — int, float, complex). It cannot be subclassed further. Its only instances are False and True (see Boolean Values).  Changed in version 3.7: x is now a positional-only parameter.


breakpoint(*args, **kws)
This function drops you into the debugger at the call site. Specifically, it calls sys.breakpointhook(), passing args and kws straight through. By default, sys.breakpointhook() calls pdb.set_trace() expecting no arguments. In this case, it is purely a convenience function so you don’t have to explicitly import pdb or type as much code to enter the debugger. However, sys.breakpointhook() can be set to some other function and breakpoint() will automatically call that, allowing you to drop into the debugger of choice. Raises an auditing event builtins.breakpoint with argument breakpointhook.  New in version 3.7.


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 BufferError
Raised when a buffer related operation cannot be performed.


builtins — Built-in objects This module provides direct access to all ‘built-in’ identifiers of Python; for example, builtins.open is the full name for the built-in function open(). See Built-in Functions and Built-in Constants for documentation. This module is not normally accessed explicitly by most applications, but can be useful in modules that provide objects with the same name as a built-in value, but in which the built-in of that name is also needed. For example, in a module that wants to implement an open() function that wraps the built-in open(), this module can be used directly: import builtins

def open(path):
    f = builtins.open(path, 'r')
    return UpperCaser(f)

class UpperCaser:
    '''Wrapper around a file that converts output to upper-case.'''

    def __init__(self, f):
        self._f = f

    def read(self, count=-1):
        return self._f.read(count).upper()

    # ...
 As an implementation detail, most modules have the name __builtins__ made available as part of their globals. The value of __builtins__ is normally either this module or the value of this module’s __dict__ attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.


class bytearray([source[, encoding[, errors]]])
Return a new array of bytes. The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Bytearray Operations. The optional source parameter can be used to initialize the array in a few different ways:  If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode(). If it is an integer, the array will have that size and will be initialized with null bytes. If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array. If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.  Without an argument, an array of size 0 is created. See also Binary Sequence Types — bytes, bytearray, memoryview and Bytearray Objects.


class bytearray([source[, encoding[, errors]]])
There is no dedicated literal syntax for bytearray objects, instead they are always created by calling the constructor:  Creating an empty instance: bytearray()
 Creating a zero-filled instance with a given length: bytearray(10)
 From an iterable of integers: bytearray(range(20))
 Copying existing binary data via the buffer protocol: bytearray(b'Hi!')
  As bytearray objects are mutable, they support the mutable sequence operations in addition to the common bytes and bytearray operations described in Bytes and Bytearray Operations. Also see the bytearray built-in. Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal numbers are a commonly used format for describing binary data. Accordingly, the bytearray type has an additional class method to read data in that format:
classmethod fromhex(string)
This bytearray class method returns bytearray object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored. >>> bytearray.fromhex('2Ef0 F1f2  ')
bytearray(b'.\xf0\xf1\xf2')
  Changed in version 3.7: bytearray.fromhex() now skips all ASCII whitespace in the string, not just spaces.
 A reverse conversion function exists to transform a bytearray object into its hexadecimal representation.
hex([sep[, bytes_per_sep]])
Return a string object containing two hexadecimal digits for each byte in the instance. >>> bytearray(b'\xf0\xf1\xf2').hex()
'f0f1f2'
  New in version 3.5.   Changed in version 3.8: Similar to bytes.hex(), bytearray.hex() now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.


bytes.capitalize()
bytearray.capitalize()
Return a copy of the sequence with each byte interpreted as an ASCII character, and the first byte capitalized and the rest lowercased. Non-ASCII byte values are passed through unchanged.  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


bytes.center(width[, fillbyte])
bytearray.center(width[, fillbyte])
Return a copy of the object centered in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For bytes objects, the original sequence is returned if width is less than or equal to len(s).  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


bytes.count(sub[, start[, end]])
bytearray.count(sub[, start[, end]])
Return the number of non-overlapping occurrences of subsequence sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.  Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.


bytes.decode(encoding="utf-8", errors="strict")
bytearray.decode(encoding="utf-8", errors="strict")
Return a string decoded from the given bytes. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace' and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings. By default, the errors argument is not checked for best performances, but only used at the first decoding error. Enable the Python Development Mode, or use a debug build to check errors.  Note Passing the encoding argument to str allows decoding any bytes-like object directly, without needing to make a temporary bytes or bytearray object.   Changed in version 3.1: Added support for keyword arguments.   Changed in version 3.9: The errors is now checked in development mode and in debug mode.


bytes.endswith(suffix[, start[, end]])
bytearray.endswith(suffix[, start[, end]])
Return True if the binary data ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position. The suffix(es) to search for may be any bytes-like object.


bytes.expandtabs(tabsize=8)
bytearray.expandtabs(tabsize=8)
Return a copy of the sequence where all ASCII tab characters are replaced by one or more ASCII spaces, depending on the current column and the given tab size. Tab positions occur every tabsize bytes (default is 8, giving tab positions at columns 0, 8, 16 and so on). To expand the sequence, the current column is set to zero and the sequence is examined byte by byte. If the byte is an ASCII tab character (b'\t'), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied.) If the current byte is an ASCII newline (b'\n') or carriage return (b'\r'), it is copied and the current column is reset to zero. Any other byte value is copied unchanged and the current column is incremented by one regardless of how the byte value is represented when printed: >>> b'01\t012\t0123\t01234'.expandtabs()
b'01      012     0123    01234'
>>> b'01\t012\t0123\t01234'.expandtabs(4)
b'01  012 0123    01234'
  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


bytes.find(sub[, start[, end]])
bytearray.find(sub[, start[, end]])
Return the lowest index in the data where the subsequence sub is found, such that sub is contained in the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found. The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.  Note The find() method should be used only if you need to know the position of sub. To check if sub is a substring or not, use the in operator: >>> b'Py' in b'Python'
True
   Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.


classmethod fromhex(string)
This bytearray class method returns bytearray object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored. >>> bytearray.fromhex('2Ef0 F1f2  ')
bytearray(b'.\xf0\xf1\xf2')
  Changed in version 3.7: bytearray.fromhex() now skips all ASCII whitespace in the string, not just spaces.


hex([sep[, bytes_per_sep]])
Return a string object containing two hexadecimal digits for each byte in the instance. >>> bytearray(b'\xf0\xf1\xf2').hex()
'f0f1f2'
  New in version 3.5.   Changed in version 3.8: Similar to bytes.hex(), bytearray.hex() now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.


bytes.index(sub[, start[, end]])
bytearray.index(sub[, start[, end]])
Like find(), but raise ValueError when the subsequence is not found. The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.  Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.


bytes.isalnum()
bytearray.isalnum()
Return True if all bytes in the sequence are alphabetical ASCII characters or ASCII decimal digits and the sequence is not empty, False otherwise. Alphabetic ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'. ASCII decimal digits are those byte values in the sequence b'0123456789'. For example: >>> b'ABCabc1'.isalnum()
True
>>> b'ABC abc1'.isalnum()
False


bytes.isalpha()
bytearray.isalpha()
Return True if all bytes in the sequence are alphabetic ASCII characters and the sequence is not empty, False otherwise. Alphabetic ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'. For example: >>> b'ABCabc'.isalpha()
True
>>> b'ABCabc1'.isalpha()
False


bytes.isascii()
bytearray.isascii()
Return True if the sequence is empty or all bytes in the sequence are ASCII, False otherwise. ASCII bytes are in the range 0-0x7F.  New in version 3.7.


bytes.isdigit()
bytearray.isdigit()
Return True if all bytes in the sequence are ASCII decimal digits and the sequence is not empty, False otherwise. ASCII decimal digits are those byte values in the sequence b'0123456789'. For example: >>> b'1234'.isdigit()
True
>>> b'1.23'.isdigit()
False


bytes.islower()
bytearray.islower()
Return True if there is at least one lowercase ASCII character in the sequence and no uppercase ASCII characters, False otherwise. For example: >>> b'hello world'.islower()
True
>>> b'Hello world'.islower()
False
 Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.


bytes.isspace()
bytearray.isspace()
Return True if all bytes in the sequence are ASCII whitespace and the sequence is not empty, False otherwise. ASCII whitespace characters are those byte values in the sequence b' \t\n\r\x0b\f' (space, tab, newline, carriage return, vertical tab, form feed).


bytes.istitle()
bytearray.istitle()
Return True if the sequence is ASCII titlecase and the sequence is not empty, False otherwise. See bytes.title() for more details on the definition of “titlecase”. For example: >>> b'Hello World'.istitle()
True
>>> b'Hello world'.istitle()
False


bytes.isupper()
bytearray.isupper()
Return True if there is at least one uppercase alphabetic ASCII character in the sequence and no lowercase ASCII characters, False otherwise. For example: >>> b'HELLO WORLD'.isupper()
True
>>> b'Hello world'.isupper()
False
 Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.


bytes.join(iterable)
bytearray.join(iterable)
Return a bytes or bytearray object which is the concatenation of the binary data sequences in iterable. A TypeError will be raised if there are any values in iterable that are not bytes-like objects, including str objects. The separator between elements is the contents of the bytes or bytearray object providing this method.


bytes.ljust(width[, fillbyte])
bytearray.ljust(width[, fillbyte])
Return a copy of the object left justified in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For bytes objects, the original sequence is returned if width is less than or equal to len(s).  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


bytes.lower()
bytearray.lower()
Return a copy of the sequence with all the uppercase ASCII characters converted to their corresponding lowercase counterpart. For example: >>> b'Hello World'.lower()
b'hello world'
 Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


bytes.lstrip([chars])
bytearray.lstrip([chars])
Return a copy of the sequence with specified leading bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or None, the chars argument defaults to removing ASCII whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped: >>> b'   spacious   '.lstrip()
b'spacious   '
>>> b'www.example.com'.lstrip(b'cmowz.')
b'example.com'
 The binary sequence of byte values to remove may be any bytes-like object. See removeprefix() for a method that will remove a single prefix string rather than all of a set of characters. For example: >>> b'Arthur: three!'.lstrip(b'Arthur: ')
b'ee!'
>>> b'Arthur: three!'.removeprefix(b'Arthur: ')
b'three!'
  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


static bytes.maketrans(from, to)
static bytearray.maketrans(from, to)
This static method returns a translation table usable for bytes.translate() that will map each character in from into the character at the same position in to; from and to must both be bytes-like objects and have the same length.  New in version 3.1.


bytes.partition(sep)
bytearray.partition(sep)
Split the sequence at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing a copy of the original sequence, followed by two empty bytes or bytearray objects. The separator to search for may be any bytes-like object.


bytes.removeprefix(prefix, /)
bytearray.removeprefix(prefix, /)
If the binary data starts with the prefix string, return bytes[len(prefix):]. Otherwise, return a copy of the original binary data: >>> b'TestHook'.removeprefix(b'Test')
b'Hook'
>>> b'BaseTestCase'.removeprefix(b'Test')
b'BaseTestCase'
 The prefix may be any bytes-like object.  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.   New in version 3.9.


bytes.removesuffix(suffix, /)
bytearray.removesuffix(suffix, /)
If the binary data ends with the suffix string and that suffix is not empty, return bytes[:-len(suffix)]. Otherwise, return a copy of the original binary data: >>> b'MiscTests'.removesuffix(b'Tests')
b'Misc'
>>> b'TmpDirMixin'.removesuffix(b'Tests')
b'TmpDirMixin'
 The suffix may be any bytes-like object.  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.   New in version 3.9.


bytes.replace(old, new[, count])
bytearray.replace(old, new[, count])
Return a copy of the sequence with all occurrences of subsequence old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. The subsequence to search for and its replacement may be any bytes-like object.  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


bytes.rfind(sub[, start[, end]])
bytearray.rfind(sub[, start[, end]])
Return the highest index in the sequence where the subsequence sub is found, such that sub is contained within s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.  Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.


bytes.rindex(sub[, start[, end]])
bytearray.rindex(sub[, start[, end]])
Like rfind() but raises ValueError when the subsequence sub is not found. The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.  Changed in version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.


bytes.rjust(width[, fillbyte])
bytearray.rjust(width[, fillbyte])
Return a copy of the object right justified in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For bytes objects, the original sequence is returned if width is less than or equal to len(s).  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


bytes.rpartition(sep)
bytearray.rpartition(sep)
Split the sequence at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty bytes or bytearray objects, followed by a copy of the original sequence. The separator to search for may be any bytes-like object.


bytes.rsplit(sep=None, maxsplit=-1)
bytearray.rsplit(sep=None, maxsplit=-1)
Split the binary sequence into subsequences of the same type, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any subsequence consisting solely of ASCII whitespace is a separator. Except for splitting from the right, rsplit() behaves like split() which is described in detail below.


bytes.rstrip([chars])
bytearray.rstrip([chars])
Return a copy of the sequence with specified trailing bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or None, the chars argument defaults to removing ASCII whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped: >>> b'   spacious   '.rstrip()
b'   spacious'
>>> b'mississippi'.rstrip(b'ipz')
b'mississ'
 The binary sequence of byte values to remove may be any bytes-like object. See removesuffix() for a method that will remove a single suffix string rather than all of a set of characters. For example: >>> b'Monty Python'.rstrip(b' Python')
b'M'
>>> b'Monty Python'.removesuffix(b' Python')
b'Monty'
  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


bytes.split(sep=None, maxsplit=-1)
bytearray.split(sep=None, maxsplit=-1)
Split the binary sequence into subsequences of the same type, using sep as the delimiter string. If maxsplit is given and non-negative, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or is -1, then there is no limit on the number of splits (all possible splits are made). If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty subsequences (for example, b'1,,2'.split(b',') returns [b'1', b'', b'2']). The sep argument may consist of a multibyte sequence (for example, b'1<>2<>3'.split(b'<>') returns [b'1', b'2', b'3']). Splitting an empty sequence with a specified separator returns [b''] or [bytearray(b'')] depending on the type of object being split. The sep argument may be any bytes-like object. For example: >>> b'1,2,3'.split(b',')
[b'1', b'2', b'3']
>>> b'1,2,3'.split(b',', maxsplit=1)
[b'1', b'2,3']
>>> b'1,2,,3,'.split(b',')
[b'1', b'2', b'', b'3', b'']
 If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive ASCII whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the sequence has leading or trailing whitespace. Consequently, splitting an empty sequence or a sequence consisting solely of ASCII whitespace without a specified separator returns []. For example: >>> b'1 2 3'.split()
[b'1', b'2', b'3']
>>> b'1 2 3'.split(maxsplit=1)
[b'1', b'2 3']
>>> b'   1   2   3   '.split()
[b'1', b'2', b'3']


bytes.splitlines(keepends=False)
bytearray.splitlines(keepends=False)
Return a list of the lines in the binary sequence, breaking at ASCII line boundaries. This method uses the universal newlines approach to splitting lines. Line breaks are not included in the resulting list unless keepends is given and true. For example: >>> b'ab c\n\nde fg\rkl\r\n'.splitlines()
[b'ab c', b'', b'de fg', b'kl']
>>> b'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
[b'ab c\n', b'\n', b'de fg\r', b'kl\r\n']
 Unlike split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line: >>> b"".split(b'\n'), b"Two lines\n".split(b'\n')
([b''], [b'Two lines', b''])
>>> b"".splitlines(), b"One line\n".splitlines()
([], [b'One line'])


bytes.startswith(prefix[, start[, end]])
bytearray.startswith(prefix[, start[, end]])
Return True if the binary data starts with the specified prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position. The prefix(es) to search for may be any bytes-like object.


bytes.strip([chars])
bytearray.strip([chars])
Return a copy of the sequence with specified leading and trailing bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or None, the chars argument defaults to removing ASCII whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped: >>> b'   spacious   '.strip()
b'spacious'
>>> b'www.example.com'.strip(b'cmowz.')
b'example'
 The binary sequence of byte values to remove may be any bytes-like object.  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


bytes.swapcase()
bytearray.swapcase()
Return a copy of the sequence with all the lowercase ASCII characters converted to their corresponding uppercase counterpart and vice-versa. For example: >>> b'Hello World'.swapcase()
b'hELLO wORLD'
 Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. Unlike str.swapcase(), it is always the case that bin.swapcase().swapcase() == bin for the binary versions. Case conversions are symmetrical in ASCII, even though that is not generally true for arbitrary Unicode code points.  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


bytes.title()
bytearray.title()
Return a titlecased version of the binary sequence where words start with an uppercase ASCII character and the remaining characters are lowercase. Uncased byte values are left unmodified. For example: >>> b'Hello world'.title()
b'Hello World'
 Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. All other byte values are uncased. The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result: >>> b"they're bill's friends from the UK".title()
b"They'Re Bill'S Friends From The Uk"
 A workaround for apostrophes can be constructed using regular expressions: >>> import re
>>> def titlecase(s):
...     return re.sub(rb"[A-Za-z]+('[A-Za-z]+)?",
...                   lambda mo: mo.group(0)[0:1].upper() +
...                              mo.group(0)[1:].lower(),
...                   s)
...
>>> titlecase(b"they're bill's friends.")
b"They're Bill's Friends."
  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


bytes.translate(table, /, delete=b'')
bytearray.translate(table, /, delete=b'')
Return a copy of the bytes or bytearray object where all bytes occurring in the optional argument delete are removed, and the remaining bytes have been mapped through the given translation table, which must be a bytes object of length 256. You can use the bytes.maketrans() method to create a translation table. Set the table argument to None for translations that only delete characters: >>> b'read this short text'.translate(None, b'aeiou')
b'rd ths shrt txt'
  Changed in version 3.6: delete is now supported as a keyword argument.


bytes.upper()
bytearray.upper()
Return a copy of the sequence with all the lowercase ASCII characters converted to their corresponding uppercase counterpart. For example: >>> b'Hello World'.upper()
b'HELLO WORLD'
 Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


bytes.zfill(width)
bytearray.zfill(width)
Return a copy of the sequence left filled with ASCII b'0' digits to make a sequence of length width. A leading sign prefix (b'+'/ b'-') is handled by inserting the padding after the sign character rather than before. For bytes objects, the original sequence is returned if width is less than or equal to len(seq). For example: >>> b"42".zfill(5)
b'00042'
>>> b"-42".zfill(5)
b'-0042'
  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


class bytes([source[, encoding[, errors]]])
Firstly, the syntax for bytes literals is largely the same as that for string literals, except that a b prefix is added:  Single quotes: b'still allows embedded "double" quotes'
 Double quotes: b"still allows embedded 'single' quotes". Triple quoted: b'''3 single quotes''', b"""3 double quotes"""
  Only ASCII characters are permitted in bytes literals (regardless of the declared source code encoding). Any binary values over 127 must be entered into bytes literals using the appropriate escape sequence. As with string literals, bytes literals may also use a r prefix to disable processing of escape sequences. See String and Bytes literals for more about the various forms of bytes literal, including supported escape sequences. While bytes literals and representations are based on ASCII text, bytes objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that 0 <= x < 256 (attempts to violate this restriction will trigger ValueError). This is done deliberately to emphasise that while many binary formats include ASCII based elements and can be usefully manipulated with some text-oriented algorithms, this is not generally the case for arbitrary binary data (blindly applying text processing algorithms to binary data formats that are not ASCII compatible will usually lead to data corruption). In addition to the literal forms, bytes objects can be created in a number of other ways:  A zero-filled bytes object of a specified length: bytes(10)
 From an iterable of integers: bytes(range(20))
 Copying existing binary data via the buffer protocol: bytes(obj)
  Also see the bytes built-in. Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal numbers are a commonly used format for describing binary data. Accordingly, the bytes type has an additional class method to read data in that format:
classmethod fromhex(string)
This bytes class method returns a bytes object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored. >>> bytes.fromhex('2Ef0 F1f2  ')
b'.\xf0\xf1\xf2'
  Changed in version 3.7: bytes.fromhex() now skips all ASCII whitespace in the string, not just spaces.
 A reverse conversion function exists to transform a bytes object into its hexadecimal representation.
hex([sep[, bytes_per_sep]])
Return a string object containing two hexadecimal digits for each byte in the instance. >>> b'\xf0\xf1\xf2'.hex()
'f0f1f2'
 If you want to make the hex string easier to read, you can specify a single character separator sep parameter to include in the output. By default between each byte. A second optional bytes_per_sep parameter controls the spacing. Positive values calculate the separator position from the right, negative values from the left. >>> value = b'\xf0\xf1\xf2'
>>> value.hex('-')
'f0-f1-f2'
>>> value.hex('_', 2)
'f0_f1f2'
>>> b'UUDDLRLRAB'.hex(' ', -4)
'55554444 4c524c52 4142'
  New in version 3.5.   Changed in version 3.8: bytes.hex() now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.


class bytes([source[, encoding[, errors]]])
Return a new “bytes” object, which is an immutable sequence of integers in the range 0 <= x < 256. bytes is an immutable version of bytearray – it has the same non-mutating methods and the same indexing and slicing behavior. Accordingly, constructor arguments are interpreted as for bytearray(). Bytes objects can also be created with literals, see String and Bytes literals. See also Binary Sequence Types — bytes, bytearray, memoryview, Bytes Objects, and Bytes and Bytearray Operations.


bytes.capitalize()
bytearray.capitalize()
Return a copy of the sequence with each byte interpreted as an ASCII character, and the first byte capitalized and the rest lowercased. Non-ASCII byte values are passed through unchanged.  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.


bytes.center(width[, fillbyte])
bytearray.center(width[, fillbyte])
Return a copy of the object centered in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For bytes objects, the original sequence is returned if width is less than or equal to len(s).  Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.