Skip to content

Fix ResourceWarning when passing pathlib.Path to send_photo/send_document #4908

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 8 commits into from
Aug 17, 2025
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
5 changes: 5 additions & 0 deletions changes/unreleased/4908.KnwujH2JruNRZSrTTvvc9B.toml
Original file line number Diff line number Diff line change
@@ -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"]
3 changes: 2 additions & 1 deletion src/telegram/_utils/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
10 changes: 10 additions & 0 deletions tests/_utils/test_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Loading