[PATCH 1 of 3] demandimport: define an importnow context manager

Pierre-Yves David pierre-yves.david at ens-lyon.org
Tue May 26 20:45:12 UTC 2015



On 05/26/2015 01:35 PM, Jordi Gutiérrez Hermoso wrote:
> # HG changeset patch
> # User Jordi Gutiérrez Hermoso <jordigh at octave.org>
> # Date 1432671771 14400
> #      Tue May 26 16:22:51 2015 -0400
> # Node ID ac165f67eab4ab8157f73ab229e80883d49fabe0
> # Parent  6ac860f700b5cfeda232d5305963047696b869ca
> demandimport: define an importnow context manager
>
> This can be useful for use in "with" blocks for temporarily disabling
> demandimport.
>
> diff --git a/mercurial/demandimport.py b/mercurial/demandimport.py
> --- a/mercurial/demandimport.py
> +++ b/mercurial/demandimport.py
> @@ -25,6 +25,8 @@ These imports will not be delayed:
>   '''
>
>   import __builtin__, os, sys
> +from contextlib import contextmanager
> +
>   _origimport = __import__
>
>   nothing = object()
> @@ -179,3 +181,14 @@ def enable():
>   def disable():
>       "disable global demand-loading of modules"
>       __builtin__.__import__ = _origimport
> +
> + at contextmanager
> +def importnow():

what about: nodemandimport?

> +    demandenabled = isenabled()
> +    if demandenabled:
> +        disable()
> +
> +    yield
> +
> +    if demandenabled:
> +        enable()

You want:

    try:
        yield
    finally:
        if demandenabled:
             enable()


otherwise you will fail to restore in case of error.

-- 
Pierre-Yves David



More information about the Mercurial-devel mailing list