Implement os.PathLike for NamedTemporaryFile

tempfile.NamedTemporaryFile should implement the os.PathLike Protocol.
This should be fairly easy to implement, as the path as a string is already avaliable as the name attribute.


It returns a file-like object.

Why it should implement the os.PathLike protocol?

If it does, then it sounds like result of open should be of PathLike, too.

Then, the following code would be accepted by Python:

f = open('xx', 'w')
f = open(f, 'w')

So does for many other types.

I think there may be a miscommunication here. NamedTemporaryFile gives you a file-like object. os.PathLike is an interface for names of files (well, paths to them). When you create a NamedTemporaryFile, you don’t specify a name; Python figures out a suitable name (that won’t conflict with existing files or folders). And you get back the actual file handle, which you can use to .read or .write or whatever else; it doesn’t make sense for that to be os.PathLike - you’ve already done the file opening.

If you mean that the .name of the created file should implement the protocol, it does - it’s a string. If you mean that it should specifically be a pathlib.Path instance, that could break other things that don’t know about os.PathLike.

If you mean that e.g. the dir parameter for NamedTemporaryFile should accept anything that’s os.PathLike - doesn’t it already? I haven’t checked…

If you mean something else, you’re going to have to explain it more clearly. Show an example of code you think you should be able to write, explain what happens currently when you try it, explain what you think should happen instead, and justify it.

1 Like

I think you guys are right, thanks for pointing out my misunderstanding :slight_smile:

There’s an open issue and PR for this:

I still think that NamedTemporaryFile supporting the PathLike protocol makes sense. The filename is the distinguishing feature of NamedTemporaryFile, so it will be used. The following code would make total sense to me:

with NamedTemporaryFile() as tmp:
    shutil.copyfile(tmp, "/foo/bar")