[Python-Dev] Python FAQ: Why doesn't Python have a "with" statement?

Cesare Di Mauro cesare at pronto.it
Thu Jun 19 06:58:07 CEST 2008


Very very, interesting. Thanks. :)

Somebody thinks that Python is unsuitable to implement a DSL: IMO your example prove the contrary. :D

Cesare

In data 16 giugno 2008 alle ore 01:12:46, Alex Martelli <aleaxit at gmail.com> ha scritto:

> +1 on updating the FAQ.  Maybe we could even have it notice that a
> read-only version of the desired semantic for 'with' is easily hacked
> with the *current* semantic of 'with'...:
>
> @contextlib.contextmanager
> def readonly(anobj):
>     caller_globals = sys._getframe(2).f_globals
>     saved_globals = caller_globals.copy()
>     caller_globals.update((n, getattr(anobj, n)) for n in dir(anobj))
>     yield
>     caller_globals.clear()
>     caller_globals.update(saved_globals)
>
> and then, of course,
>
> with readonly(someobj): ...
>
> (local variables take precedence, and in particular all assignments
> define local variables, as usual -- but you can say e.g. 'zz' to mean
> 'someobj.zz', if you're sufficiently keen on giving up the advantage
> of having many well-separated namespaces;-).
>
>
> Alex



More information about the Python-Dev mailing list