G
Gunter Henriksen
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)
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)