demandimport: define a `deactivated` context manager
authorJordi Gutiérrez Hermoso <jordigh@octave.org>
Thu, 28 May 2015 16:11:26 -0400
changeset 25327 2e7804110b14
parent 25326 238e5cd94bbc
child 25328 2cfb0bbf83a1
demandimport: define a `deactivated` context manager This can be useful for use in "with" blocks for temporarily disabling demandimport.
mercurial/demandimport.py
--- a/mercurial/demandimport.py	Thu May 28 14:14:11 2015 -0400
+++ b/mercurial/demandimport.py	Thu May 28 16:11:26 2015 -0400
@@ -25,6 +25,8 @@
 '''
 
 import __builtin__, os, sys
+from contextlib import contextmanager
+
 _origimport = __import__
 
 nothing = object()
@@ -179,3 +181,16 @@
 def disable():
     "disable global demand-loading of modules"
     __builtin__.__import__ = _origimport
+
+@contextmanager
+def deactivated():
+    "context manager for disabling demandimport in 'with' blocks"
+    demandenabled = isenabled()
+    if demandenabled:
+        disable()
+
+    try:
+        yield
+    finally:
+        if demandenabled:
+            enable()