diff --git a/mercurial/encoding.py b/mercurial/encoding.py
--- a/mercurial/encoding.py
+++ b/mercurial/encoding.py
@@ -25,6 +25,7 @@
         Any,
         Callable,
         List,
+        TYPE_CHECKING,
         Text,
         Type,
         TypeVar,
@@ -32,7 +33,7 @@
     )
 
     # keep pyflakes happy
-    for t in (Any, Callable, List, Text, Type, Union):
+    for t in (Any, Callable, List, Text, Type, Union, TYPE_CHECKING):
         assert t
 
     _Tlocalstr = TypeVar('_Tlocalstr', bound=localstr)
@@ -265,16 +266,20 @@
     strfromlocal = unifromlocal
     strmethod = unimethod
 else:
+    strtolocal = pycompat.identity
+    strfromlocal = pycompat.identity
+    strmethod = pycompat.identity
 
-    def strtolocal(s):
-        # type: (str) -> bytes
-        return s
+    if 'TYPE_CHECKING' in globals() and TYPE_CHECKING:
 
-    def strfromlocal(s):
-        # type: (bytes) -> str
-        return s
+        def strtolocal(s):
+            # type: (str) -> bytes
+            return s
 
-    strmethod = pycompat.identity
+        def strfromlocal(s):
+            # type: (bytes) -> str
+            return s
+
 
 if not _nativeenviron:
     # now encoding and helper functions are available, recreate the environ