Is there a way to wrap class instances around each other like below, as many times as needed, while still having access to attributes as if unwrapped?
class MyPath:
def __init__(self, path=None):
self.path = path
print(MyPath('my/file/path.txt').path)
# my/file/path.txt
print(MyPath(MyPath('my/file/path.txt')).path)
# <__main__.MyPath object at 0x105061ed0>
pathlib.Path employs this, but I couldn’t figure it out from the source code.
One simplistic possibility is:
class MyPath:
def __init__(self, instance_or_path=None):
self._instance_or_path = instance_or_path
@property
def path(self):
if isinstance(self._instance_or_path, MyPath):
return self._instance_or_path.path
return self._instance_or_path
Put I was thinking there might be a better way, which doesn’t require type checking.