Block-Local Variables using "with"

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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,818
Latest member
Brigette36

Latest Threads

Top