Skip to content
Open
6 changes: 6 additions & 0 deletions Doc/deprecations/pending-removal-in-3.21.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 9 additions & 5 deletions Doc/library/mimetypes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -54,9 +53,10 @@ 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.
This has been soft deprecated since version 3.13.


.. function:: guess_file_type(path, *, strict=True)
Expand Down Expand Up @@ -265,6 +265,10 @@ 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.
This has been soft deprecated since version 3.13.

.. method:: MimeTypes.guess_file_type(path, *, strict=True)

Expand Down
7 changes: 7 additions & 0 deletions Doc/whatsnew/3.16.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1378,6 +1378,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,
Expand Down
5 changes: 3 additions & 2 deletions Lib/_py_warnings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
40 changes: 21 additions & 19 deletions Lib/mimetypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@
"""

import sys
lazy import os
lazy import posixpath
lazy import urllib.parse
lazy import warnings
lazy from argparse import ArgumentParser


try:
from _winapi import _mimetypes_read_windows_registry
Expand Down Expand Up @@ -114,7 +120,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
Expand All @@ -132,17 +138,22 @@ 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

# 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:
warnings._deprecated(
"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=1,
skip_file_prefixes=(__file__,)
)
return self.guess_file_type(url, strict=strict)
if scheme == 'data':
# syntax of data URLs:
Expand All @@ -164,19 +175,13 @@ 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):
"""Guess the type of a file based on its path.

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)
Expand Down Expand Up @@ -436,9 +441,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)
Expand Down Expand Up @@ -726,8 +728,6 @@ def _default_mime_types():


def _parse_args(args):
from argparse import ArgumentParser

parser = ArgumentParser(
description='map filename extensions to MIME types',
)
Expand Down Expand Up @@ -761,7 +761,11 @@ def _main(args=None):
return results
else:
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:
Expand All @@ -770,8 +774,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))
51 changes: 33 additions & 18 deletions Lib/test/test_mimetypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,14 +277,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):
Expand Down Expand Up @@ -434,25 +434,29 @@ 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):
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)
Expand All @@ -464,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
Expand Down Expand Up @@ -506,16 +517,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'),
Expand Down Expand Up @@ -555,9 +570,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, [])
Expand All @@ -584,7 +599,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):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Deprecate passing a file path to :func:`mimetypes.guess_type`. Use :func:`mimetypes.guess_file_type` instead. Patch by Stephen Rosen.
Loading