From 84b733e6499bd926fc68df17540a9d9a0cc599b5 Mon Sep 17 00:00:00 2001 From: NaveenKumarG-dev Date: Wed, 17 Jun 2026 10:21:10 +0530 Subject: [PATCH 1/9] gh-151575: Emit DeprecationWarning in mimetypes.guess_type() for file paths feat: introduce MimeTypes class and deprecate file path support in guess_type with new guess_file_type method feat: add guess_file_type to mimetypes module to support path-based MIME lookups test: add test suite for mimetypes module Address PR feedback: fix mimetypes CLI, lazy imports, and doc deprecations --- .../pending-removal-in-future.rst | 4 ++ Doc/library/mimetypes.rst | 12 +++-- Doc/whatsnew/3.16.rst | 7 +++ Lib/mimetypes.py | 17 +++++-- Lib/test/test_mimetypes.py | 46 ++++++++++++------- ...6-17-09-45-00.gh-issue-151575.mimetype.rst | 1 + 6 files changed, 63 insertions(+), 24 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2026-06-17-09-45-00.gh-issue-151575.mimetype.rst diff --git a/Doc/deprecations/pending-removal-in-future.rst b/Doc/deprecations/pending-removal-in-future.rst index 6f372275225669d..e3315febd3976ee 100644 --- a/Doc/deprecations/pending-removal-in-future.rst +++ b/Doc/deprecations/pending-removal-in-future.rst @@ -71,6 +71,10 @@ although there is currently no date scheduled for their removal. * :mod:`mailbox`: Use of StringIO input and text mode is deprecated, use BytesIO and binary mode instead. +* :mod:`mimetypes`: Passing a file path (including path-like objects and bytes + paths) to :func:`~mimetypes.guess_type`. Use + :func:`~mimetypes.guess_file_type` instead. (:gh:`151575`) + * :mod:`os`: Calling :func:`os.register_at_fork` in a multi-threaded process. * :mod:`os.path`: :func:`os.path.commonprefix` is deprecated, use diff --git a/Doc/library/mimetypes.rst b/Doc/library/mimetypes.rst index 38efc08ee421b24..18caec4e0d5c2da 100644 --- a/Doc/library/mimetypes.rst +++ b/Doc/library/mimetypes.rst @@ -28,8 +28,7 @@ the information :func:`init` sets up. .. index:: pair: MIME; headers - Guess the type of a file based on its filename, path or URL, given by *url*. - URL can be a string or a :term:`path-like object`. + Guess the type of a file based on its URL, given as a string. The return value is a tuple ``(type, encoding)`` where *type* is ``None`` if the type can't be guessed (missing or unknown suffix) or a string of the form @@ -54,9 +53,9 @@ the information :func:`init` sets up. .. versionchanged:: 3.8 Added support for *url* being a :term:`path-like object`. - .. soft-deprecated:: 3.13 - Passing a file path instead of URL. - Use :func:`guess_file_type` for this. + .. deprecated-removed:: 3.16 3.21 + Passing a file path (or path-like object) instead of a URL. + Use :func:`guess_file_type` instead. .. function:: guess_file_type(path, *, strict=True) @@ -265,6 +264,9 @@ than one MIME-type database; it provides an interface similar to the one of the Similar to the :func:`guess_type` function, using the tables stored as part of the object. + .. deprecated-removed:: 3.16 3.21 + Passing a file path (or path-like object) instead of a URL. + Use :func:`guess_file_type` instead. .. method:: MimeTypes.guess_file_type(path, *, strict=True) diff --git a/Doc/whatsnew/3.16.rst b/Doc/whatsnew/3.16.rst index 15979fb11aa11d2..57e239914dc7168 100644 --- a/Doc/whatsnew/3.16.rst +++ b/Doc/whatsnew/3.16.rst @@ -1367,6 +1367,13 @@ New deprecations instead. (Contributed by Bartosz Sławecki in :gh:`143465`.) +* :mod:`mimetypes`: + + * Passing a file path (or :term:`path-like object`) to + :func:`mimetypes.guess_type` is now deprecated. + Use :func:`mimetypes.guess_file_type` instead. + (Contributed by Naveen Kumar G and Stephen Rosen in :gh:`151575`.) + * :mod:`struct`: * The ``'F'`` and ``'D'`` type codes, soft-deprecated since Python 3.15, diff --git a/Lib/mimetypes.py b/Lib/mimetypes.py index 561b99a92c8d16b..af74dff94fae7a9 100644 --- a/Lib/mimetypes.py +++ b/Lib/mimetypes.py @@ -114,7 +114,7 @@ def add_type(self, type, ext, strict=True): exts.append(ext) def guess_type(self, url, strict=True): - """Guess the type of a file which is either a URL or a path-like object. + """Guess the type of a file based on its URL. Return value is a tuple (type, encoding) where type is None if the type can't be guessed (no or unknown suffix) or a string @@ -136,13 +136,19 @@ def guess_type(self, url, strict=True): import os import urllib.parse - # TODO: Deprecate accepting file paths (in particular path-like objects). url = os.fspath(url) p = urllib.parse.urlparse(url) if p.scheme and len(p.scheme) > 1: scheme = p.scheme url = p.path else: + import warnings + warnings.warn( + "Passing a file path to guess_type() is deprecated and will be " + "removed in a future version. Use guess_file_type() instead.", + DeprecationWarning, + stacklevel=2, + ) return self.guess_file_type(url, strict=strict) if scheme == 'data': # syntax of data URLs: @@ -760,8 +766,13 @@ def _main(args=None): results.append(f"error: unknown type {gtype}") return results else: + import urllib.parse for gtype in args.type: - guess, encoding = guess_type(gtype, not args.lenient) + p = urllib.parse.urlparse(gtype) + if p.scheme and len(p.scheme) > 1: + guess, encoding = guess_type(gtype, strict=not args.lenient) + else: + guess, encoding = guess_file_type(gtype, strict=not args.lenient) if guess: results.append(f"type: {guess} encoding: {encoding}") else: diff --git a/Lib/test/test_mimetypes.py b/Lib/test/test_mimetypes.py index 8e39552dba8aa89..11fe784e0b8be54 100644 --- a/Lib/test/test_mimetypes.py +++ b/Lib/test/test_mimetypes.py @@ -3,7 +3,9 @@ import os import shlex import sys +import unittest import unittest.mock + from platform import win32_edition from test import support from test.support import cpython_only, force_not_colorized, os_helper, requires_subprocess @@ -277,14 +279,14 @@ def test_default_knownfiles(self): def test_added_types_are_used(self): mimetypes.add_type('testing/default-type', '') - mime_type, _ = mimetypes.guess_type('') + mime_type, _ = mimetypes.guess_file_type('') self.assertEqual(mime_type, 'testing/default-type') - mime_type, _ = mimetypes.guess_type('test.myext') + mime_type, _ = mimetypes.guess_file_type('test.myext') self.assertEqual(mime_type, None) mimetypes.add_type('testing/type', '.myext') - mime_type, _ = mimetypes.guess_type('test.myext') + mime_type, _ = mimetypes.guess_file_type('test.myext') self.assertEqual(mime_type, 'testing/type') def test_add_type_with_undotted_extension_not_supported(self): @@ -434,21 +436,26 @@ def test_filename_with_url_delimiters(self): path = prefix + name with self.subTest(path=path): eq(self.db.guess_file_type(path), gzip_expected) - eq(self.db.guess_type(path), gzip_expected) + with self.assertWarns(DeprecationWarning): + eq(self.db.guess_type(path), gzip_expected) expected = (None, None) if os.name == 'nt' else gzip_expected for prefix in ('//', '\\\\', '//share/', '\\\\share\\'): path = prefix + name with self.subTest(path=path): eq(self.db.guess_file_type(path), expected) - eq(self.db.guess_type(path), expected) + with self.assertWarns(DeprecationWarning): + eq(self.db.guess_type(path), expected) eq(self.db.guess_file_type(r" \"\`;b&b&c |.tar.gz"), gzip_expected) - eq(self.db.guess_type(r" \"\`;b&b&c |.tar.gz"), gzip_expected) + with self.assertWarns(DeprecationWarning): + eq(self.db.guess_type(r" \"\`;b&b&c |.tar.gz"), gzip_expected) eq(self.db.guess_file_type(r'foo/.tar.gz'), (None, 'gzip')) - eq(self.db.guess_type(r'foo/.tar.gz'), (None, 'gzip')) + with self.assertWarns(DeprecationWarning): + eq(self.db.guess_type(r'foo/.tar.gz'), (None, 'gzip')) expected = (None, 'gzip') if os.name == 'nt' else gzip_expected eq(self.db.guess_file_type(r'foo\.tar.gz'), expected) - eq(self.db.guess_type(r'foo\.tar.gz'), expected) + with self.assertWarns(DeprecationWarning): + eq(self.db.guess_type(r'foo\.tar.gz'), expected) eq(self.db.guess_type(r'scheme:foo\.tar.gz'), gzip_expected) def test_url(self): @@ -506,16 +513,20 @@ def test_path_like_ob(self): expected = self.db.guess_file_type(filename) self.assertEqual(self.db.guess_file_type(filepath), expected) - self.assertEqual(self.db.guess_type(filepath), expected) + with self.assertWarns(DeprecationWarning): + self.assertEqual(self.db.guess_type(filepath), expected) self.assertEqual(self.db.guess_file_type( filepath_with_abs_dir), expected) - self.assertEqual(self.db.guess_type( - filepath_with_abs_dir), expected) + with self.assertWarns(DeprecationWarning): + self.assertEqual(self.db.guess_type( + filepath_with_abs_dir), expected) self.assertEqual(self.db.guess_file_type(filepath_relative), expected) - self.assertEqual(self.db.guess_type(filepath_relative), expected) + with self.assertWarns(DeprecationWarning): + self.assertEqual(self.db.guess_type(filepath_relative), expected) self.assertEqual(self.db.guess_file_type(path_dir), (None, None)) - self.assertEqual(self.db.guess_type(path_dir), (None, None)) + with self.assertWarns(DeprecationWarning): + self.assertEqual(self.db.guess_type(path_dir), (None, None)) def test_bytes_path(self): self.assertEqual(self.db.guess_file_type(b'foo.html'), @@ -534,6 +545,9 @@ def test_keywords_args_api(self): type='image/jpeg', strict=True), ['.jpg', '.jpe', '.jpeg']) + + + @unittest.skipUnless(sys.platform.startswith("win"), "Windows only") class Win32MimeTypesTestCase(unittest.TestCase): def setUp(self): @@ -555,9 +569,9 @@ def test_registry_parsing(self): # Windows registry is undocumented AFAIK. # Use file types that should *always* exist: eq = self.assertEqual - eq(self.db.guess_type("foo.txt"), ("text/plain", None)) - eq(self.db.guess_type("image.jpg"), ("image/jpeg", None)) - eq(self.db.guess_type("image.png"), ("image/png", None)) + eq(self.db.guess_file_type("foo.txt"), ("text/plain", None)) + eq(self.db.guess_file_type("image.jpg"), ("image/jpeg", None)) + eq(self.db.guess_file_type("image.png"), ("image/png", None)) def test_default_knownfiles(self): self.assertEqual(knownfiles, []) diff --git a/Misc/NEWS.d/next/Library/2026-06-17-09-45-00.gh-issue-151575.mimetype.rst b/Misc/NEWS.d/next/Library/2026-06-17-09-45-00.gh-issue-151575.mimetype.rst new file mode 100644 index 000000000000000..8bb01faf719903f --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-06-17-09-45-00.gh-issue-151575.mimetype.rst @@ -0,0 +1 @@ +Deprecate passing a file path to :func:`mimetypes.guess_type`. Use :func:`mimetypes.guess_file_type` instead. From 44b9566d057b82fc6bafa9a497ff159dbf107576 Mon Sep 17 00:00:00 2001 From: Stephen Rosen Date: Thu, 26 Nov 2026 17:40:55 -0600 Subject: [PATCH 2/9] Move mimetypes lazy imports to top of module os, sys, and posixpath are loaded on interpreter start -- making them lazy has no meaningful effect, so they are made into plain imports. urllib.parse, warnings, and argparse.ArgumentParser are made into lazy imports. Inline imports are removed. --- Lib/mimetypes.py | 24 ++++++------------------ 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/Lib/mimetypes.py b/Lib/mimetypes.py index af74dff94fae7a9..ed90c0e4fd494fa 100644 --- a/Lib/mimetypes.py +++ b/Lib/mimetypes.py @@ -24,6 +24,12 @@ """ import sys +import os +import posixpath +lazy import urllib.parse +lazy import warnings +lazy from argparse import ArgumentParser + try: from _winapi import _mimetypes_read_windows_registry @@ -132,9 +138,6 @@ def guess_type(self, url, strict=True): Optional 'strict' argument when False adds a bunch of commonly found, but non-standard types. """ - # Lazy import to improve module import time - import os - import urllib.parse url = os.fspath(url) p = urllib.parse.urlparse(url) @@ -142,7 +145,6 @@ def guess_type(self, url, strict=True): scheme = p.scheme url = p.path else: - import warnings warnings.warn( "Passing a file path to guess_type() is deprecated and will be " "removed in a future version. Use guess_file_type() instead.", @@ -170,9 +172,6 @@ def guess_type(self, url, strict=True): type = 'text/plain' return type, None # never compressed, so encoding is None - # Lazy import to improve module import time - import posixpath - return self._guess_file_type(url, strict, posixpath.splitext) def guess_file_type(self, path, *, strict=True): @@ -180,9 +179,6 @@ def guess_file_type(self, path, *, strict=True): Similar to guess_type(), but takes file path instead of URL. """ - # Lazy import to improve module import time - import os - path = os.fsdecode(path) path = os.path.splitdrive(path)[1] return self._guess_file_type(path, strict, os.path.splitext) @@ -442,9 +438,6 @@ def init(files=None): else: db = _db - # Lazy import to improve module import time - import os - for file in files: if os.path.isfile(file): db.read(file) @@ -732,8 +725,6 @@ def _default_mime_types(): def _parse_args(args): - from argparse import ArgumentParser - parser = ArgumentParser( description='map filename extensions to MIME types', ) @@ -766,7 +757,6 @@ def _main(args=None): results.append(f"error: unknown type {gtype}") return results else: - import urllib.parse for gtype in args.type: p = urllib.parse.urlparse(gtype) if p.scheme and len(p.scheme) > 1: @@ -781,8 +771,6 @@ def _main(args=None): if __name__ == '__main__': - import sys - results = _main() print("\n".join(results)) sys.exit(any(result.startswith("error: ") for result in results)) From 2e30c8a0e6d5d0f2a5321a18ca43003a7276a793 Mon Sep 17 00:00:00 2001 From: Stephen Rosen Date: Thu, 26 Nov 2026 17:43:55 -0600 Subject: [PATCH 3/9] Add soft-deprecation notes for mimetypes.guess_type Per discussion and feedback, passing a Path is noted in text (not with a directive) as soft deprecated, and deprecated-removed for the 3.16 - 3.21 timeline. --- Doc/library/mimetypes.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Doc/library/mimetypes.rst b/Doc/library/mimetypes.rst index 18caec4e0d5c2da..837ecf913e1009a 100644 --- a/Doc/library/mimetypes.rst +++ b/Doc/library/mimetypes.rst @@ -56,6 +56,7 @@ the information :func:`init` sets up. .. deprecated-removed:: 3.16 3.21 Passing a file path (or path-like object) instead of a URL. Use :func:`guess_file_type` instead. + Soft deprecated since version 3.13. .. function:: guess_file_type(path, *, strict=True) @@ -267,6 +268,7 @@ than one MIME-type database; it provides an interface similar to the one of the .. deprecated-removed:: 3.16 3.21 Passing a file path (or path-like object) instead of a URL. Use :func:`guess_file_type` instead. + Soft deprecated since version 3.13. .. method:: MimeTypes.guess_file_type(path, *, strict=True) From 586ffdb7b406c3c00af991de1fdf9fe5bbfc1ea7 Mon Sep 17 00:00:00 2001 From: Stephen Rosen Date: Thu, 26 Nov 2026 17:52:09 -0600 Subject: [PATCH 4/9] Revert unnecessary changes in test_mimetypes --- Lib/test/test_mimetypes.py | 5 ----- 1 file changed, 5 deletions(-) diff --git a/Lib/test/test_mimetypes.py b/Lib/test/test_mimetypes.py index 11fe784e0b8be54..41532fc71bf2e0d 100644 --- a/Lib/test/test_mimetypes.py +++ b/Lib/test/test_mimetypes.py @@ -3,9 +3,7 @@ import os import shlex import sys -import unittest import unittest.mock - from platform import win32_edition from test import support from test.support import cpython_only, force_not_colorized, os_helper, requires_subprocess @@ -545,9 +543,6 @@ def test_keywords_args_api(self): type='image/jpeg', strict=True), ['.jpg', '.jpe', '.jpeg']) - - - @unittest.skipUnless(sys.platform.startswith("win"), "Windows only") class Win32MimeTypesTestCase(unittest.TestCase): def setUp(self): From 48aabd7d5eda20bb4e31638799ce7689a2a41431 Mon Sep 17 00:00:00 2001 From: Stephen Rosen Date: Thu, 26 Nov 2026 20:13:29 -0600 Subject: [PATCH 5/9] Fix lazy import test for mimetypes --- Lib/test/test_mimetypes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/test/test_mimetypes.py b/Lib/test/test_mimetypes.py index 41532fc71bf2e0d..b7c0057be55ed32 100644 --- a/Lib/test/test_mimetypes.py +++ b/Lib/test/test_mimetypes.py @@ -593,7 +593,7 @@ def test__all__(self): @cpython_only def test_lazy_import(self): - ensure_lazy_imports("mimetypes", {"os", "posixpath", "urllib.parse", "argparse"}) + ensure_lazy_imports("mimetypes", {"urllib.parse", "argparse", "warnings"}) class CommandLineTest(unittest.TestCase): From 9652321e319475b85395833758a92e87958770bb Mon Sep 17 00:00:00 2001 From: Stephen Rosen Date: Fri, 27 Nov 2026 13:29:14 -0600 Subject: [PATCH 6/9] Apply review suggestions Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com> Co-authored-by: Stan Ulbrych <89152624+StanFromIreland@users.noreply.github.com> --- Doc/deprecations/pending-removal-in-3.21.rst | 6 ++++++ Doc/deprecations/pending-removal-in-future.rst | 4 ---- Doc/library/mimetypes.rst | 4 ++-- Lib/mimetypes.py | 10 +++++----- 4 files changed, 13 insertions(+), 11 deletions(-) diff --git a/Doc/deprecations/pending-removal-in-3.21.rst b/Doc/deprecations/pending-removal-in-3.21.rst index c85f170e3d3f948..2ee6346a8049d24 100644 --- a/Doc/deprecations/pending-removal-in-3.21.rst +++ b/Doc/deprecations/pending-removal-in-3.21.rst @@ -27,6 +27,12 @@ Pending removal in Python 3.21 parameter or pass the dispatch type explicitly instead. (Contributed by Bartosz Sławecki in :gh:`143465`.) +* :mod:`mimetypes`: + + * Passing a file path (including path-like objects and bytes paths) to + :func:`~mimetypes.guess_type`. Use :func:`~mimetypes.guess_file_type` + instead. + * :mod:`struct`: * Soft-deprecated since Python 3.15, using ``'F'`` and ``'D'`` type codes are now diff --git a/Doc/deprecations/pending-removal-in-future.rst b/Doc/deprecations/pending-removal-in-future.rst index e3315febd3976ee..6f372275225669d 100644 --- a/Doc/deprecations/pending-removal-in-future.rst +++ b/Doc/deprecations/pending-removal-in-future.rst @@ -71,10 +71,6 @@ although there is currently no date scheduled for their removal. * :mod:`mailbox`: Use of StringIO input and text mode is deprecated, use BytesIO and binary mode instead. -* :mod:`mimetypes`: Passing a file path (including path-like objects and bytes - paths) to :func:`~mimetypes.guess_type`. Use - :func:`~mimetypes.guess_file_type` instead. (:gh:`151575`) - * :mod:`os`: Calling :func:`os.register_at_fork` in a multi-threaded process. * :mod:`os.path`: :func:`os.path.commonprefix` is deprecated, use diff --git a/Doc/library/mimetypes.rst b/Doc/library/mimetypes.rst index 837ecf913e1009a..619fed834e74d73 100644 --- a/Doc/library/mimetypes.rst +++ b/Doc/library/mimetypes.rst @@ -56,7 +56,7 @@ the information :func:`init` sets up. .. deprecated-removed:: 3.16 3.21 Passing a file path (or path-like object) instead of a URL. Use :func:`guess_file_type` instead. - Soft deprecated since version 3.13. + This has been soft deprecated since version 3.13. .. function:: guess_file_type(path, *, strict=True) @@ -268,7 +268,7 @@ than one MIME-type database; it provides an interface similar to the one of the .. deprecated-removed:: 3.16 3.21 Passing a file path (or path-like object) instead of a URL. Use :func:`guess_file_type` instead. - Soft deprecated since version 3.13. + This has been soft deprecated since version 3.13. .. method:: MimeTypes.guess_file_type(path, *, strict=True) diff --git a/Lib/mimetypes.py b/Lib/mimetypes.py index ed90c0e4fd494fa..13cc8d27277b600 100644 --- a/Lib/mimetypes.py +++ b/Lib/mimetypes.py @@ -24,8 +24,8 @@ """ import sys -import os -import posixpath +lazy import os +lazy import posixpath lazy import urllib.parse lazy import warnings lazy from argparse import ArgumentParser @@ -145,11 +145,11 @@ def guess_type(self, url, strict=True): scheme = p.scheme url = p.path else: - warnings.warn( + warnings._deprecated( "Passing a file path to guess_type() is deprecated and will be " "removed in a future version. Use guess_file_type() instead.", - DeprecationWarning, - stacklevel=2, + remove=(3, 21), + stacklevel=4, ) return self.guess_file_type(url, strict=strict) if scheme == 'data': From 426bb6ca8004ffc73107e8ec479a0b11b0ed07cd Mon Sep 17 00:00:00 2001 From: Stephen Rosen Date: Fri, 27 Nov 2026 13:36:32 -0600 Subject: [PATCH 7/9] Add a test case for mimetypes checking file URLs Add two checks for file URLs, and remove a vestigial line from a nearby test. --- Lib/test/test_mimetypes.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Lib/test/test_mimetypes.py b/Lib/test/test_mimetypes.py index b7c0057be55ed32..a3092489cb9f662 100644 --- a/Lib/test/test_mimetypes.py +++ b/Lib/test/test_mimetypes.py @@ -457,7 +457,6 @@ def test_filename_with_url_delimiters(self): eq(self.db.guess_type(r'scheme:foo\.tar.gz'), gzip_expected) def test_url(self): - result = self.db.guess_type('http://example.com/host.html') result = self.db.guess_type('http://host.html') msg = 'URL only has a host name, not a file' self.assertSequenceEqual(result, (None, None), msg) @@ -469,6 +468,13 @@ def test_url(self): result = self.db.guess_type('http://example.com/host.html?q=x.tar') self.assertSequenceEqual(result, ('text/html', None)) + def test_file_url(self): + result = self.db.guess_type('file:///a/b/c/file.txt') + self.assertSequenceEqual(result, ('text/plain', None)) + # a local path URL which looks a bit like a netloc + result = self.db.guess_type('file:///host.html') + self.assertSequenceEqual(result, ('text/html', None)) + def test_guess_all_types(self): # First try strict. Use a set here for testing the results because if # test_urllib2 is run before test_mimetypes, global state is modified From f9b213ef889bf2dd91b32aa66443db7ac2a21c01 Mon Sep 17 00:00:00 2001 From: Stephen Rosen Date: Mon, 30 Nov 2026 09:40:21 -0600 Subject: [PATCH 8/9] Apply batched suggestions from code review Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com> --- Lib/mimetypes.py | 6 ++++-- .../2026-06-17-09-45-00.gh-issue-151575.mimetype.rst | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/Lib/mimetypes.py b/Lib/mimetypes.py index 13cc8d27277b600..13ff48dbe5ee90b 100644 --- a/Lib/mimetypes.py +++ b/Lib/mimetypes.py @@ -146,8 +146,10 @@ def guess_type(self, url, strict=True): url = p.path else: warnings._deprecated( - "Passing a file path to guess_type() is deprecated and will be " - "removed in a future version. Use guess_file_type() instead.", + "mimetypes.guess_type() with a file path", + "Passing a file path to guess_type() is deprecated " + "and will be removed in Python {remove}. " + "Use guess_file_type() instead.", remove=(3, 21), stacklevel=4, ) diff --git a/Misc/NEWS.d/next/Library/2026-06-17-09-45-00.gh-issue-151575.mimetype.rst b/Misc/NEWS.d/next/Library/2026-06-17-09-45-00.gh-issue-151575.mimetype.rst index 8bb01faf719903f..efa70b93a561bcf 100644 --- a/Misc/NEWS.d/next/Library/2026-06-17-09-45-00.gh-issue-151575.mimetype.rst +++ b/Misc/NEWS.d/next/Library/2026-06-17-09-45-00.gh-issue-151575.mimetype.rst @@ -1 +1 @@ -Deprecate passing a file path to :func:`mimetypes.guess_type`. Use :func:`mimetypes.guess_file_type` instead. +Deprecate passing a file path to :func:`mimetypes.guess_type`. Use :func:`mimetypes.guess_file_type` instead. Patch by Stephen Rosen. From e0512a6d4a2e5505e10cc0585bcd647e80a6e6e4 Mon Sep 17 00:00:00 2001 From: Stephen Rosen Date: Mon, 30 Nov 2026 15:45:24 -0600 Subject: [PATCH 9/9] Use skip_file_prefixes for guess_type() deprecation `mimetypes.guess_type()` wraps `mimetypes.MimeType.guess_type()`, and we want an appropriate warning emitted for both callpaths. However, the stack depth is different for these two cases. In order to get appropriate warnings, pass `skip_file_prefixes` to skip the `mimetypes` module and `stacklevel=1` to force the warning to be emitted at the level of the caller into `mimetypes`. This requires `warnings._deprecated` to gain support for `skip_file_prefixes` as a passthrough argument for `warn()`. --- Lib/_py_warnings.py | 5 +++-- Lib/mimetypes.py | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/Lib/_py_warnings.py b/Lib/_py_warnings.py index c82d3a21981d0f0..e336a49d0e91dbd 100644 --- a/Lib/_py_warnings.py +++ b/Lib/_py_warnings.py @@ -874,7 +874,7 @@ def wrapper(*args, **kwargs): def _deprecated(name, message=_DEPRECATED_MSG, *, remove, _version=sys.version_info, - stacklevel=3): + stacklevel=3, skip_file_prefixes=()): """Warn that *name* is deprecated or should be removed. RuntimeError is raised if *remove* specifies a major/minor tuple older than @@ -890,7 +890,8 @@ def _deprecated(name, message=_DEPRECATED_MSG, *, remove, _version=sys.version_i raise RuntimeError(msg) else: msg = message.format(name=name, remove=remove_formatted) - _wm.warn(msg, DeprecationWarning, stacklevel=stacklevel) + _wm.warn(msg, DeprecationWarning, stacklevel=stacklevel, + skip_file_prefixes=skip_file_prefixes) # Private utility function called by _PyErr_WarnUnawaitedCoroutine diff --git a/Lib/mimetypes.py b/Lib/mimetypes.py index 13ff48dbe5ee90b..d5d892f870869df 100644 --- a/Lib/mimetypes.py +++ b/Lib/mimetypes.py @@ -151,7 +151,8 @@ def guess_type(self, url, strict=True): "and will be removed in Python {remove}. " "Use guess_file_type() instead.", remove=(3, 21), - stacklevel=4, + stacklevel=1, + skip_file_prefixes=(__file__,) ) return self.guess_file_type(url, strict=strict) if scheme == 'data':