importlib.readers.MultiplexedPath.joinpath() to return MultiplexedPaths for subdirs that exist in multiple base dirs

Update: my previous example implementation only worked for the first level of sub directories. Below is an updated example that also works for deeper subdirectory levels.

I recently looked into MultiplexedPath as a way to provide easy access to data files that can be either part of a packages resources, or reside in a local user directory. In my case, the contents of both these base paths have the same directory structure. Currently, when accessing one of these subdirectories with the joinpath() method, you only get a Path object pointing to the first occurrence of the requested subdirectory that was found.

My suggestion would be to in these cases instead return another MultiplexedPath object, so that when you iterate over the contents of one of these common subfolders you get the merged contents of all existing common subdirectories, in the same way that MultiplexedPath.iterdir() now also returns the combined results of all of its included base paths.

An example implementation, based on the current implementation in MultiplexedPath:

    def joinpath(self, child):
        # first try to find child in current paths
        paths = []
        for path in (p / child for p in self._paths):
            if path.exists():
                if path.is_dir():
                    # If it's a dir, try to combine it with others
                    # If it's a file, immediately return it
                    return path

        # if it does not exist, construct it with the first path
        return MultiplexedPath(*paths) if len(paths) > 1 else \
            paths[0] if len(paths) == 1 else self._paths[0] / child
1 Like