New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Making tempfile.NamedTemporaryFile a class #66581
Comments
Currently, tempfile.TemporaryFile and tempfile.NamedTemporaryFile are functions, not classes, despite what their names suggest, preventing subclassing. It would arguably be not so easy to make TemporaryFile a class, as its return value is whatever "_io.open" returns, which can be of various types, but NamedTemporaryFile can trivially converted into a class by reusing the body of _TemporaryFileWrapper (which is not used elsewhere). |
Can you explain why you want to subclass them? |
The initial idea was to solve bpo-14243 (NamedTemporaryFile would be more useful on Windows if you could close it without deleting) by adding a "closed" keyword argument to the constructor of a subclass, that would set "delete" to False and then close it, e.g. class NTF(NamedTemporaryFile):
def __init__(self, *args, closed=False, **kwargs):
if closed: kwargs["delete"] = True
super().__init__(*args, **kwargs)
if closed: self.close() Actually, there are some not-so-nice interactions with the context-manager protocol though, as the file cannot be reopened. So it's not clear that this is such a good idea. Still, it somewhat confusing that a CamelCase object is not actually a type (especially when TemporaryDirectory is one). |
You can do this with a function too: def NTF(*args, closed=False, **kwargs):
if closed: kwargs["delete"] = True
ntf = NamedTemporaryFile(*args, **kwargs)
if closed: ntf.close()
return ntf |
Yes, but this will make the context-manager approach (with NamedTemporaryFile(closed=True): <do stuff>) unusable, because the underlying file object will be closed before calling __enter__. I think the only reasonable way to implement this would be to have __enter__ return the file name (as for TemporaryDirectory), instead of the file object (which is reasonable because if I pass closed=True, it probably means all I care is that a file exists here for some other process to use!). |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: