Skip to content

ENH/TST: Allow more keywords to ensure_clean #30915

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

Merged
merged 1 commit into from
Jan 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 18 additions & 4 deletions pandas/_testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -473,7 +473,7 @@ def close(fignum=None):


@contextmanager
def ensure_clean(filename=None, return_filelike=False):
def ensure_clean(filename=None, return_filelike=False, **kwargs):
"""
Gets a temporary path and agrees to remove on close.

Expand All @@ -485,23 +485,37 @@ def ensure_clean(filename=None, return_filelike=False):
return_filelike : bool (default False)
if True, returns a file-like which is *always* cleaned. Necessary for
savefig and other functions which want to append extensions.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why don’t list encoding , mode here explicitly

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

and in the signature

Copy link
Member Author

@gfyoung gfyoung Jan 11, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryFile
https://docs.python.org/3/library/tempfile.html#tempfile.mkstemp

encoding and mode are not accepted in mkstemp.

The only shared parameters are prefix, suffix (corresponds to filename in our signature), and dir. Not sure that the remaining two need exposure.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking back on comment in OP is the main thing needed for now just encoding? If so I think better to just list explicitly and not pass to mkstemp

Copy link
Member Author

@gfyoung gfyoung Jan 11, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If so I think better to just list explicitly and not pass to mkstemp

The whole point is to use the **kwargs in ensure_clean as a pass through to mkstemp or TemporaryFile, depending on whether return_filelike is true or false.

Explicitly listing arguments that apply to one but not the other is going to be confusing. What is being done is a lot more extensible in the long-run.

**kwargs
Additional keywords passed in for creating a temporary file.
:meth:`tempFile.TemporaryFile` is used when `return_filelike` is ``True``.
:meth:`tempfile.mkstemp` is used when `return_filelike` is ``False``.
Note that the `filename` parameter will be passed in as the `suffix`
argument to either function.

See Also
--------
tempfile.TemporaryFile
tempfile.mkstemp
"""
filename = filename or ""
fd = None

kwargs["suffix"] = filename

if return_filelike:
f = tempfile.TemporaryFile(suffix=filename)
f = tempfile.TemporaryFile(**kwargs)

try:
yield f
finally:
f.close()
else:
# don't generate tempfile if using a path with directory specified
# Don't generate tempfile if using a path with directory specified.
if len(os.path.dirname(filename)):
raise ValueError("Can't pass a qualified name to ensure_clean()")

try:
fd, filename = tempfile.mkstemp(suffix=filename)
fd, filename = tempfile.mkstemp(**kwargs)
except UnicodeEncodeError:
import pytest

Expand Down
16 changes: 7 additions & 9 deletions pandas/tests/io/parser/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from io import StringIO
import os
import platform
from tempfile import TemporaryFile
from urllib.error import URLError

import numpy as np
Expand Down Expand Up @@ -1847,16 +1846,15 @@ def test_temporary_file(all_parsers):
parser = all_parsers
data = "0 0"

new_file = TemporaryFile("w+")
new_file.write(data)
new_file.flush()
new_file.seek(0)
with tm.ensure_clean(mode="w+", return_filelike=True) as new_file:
new_file.write(data)
new_file.flush()
new_file.seek(0)

result = parser.read_csv(new_file, sep=r"\s+", header=None)
new_file.close()
result = parser.read_csv(new_file, sep=r"\s+", header=None)

expected = DataFrame([[0, 0]])
tm.assert_frame_equal(result, expected)
expected = DataFrame([[0, 0]])
tm.assert_frame_equal(result, expected)


def test_internal_eof_byte(all_parsers):
Expand Down
3 changes: 1 addition & 2 deletions pandas/tests/io/parser/test_encoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

from io import BytesIO
import os
import tempfile

import numpy as np
import pytest
Expand Down Expand Up @@ -164,7 +163,7 @@ def test_encoding_temp_file(all_parsers, utf_value, encoding_fmt, pass_encoding)

expected = DataFrame({"foo": ["bar"]})

with tempfile.TemporaryFile(mode="w+", encoding=encoding) as f:
with tm.ensure_clean(mode="w+", encoding=encoding, return_filelike=True) as f:
f.write("foo\nbar")
f.seek(0)

Expand Down