Created
March 31, 2018 17:35
-
-
Save mdwhatcott/8667dc728235d0a6bbd7437e567ff83e to your computer and use it in GitHub Desktop.
Dynamic attribute resolution to mimic a directory tree on a file system (either real or contrived).
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
class Path(object): | |
""" | |
This nifty class uses dynamic attribute resolution to mimic a directory | |
tree on a file system (either real or contrived). | |
""" | |
def __init__(self, root, enforce_real_paths=False): | |
self.root___ = str(root) | |
self.navigation___ = [] | |
self.enforce___ = enforce_real_paths | |
if self.enforce___ and not os.path.exists(self.root___): | |
raise IOError('Path does not exist: {0}', self.root___) | |
def __getattr__(self, item): | |
self.navigation___.append(item) | |
proposed = os.path.join(self.root___, *self.navigation___) | |
if self.enforce___ and not os.path.exists(proposed): | |
self.navigation___.pop() | |
raise IOError('Path does not exist: {0}'.format(proposed)) | |
return self | |
# noinspection PyUnusedLocal | |
def __call__(self, *args, **kwargs): | |
path = os.path.join(self.root___, *self.navigation___) | |
if args: | |
path += args[0] | |
self.navigation___ = [] | |
return path | |
def __str__(self): | |
return self.root___ | |
def __repr__(self): | |
return 'Path({0}, enforce_real_paths={1})'.format( | |
self.root___, self.enforce___) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment