Skip to content

Commit aa3f419

Browse files
authored
gh-109653: Improve the import time of email.utils (#109824)
1 parent e733136 commit aa3f419

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed

Lib/email/utils.py

+7-5
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,6 @@
2525
import os
2626
import re
2727
import time
28-
import random
29-
import socket
3028
import datetime
3129
import urllib.parse
3230

@@ -36,9 +34,6 @@
3634

3735
from email._parseaddr import parsedate, parsedate_tz, _parsedate_tz
3836

39-
# Intrapackage imports
40-
from email.charset import Charset
41-
4237
COMMASPACE = ', '
4338
EMPTYSTRING = ''
4439
UEMPTYSTRING = ''
@@ -94,6 +89,8 @@ def formataddr(pair, charset='utf-8'):
9489
name.encode('ascii')
9590
except UnicodeEncodeError:
9691
if isinstance(charset, str):
92+
# lazy import to improve module import time
93+
from email.charset import Charset
9794
charset = Charset(charset)
9895
encoded_name = charset.header_encode(name)
9996
return "%s <%s>" % (encoded_name, address)
@@ -181,6 +178,11 @@ def make_msgid(idstring=None, domain=None):
181178
portion of the message id after the '@'. It defaults to the locally
182179
defined hostname.
183180
"""
181+
# Lazy imports to speedup module import time
182+
# (no other functions in email.utils need these modules)
183+
import random
184+
import socket
185+
184186
timeval = int(time.time()*100)
185187
pid = os.getpid()
186188
randint = random.getrandbits(64)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Reduce the import time of :mod:`email.utils` by around 43%. This results in
2+
the import time of :mod:`email.message` falling by around 18%, which in turn
3+
reduces the import time of :mod:`importlib.metadata` by around 6%. Patch by
4+
Alex Waygood.

0 commit comments

Comments
 (0)