[Python] ブロック・ローカルな変数

実装してみた。

from __future__ import with_statement
from contextlib import contextmanager
import inspect

@contextmanager
def lexical_scope(*args):
    frame = inspect.currentframe().f_back.f_back
    saved = frame.f_locals.keys()
    try:
        if not args: yield
        elif len(args) == 1: yield args[0]
        else: yield args
    finally:
        f_locals = frame.f_locals
        for key in (x for x in f_locals.keys() if x not in saved):
            del f_locals[key]
        del frame


if __name__ == '__main__':

    with lexical_scope(1,2,3) as (a,b,c):
        d = 4
        print a,b,c,d

    # Check, there are no 'a', 'b', 'c' and 'd' variables.
    print dir()