[Python-ideas] 'Injecting' objects as function-local constants

Terry Reedy tjreedy at udel.edu
Wed Jun 15 21:04:03 CEST 2011


On 6/15/2011 11:48 AM, Alex Light wrote:

>     Alex Light dixit (2011-06-14, 13:44):
>
>      > >>>            frmglobals = func.__globals__.copy()
>      > >>>            func.__globals__.update(localArgs)
>      > >>>            ret= func(*args, **kwargs)
>      > >>>            func.__globals__.clear()
>      > >>>            func.__globals__.update(frmglobals)

>  >>>            frmglobals = func.__globals__.copy()
>  >>>            func.__globals__.update(localArgs)
>  >>>            ret= func(*args, **kwargs)
>  >>>            func.__globals__.clear()
>  >>>            func.__globals__.update(frmglobals)
>
> with this one:
>
>  >>>            with _modifyGlobals(func.__globals__, localArgs):
>  >>>                ret = func(*args, **kwargs)
>
> with  _modifyGlobals defined as:
>
>  >>>from contextlib import contextmanager
>  >>>
>  >>>@contextmanager
>  >>>def _modifyGlobals(glbls, additions):
>  >>>    frmglbls = glbls.copy()
>  >>>    try:
>  >>>        glbls.update(additions)
>  >>>        yield
>  >>>    finally:
>  >>>        glbls.clear()
>  >>>        glbls.update(frmglbls)

Posting code with all the '>>>' prompts added makes it terribly hard to 
cut and paste to try it out.

-- 
Terry Jan Reedy




More information about the Python-ideas mailing list