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.
self.original_object = sys.path seems to be redundant.
sys.path is shallow copied to
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[:]), and copying and assigning it can achieve the goal.
Maybe there is some background about the code, can someone tell me please.