Block-Local Variables using "with"

Gunter Henriksen gunterhenriksen at gmail.com
Thu May 14 17:40:27 EDT 2009


Presuming there is a reason to want block-local variables,
does this seem like a good way to do something like it?

@contextlib.contextmanager
def blocklocal(**kwargs):
    bl = type('', (object,), {})()
    for (k, v) in kwargs.items():
        bl.__setattr__(k, v)
    yield bl
    for k in bl.__dict__.copy():
        bl.__delattr__(k)

with blocklocal(a=12, b="hello") as bl:
    bl.c = "world"
    print(bl.a, bl.b, bl.c)

The "bl" variable would still be there but empty.
Are there cleaner ways? (without nested "def"s)



More information about the Python-list mailing list