diff --git a/mercurial/util.py b/mercurial/util.py
index 908c5906091bf9a229be085a5752fc8b3604b78e_bWVyY3VyaWFsL3V0aWwucHk=..7f27e69dd27f2ab6d17c8a5b0589faa8840467c6_bWVyY3VyaWFsL3V0aWwucHk= 100644
--- a/mercurial/util.py
+++ b/mercurial/util.py
@@ -21,4 +21,10 @@
 # Python compatibility
 
 def sha1(s):
+    return _fastsha1(s)
+
+def _fastsha1(s):
+    # This function will import sha1 from hashlib or sha (whichever is
+    # available) and overwrite itself with it on the first call.
+    # Subsequent calls will go directly to the imported function.
     try:
@@ -24,5 +30,4 @@
     try:
-        import hashlib
-        _sha1 = hashlib.sha1
+        from hashlib import sha1 as _sha1
     except ImportError:
         from sha import sha as _sha1
@@ -27,7 +32,7 @@
     except ImportError:
         from sha import sha as _sha1
-    global sha1
-    sha1 = _sha1
+    global _fastsha1
+    _fastsha1 = _sha1
     return _sha1(s)
 
 import subprocess