Make a unique filesystem path, without creating the file

Ben Finney ben+python at
Tue Feb 16 14:48:14 EST 2016

Steven D'Aprano <steve at> writes:

> On Tue, 16 Feb 2016 04:56 pm, Ben Finney wrote:
> >     names = tempfile._get_candidate_names()
> I'm not sure that calling a private function of the tempfile module is
> better than calling a deprecated function.

Agreed, which is why I'm seeking a public API that is not deprecated.

> So why not just pick a random bunch of characters?
>     chars = list(string.ascii_letters)
>     random.shuffle(chars)
>     fake_file_path = ''.join(chars[:10])

This (an equivalent) is already implemented, internally to ‘tempfile’
and tested and maintained and more robust than me re-inventing the wheel.

> Yes, but the system doesn't try to enforce the filesystem's rules,
> does it?

The test case I'm writing should not be prone to failure if the system
happens to perform some arbitrary validation of filesystem paths.

‘tempfile’ already knows how to generate filesystem paths, I want to use
that and not have to get it right myself.

> and your system shouldn't care.

If it does, this test case should not fail.

> Since your test doesn't know what filesystem your code will be running
> on, you can't make any assumptions about what paths are valid or not
> valid.

That implies that ‘tempfile._get_candidate_names’ would generate paths
that would potentially be invalid. Is that what you intend to imply?

> > Almost. I want the filesystem paths to be valid because the system
> > under test expects them, it may perform its own validation,
> If the system tries to validate paths, it is broken.

This is “you don't want what you say you want”, and seeing the
justifications presented I don't agree.

 \     “I must say that I find television very educational. The minute |
  `\       somebody turns it on, I go to the library and read a book.” |
_o__)                                                    —Groucho Marx |
Ben Finney

More information about the Python-list mailing list