Make a unique filesystem path, without creating the file

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Feb 14 23:54:42 EST 2016


On Monday 15 February 2016 12:19, Ben Finney wrote:

> One valid filesystem path each time it's accessed. That is, behaviour
> equivalent to ‘tempfile.mktemp’.
> 
> My question is because the standard library clearly has this useful
> functionality implemented, but simultaneously warns strongly against its
> use.

If you can absolutely guarantee that this string will never actually be used 
on a real filesystem, then go right ahead and use it. There's nothing wrong 
with (for instance) calling mktemp to generate *strings* that merely *look* 
like pathnames.

If you want to guarantee that these faux pathnames can't leak out of your 
test suite and touch the file system, prepend an ASCII NUL to them. That 
will make it an illegal path on all file systems that I'm aware of.


> I'm looking for how to get at that functionality in a non-deprecated
> way, without re-implementing it myself.

You probably can't, not if you want to future-proof your code against the 
day when tempfile.mktemp is removed.

But you can simply fork that module, delete all the irrelevant bits, and 
make the mktemp function a private utility in your test suite.


-- 
Steve




More information about the Python-list mailing list