Potentially redundant code in context manager(import_helper.py)

Hi, I was recently reading the source code about CPython unittest, and I found the following code in import_help.py:

class DirsOnSysPath(object):
    """Context manager to temporarily add directories to sys.path.
    ...
    """

    def __init__(self, *paths):
        self.original_value = sys.path[:]
        self.original_object = sys.path  # is this redundant?
        sys.path.extend(paths)

    def __enter__(self):
        return self

    def __exit__(self, *ignore_exc):
        sys.path = self.original_object
        sys.path[:] = self.original_value

Here is a class for testing Tools and scripts, it can temporarily add the package directory to sys.path, and restore sys.path after the test is completed.

IMO, self.original_object = sys.path seems to be redundant.

Here, sys.path is shallow copied to self.original_object, and self.original_object is assigned to sys.path at the end. extend will not change the id of the list object, and it seems that the two are one object from beginning to end.

It seems that we could only keep the slice of sys.path (sys.path[:]), and copying and assigning it can achieve the goal.

Maybe there is some background about the code, can someone tell me please.:slight_smile:

self.original_value is the contents of the sys.path list.
self.original_object is the list itself that is sys.path

So no the code is correct.

It maintains the object identity of sys.path and the contents of sys.path list.

1 Like

Thanks! :yum: I suddenly understood.

If someone directly assigns other variables(int, float or others) to sys.path, it may trigger unexpected errors. (While normally no one does this, removing this line also passes all unit tests)

Also asigning a new list would be a problem potentially.

sys.path = ['my', 'test', 'path']