diff --git a/changes/unreleased/4908.KnwujH2JruNRZSrTTvvc9B.toml b/changes/unreleased/4908.KnwujH2JruNRZSrTTvvc9B.toml new file mode 100644 index 00000000000..a8359bfc2e4 --- /dev/null +++ b/changes/unreleased/4908.KnwujH2JruNRZSrTTvvc9B.toml @@ -0,0 +1,5 @@ +bugfixes = "Fix ``ResourceWarning`` when passing ``pathlib.Path`` objects to methods which accept file input" +[[pull_requests]] +uid = "4908" +author_uid = "harshil21" +closes_threads = ["4907"] diff --git a/src/telegram/_utils/files.py b/src/telegram/_utils/files.py index 9bacce86f3c..860c1612351 100644 --- a/src/telegram/_utils/files.py +++ b/src/telegram/_utils/files.py @@ -145,7 +145,8 @@ def parse_file_input( # pylint: disable=too-many-return-statements path = Path(file_input) if local_mode: return path.absolute().as_uri() - return InputFile(path.open(mode="rb"), filename=filename, attach=attach) + with path.open(mode="rb") as file_handle: + return InputFile(file_handle, filename=filename, attach=attach) return file_input if isinstance(file_input, bytes): diff --git a/tests/_utils/test_files.py b/tests/_utils/test_files.py index 7d0b5454416..d789bdcd622 100644 --- a/tests/_utils/test_files.py +++ b/tests/_utils/test_files.py @@ -156,3 +156,13 @@ def test_load_file_subprocess_pipe(self): proc.kill() # This exception may be thrown if the process has finished before we had the chance # to kill it. + + @pytest.mark.filterwarnings("error::ResourceWarning") + def test_parse_file_input_path_no_resource_warning(self): + """Test that parsing a Path input doesn't generate ResourceWarning.""" + test_file = data_file(filename="telegram.png") + + # This should not raise a ResourceWarning + result = telegram._utils.files.parse_file_input(test_file) + assert isinstance(result, InputFile) + assert result.filename.endswith(".png")