[docs] [issue15269] Document dircmp.left and dircmp.right

Chris Jerdonek report at bugs.python.org
Wed Jul 25 01:21:23 CEST 2012

Chris Jerdonek <chris.jerdonek at gmail.com> added the comment:

Thanks for taking the time to look at this, Eli.

In response to your question, here is one illustrated rationale.

When recursing through a directory using dircmp, it is simplest and cleanest to be able to recurse on the subdirs attribute without having to pass pairs of paths around or reconstruct dircmp instances.  You can see this for example in filecmp's own very concise implementation of dircmp.report_full_closure():

    def report_full_closure(self): # Report on self and subdirs recursively
        for sd in self.subdirs.values():

However, dircmp's reporting functionality is self-admittedly "lousy":

    def report(self): # Print a report on the differences between a and b
        # Output format is purposely lousy
        print('diff', self.left, self.right)

(Incidentally, observe above that dircmp.report() itself uses the 'left' and 'right' attributes.)

Given the limitations of report_full_closure(), etc, it is natural that one might want to write a custom or replacement reporting function with nicer formatting.  When doing this, it would be nice to be able to follow that same clean and concise recursion pattern.  For example--

    def diff(dcmp):
        for sd in dcmp.subdirs.values():
        for name in dcmp.diff_files:
            print("%s differs in %s and %s" % (name, dcmp.left, dcmp.right))

    dcmp = dircmp('dir1', 'dir2')

If one isn't able to access 'left' and 'right' (or if one simply isn't aware of those attributes, which was the case for me at one point), the alternative would be to do something like the following, which is much uglier and less DRY:

    import os

    def diff2(dcmp, dir1, dir2):
        for name, sd in dcmp.subdirs.items():
            subdir1 = os.path.join(dir1, name)
            subdir2 = os.path.join(dir2, name)
            diff2(sd, subdir1, subdir2)
        for name in dcmp.diff_files:
            print("%s differs in %s and %s" % (name, dir1, dir2))

    dcmp = dircmp('dir1', 'dir2')
    diff2(dcmp, dir1='dir1', dir2='dir2')

An example like diff() above might even be worth including in the docs as an example of how subdirs can be used to avoid having to manually call os.path.join(...), etc.

There are also non-recursive situations in which being able to access dircmp.left and dircmp.right makes for cleaner code.


Python tracker <report at bugs.python.org>

More information about the docs mailing list