The diff_bytes() function of Python difflib module

The function diff_bytes() from the difflib module of Python computes the differences between two lists of bytes. The returned differences are also of type bytes with the original encoding as the input parameters.

Difflib Module Updated 9 Apr 2026 2 min read

Function signature

diff_bytes(dfunc, a, b, fromfile=b'', tofile=b'',

fromfiledate=b'', tofiledate=b'', n=3, lineterm=b'\n')

Parameters

dfunc – A function that computes the differences between the two lists of bytes.

a – Version one of the bytes passed as list of bytes.

b – Version two of the bytes passed as list of bytes.

fromfile – A Python bytes object that denotes the name for version one.

tofile – A Python bytes object that denotes the name for version two.

fromfiledate – Timestamp of version one as bytes.

tofiledate – Timestamp of version two as bytes.

n – The number of context lines to appear in output. An integer value.

lineterm – The line terminator. The default value is “\n”.

Overview

  • The function diff_bytes() finds the difference between two lists of bytes and returns them in the same encoding as the original bytes.
  • The diff_bytes() accepts a function that can find the difference between the two lists of bytes. Functions like unified_diff() or context_diff() can be passed for the dfunc parameter for computing the differences between the two versions of bytes.

Example

python
# Example Python program that finds

            # the differences between two bytes

            # objects using the function

            # difflib.diff_bytes()

            import difflib

# Lists of bytes

            bytes1 = [b"A tree that looks at God all day,",

                      b"And lifts her leafy arms to pray;"]

bytes2 = [b"A tree that may in Summer wear",

                      b"A nest of robins in her hair;"]

# Find the differences

            diffs = difflib.diff_bytes(difflib.unified_diff,

                                       bytes1,

                                       bytes2)

            # Print the differences

            for diff in diffs:

                print(diff)

Output

Output
b'--- \n'

            b'+++ \n'

            b'@@ -1,2 +1,2 @@\n'

            b'-A tree that looks at God all day,'

            b'-And lifts her leafy arms to pray;'

            b'+A tree that may in Summer wear'

            b'+A nest of robins in her hair;'