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

Alex Light scialexlight at gmail.com
Wed Jun 15 21:23:41 CEST 2011


Here is the source if anyone wants it.
--Alex
On Wed, Jun 15, 2011 at 3:04 PM, Terry Reedy <tjreedy at udel.edu> wrote:
> 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
>>> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110615/19cc4747/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: make_local.py
Type: application/octet-stream
Size: 1776 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110615/19cc4747/attachment.obj>


More information about the Python-ideas mailing list

AltStyle によって変換されたページ (->オリジナル) /