Skip to content

Commit dc7a2b6

Browse files
authored
gh-118761: Improve import time of mimetypes (#126979)
1 parent bab4b04 commit dc7a2b6

File tree

2 files changed

+18
-6
lines changed

2 files changed

+18
-6
lines changed

Diff for: Lib/mimetypes.py

+16-6
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,6 @@
2323
read_mime_types(file) -- parse one file, return a dictionary or None
2424
"""
2525

26-
import os
27-
import sys
28-
import posixpath
29-
import urllib.parse
30-
3126
try:
3227
from _winapi import _mimetypes_read_windows_registry
3328
except ImportError:
@@ -119,6 +114,10 @@ def guess_type(self, url, strict=True):
119114
Optional 'strict' argument when False adds a bunch of commonly found,
120115
but non-standard types.
121116
"""
117+
# Lazy import to improve module import time
118+
import os
119+
import urllib.parse
120+
122121
# TODO: Deprecate accepting file paths (in particular path-like objects).
123122
url = os.fspath(url)
124123
p = urllib.parse.urlparse(url)
@@ -146,13 +145,20 @@ def guess_type(self, url, strict=True):
146145
if '=' in type or '/' not in type:
147146
type = 'text/plain'
148147
return type, None # never compressed, so encoding is None
148+
149+
# Lazy import to improve module import time
150+
import posixpath
151+
149152
return self._guess_file_type(url, strict, posixpath.splitext)
150153

151154
def guess_file_type(self, path, *, strict=True):
152155
"""Guess the type of a file based on its path.
153156
154157
Similar to guess_type(), but takes file path instead of URL.
155158
"""
159+
# Lazy import to improve module import time
160+
import os
161+
156162
path = os.fsdecode(path)
157163
path = os.path.splitdrive(path)[1]
158164
return self._guess_file_type(path, strict, os.path.splitext)
@@ -399,6 +405,9 @@ def init(files=None):
399405
else:
400406
db = _db
401407

408+
# Lazy import to improve module import time
409+
import os
410+
402411
for file in files:
403412
if os.path.isfile(file):
404413
db.read(file)
@@ -445,7 +454,7 @@ def _default_mime_types():
445454
}
446455

447456
# Before adding new types, make sure they are either registered with IANA,
448-
# at http://www.iana.org/assignments/media-types
457+
# at https://www.iana.org/assignments/media-types/media-types.xhtml
449458
# or extensions, i.e. using the x- prefix
450459

451460
# If you add to these, please keep them sorted by mime type.
@@ -646,6 +655,7 @@ def _default_mime_types():
646655

647656
def _main():
648657
import getopt
658+
import sys
649659

650660
USAGE = """\
651661
Usage: mimetypes.py [options] type
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve import time of :mod:`mimetypes` by around 11-16 times. Patch by Hugo
2+
van Kemenade.

0 commit comments

Comments
 (0)