Intercepting binding?

Carl Banks pavlovevidence at gmail.com
Thu Sep 24 13:12:24 CEST 2009


On Sep 23, 5:49 pm, "Rhodri James" <rho... at wildebst.demon.co.uk>
wrote:
> On Thu, 24 Sep 2009 01:34:35 +0100, andrew cooke <and... at acooke.org> wrote:
>
> > For example, I assume it's possible to somehow access the dictionary
> > for the current block, but I can't see how to do this after
> > assignment.  If I do it in the Foo constructor, for example, "a" will
> > not yet be bound.
>
> I apologise for failing to notice earlier that you know what you're
> talking about.  I blame the hour :-)
>
> I'm not sure you can access the namespace dictionary of the "current
> block" (module?), that's the problem.  Oh, except via locals(), which
> might do exactly what you're after depending.  Excuse me, I'm being
> very dim tonight.


Hmmm.


@contextlib.contextmanager
def capture_changed_bindings():
    before = sys._getframe(2).f_locals.copy()
    changed = {}
    yield changed
    after = sys._getframe(2).f_locals
    for key,value in after.iteritems():
        if value is changed:
            continue
        if key not in before or value is not before[key]:
            changed[key] = value

def test():
    a = 2
    b = 3
    c = 4
    with capture_changed_bindings() as changed:
        b = 5
        c = 4
        d = 6
    print changed

test()


Quick and dirty, not robust at all.  But you get the idea.

Carl Banks



More information about the Python-list mailing list