cachepath module

Package that provides CachePath, as well as exporting a Python2/3 compatible Path.

cachepath.TempPath(cls, *args, **kwargs)[source]

See CachePath for more details:

TempPath('x', 'y', suffix='.z')
# Is safer, easier, and explains your intent to always have a new file better than
CachePath('x', 'y', 'randomstringhere', suffix='.z')

# However,
TempPath() == CachePath()  # for convenience
class cachepath.CachePath[source]

Bases: pathlib2.Path

Construct a CachePath from one or several strings/Paths.

Constructing a CachePath automatically creates the preceding folders necessary for the file to exist, if they’re not already there.

CachePaths also have a few helper methods:



By accident, these methods are also attached to regular Paths after constructing a CachePath, but it’s not recommended to depend on this behavior.


Basic Usage:

CachePath() == '/tmp/xyz123randomfile'
CachePath('myfilename') == '/tmp/myfilename'
CachePath('myfolder', dir=True) == '/tmp/myfolder/'
TempPath('myfolder') == '/tmp/myfolder/zsdskjrandom'

Multi-component Paths:

p = CachePath('date/processed_data', dir=True)
# Or, Alternate constructor to avoid {}/{}.format()
p = CachePath('date', 'processed_data', dir=True)

For an example of real usage, here’s a quick cache for an arbitrary function/arg combo

def get_scraped_ebay_stats(product_id):
    p = CachePath('ebay_results/{}'.format(product_id))
    if not p.exists():
       sh('wget {}'.format(p))
    return parser.parse(p.read_text())
  • args ([str], optional) – List of strings to join for Path. If None, getempfile is used.
  • dir (bool, optional) –

    Is the path intended to be a directory? Useful when you just need a tempdir for lots of files, and you don’t want to make a CachePath out of each.

    d = CachePath(date, dir=True)
    list(d.iterdir()) == ['tool1results', 'tool2results']
  • suffix (str, optional) – Appended to the last path in *args, i.e. CachePath(‘a’, ‘b’, suffix=’_long_suff.txt’) == ‘/tmp/a/b_long_suff.txt’
  • mode (int, optional, default=0o777) – Mode to create folder with, if it doesn’t already exist.

Clear the file/dir, leaving it empty (dir) or 0 length (file).

Monkey-patched onto all Paths on import. Creates file if path doesn’t exist.


Delete the file/dir, even if it’s a dir with files in it.

Monkey-patched onto all Paths on import. Does nothing if path doesn’t exist.