Skip to content

Commit

Permalink
Improve import time of mimetypes: defer os, sys, posixpath
Browse files Browse the repository at this point in the history
  • Loading branch information
hugovk committed Nov 18, 2024
1 parent 12fc4fe commit e6e4752
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions Lib/mimetypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,6 @@
read_mime_types(file) -- parse one file, return a dictionary or None
"""

import os
import sys
import posixpath

try:
from _winapi import _mimetypes_read_windows_registry
except ImportError:
Expand Down Expand Up @@ -119,6 +115,7 @@ def guess_type(self, url, strict=True):
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).
Expand Down Expand Up @@ -148,13 +145,20 @@ def guess_type(self, url, strict=True):
if '=' in type or '/' not in type:
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 @@ -401,6 +405,9 @@ 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 @@ -639,6 +646,7 @@ def _default_mime_types():

def _main():
import getopt
import sys

USAGE = """\
Usage: mimetypes.py [options] type
Expand Down

0 comments on commit e6e4752

Please sign in to comment.