Last active
January 18, 2023 21:48
-
-
Save tsvikas/a6f10786b9762c128da2e1c5afc49c67 to your computer and use it in GitHub Desktop.
PathGroup is a group of python Path objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from itertools import chain | |
from pathlib import Path | |
class PathGroup(list): | |
def __getitem__(self, y): | |
res = super().__getitem__(y) | |
return PathGroup(res) if (type(res) == list) else res | |
def glob(self, pattern): | |
return PathGroup(chain.from_iterable(sorted(p.glob(pattern)) for p in self)) | |
def __getattr__(self, name): | |
if not hasattr(Path, name): | |
raise AttributeError(f"type object {type(self).__name__!r} has no attribute {name!r}") | |
attr = getattr(Path, name) | |
if isinstance(attr, property): | |
return PathGroup(getattr(p, name) for p in self) | |
elif callable(attr): | |
def f(*args, **kwargs): | |
return PathGroup( | |
getattr(p, name)(*args, **kwargs) | |
for p in self | |
) | |
f.__name__ = name | |
f.__qualname__ = self.__name__ + '.' + name | |
return f | |
else: | |
# class attribute | |
return getattr(PathGroup, name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment