On 09/18/2012 10:10 PM, porkfried wrote: > I want to define a 'with' command that makes entries > in dictionary available within the local scope, and > stores new local variables into that dictionary. The > original scope should be restored on exit, and called > functions should not see anything special. Can I do this?
No.* It is not possible to set locals by ways other than an assignment**, and it is certainly not possible to set locals in a scope other than the one you're in**. You should simply type out the dict's name. This is a lot clearer. If you want to minimize typing, you can give the variable a one-character name. Also, Python scope simply doesn't work like that. There is no block scope, only local (=function) scope, and global scope, with a dash of non-locals to spice things up a bit. > > my_dict = dict(a=1, b=2) > with MyScope(my_dict): > print "A", a, "B", b > x = 3 > print my_dict["x"] > print x # FAIL, unbound > *You could set global variables, and remove them on exit, but this is ugly for a number of reasons: this could overwrite existing globals if you're not very careful, called functions would see these globals, and they would also be exposed to other threads. **I believe there is actually a way to edit a caller's locals, but this is not documented, not portable across Python implementations and versions, and you couldn't create new locals like this, so it'd be fairly pointless here -- http://mail.python.org/mailman/listinfo/python-list