Skip to main content

Mutable Pathlib

Project description

mutapath

CircleCI codecov Renovate Status CodeFactor PyPI - Python Version PyPI Documentation Status GitHub License GitHub last commit

This library is for you if you are also annoyed that there is no mutable pathlib wrapper for use cases where paths are often changed. mutapath solves this by wrapping the extended pathlib library path.py and updating the encapsulated object every time the path might be changed.

mutapath also adds the possibility to delimit file and path modifications to a safe fallback context.

MutaPath Class

The MutaPath Class allows direct manipulation of its attributes at any time, just as any mutable object. Once a file operation is called that is intended to modify its path, the underlying path is also mutated.

>>> from mutapath import MutaPath
>>> folder = MutaPath("/home/joe/doe/folder/sub")
>>> folder
Path('/home/joe/doe/folder/sub')
>>> folder.name = "top"
>>> folder
Path('/home/joe/doe/folder/top')
>>> next = MutaPath("/home/joe/doe/folder/next")
>>> next
Path('/home/joe/doe/folder/next')
>>> next.rename(folder)
>>> next
Path('/home/joe/doe/folder/top')
>>> next.exists()
True
>>> Path('/home/joe/doe/folder/sub').exists()
False

Path Class

This class is immutable by default, just as the pathlib.Path. However, it allows to open a editing context via mutate(). Moreover, there are additional contexts for file operations. They update the file and its path while closing the context. If the file operations don't succeed, they throw an exception and fall back to the original path value.

>>> from mutapath import Path
>>> folder = Path("/home/joe/doe/folder/sub")
>>> folder
Path('/home/joe/doe/folder/sub')
>>> folder.name = "top"
AttributeError: mutapath.Path is an immutable class, unless mutate() context is used.
>>> folder
Path('/home/joe/doe/folder/sub')
>>> with folder.mutate() as m:
...     m.name = "top"
>>> folder
Path('/home/joe/doe/folder/top')
>>> next = Path("/home/joe/doe/folder/next")
>>> next.copy(folder)
>>> next
Path('/home/joe/doe/folder/next')
>>> folder.exists()
True
>>> folder.remove()
>>> with next.renaming() as m:
...     m.stem = folder.stem
...     m.suffix = ".txt"
>>> next
Path("/home/joe/doe/folder/sub.txt")
>>> next.exists()
True
>>> next.with_name("next").exists()
False

For more in-depth examples, check the tests folder.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mutapath-0.11.1.tar.gz (13.0 kB view hashes)

Uploaded Source

Built Distribution

mutapath-0.11.1-py3-none-any.whl (17.3 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page