Micro-optimized class for searching a root for children. Root is a path on the file system that may contain metadata directories either as natural directories or within a zip file. >>> FastPath('').children() ['...'] FastPath objects are cached and recycled for any given
| 816 | |
| 817 | |
| 818 | class FastPath: |
| 819 | """ |
| 820 | Micro-optimized class for searching a root for children. |
| 821 | |
| 822 | Root is a path on the file system that may contain metadata |
| 823 | directories either as natural directories or within a zip file. |
| 824 | |
| 825 | >>> FastPath('').children() |
| 826 | ['...'] |
| 827 | |
| 828 | FastPath objects are cached and recycled for any given root. |
| 829 | |
| 830 | >>> FastPath('foobar') is FastPath('foobar') |
| 831 | True |
| 832 | """ |
| 833 | |
| 834 | @_clear_after_fork # type: ignore[misc] |
| 835 | @functools.lru_cache() |
| 836 | def __new__(cls, root): |
| 837 | return super().__new__(cls) |
| 838 | |
| 839 | def __init__(self, root): |
| 840 | self.root = root |
| 841 | |
| 842 | def joinpath(self, child): |
| 843 | return pathlib.Path(self.root, child) |
| 844 | |
| 845 | def children(self): |
| 846 | with suppress(Exception): |
| 847 | return os.listdir(self.root or '.') |
| 848 | with suppress(Exception): |
| 849 | return self.zip_children() |
| 850 | return [] |
| 851 | |
| 852 | def zip_children(self): |
| 853 | # deferred for performance (python/importlib_metadata#502) |
| 854 | import zipfile |
| 855 | |
| 856 | zip_path = zipfile.Path(self.root) |
| 857 | names = zip_path.root.namelist() |
| 858 | self.joinpath = zip_path.joinpath |
| 859 | |
| 860 | return dict.fromkeys(child.split(posixpath.sep, 1)[0] for child in names) |
| 861 | |
| 862 | def search(self, name): |
| 863 | return self.lookup(self.mtime).search(name) |
| 864 | |
| 865 | @property |
| 866 | def mtime(self): |
| 867 | with suppress(OSError): |
| 868 | return os.stat(self.root).st_mtime |
| 869 | self.lookup.cache_clear() |
| 870 | |
| 871 | @method_cache |
| 872 | def lookup(self, mtime): |
| 873 | return Lookup(self) |
| 874 | |
| 875 |
no outgoing calls
searching dependent graphs…