]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
Use `lazy` imports in `collections` (gh-145054)
authorRaymond Hettinger <rhettinger@users.noreply.github.com>
Sat, 21 Feb 2026 14:14:53 +0000 (08:14 -0600)
committerGitHub <noreply@github.com>
Sat, 21 Feb 2026 14:14:53 +0000 (08:14 -0600)
Lib/collections/__init__.py

index 55ffc36ea5b0c70d0ad66b495f27a3ba89c9f4e0..2eee4c709555139eea22b376cdda6a50b696f6d0 100644 (file)
@@ -32,6 +32,8 @@ import sys as _sys
 _sys.modules['collections.abc'] = _collections_abc
 abc = _collections_abc
 
+lazy from copy import copy as _copy
+lazy from heapq import nlargest as _nlargest
 from itertools import chain as _chain
 from itertools import repeat as _repeat
 from itertools import starmap as _starmap
@@ -59,8 +61,6 @@ try:
 except ImportError:
     pass
 
-heapq = None  # Lazily imported
-
 
 ################################################################################
 ### OrderedDict
@@ -634,12 +634,7 @@ class Counter(dict):
         if n is None:
             return sorted(self.items(), key=_itemgetter(1), reverse=True)
 
-        # Lazy import to speedup Python startup time
-        global heapq
-        if heapq is None:
-            import heapq
-
-        return heapq.nlargest(n, self.items(), key=_itemgetter(1))
+        return _nlargest(n, self.items(), key=_itemgetter(1))
 
     def elements(self):
         '''Iterator over elements repeating each as many times as its count.
@@ -1249,11 +1244,10 @@ class UserDict(_collections_abc.MutableMapping):
     def copy(self):
         if self.__class__ is UserDict:
             return UserDict(self.data.copy())
-        import copy
         data = self.data
         try:
             self.data = {}
-            c = copy.copy(self)
+            c = _copy(self)
         finally:
             self.data = data
         c.update(self)