No macros in Python
holger krekel
pyth at devel.trillke.net
Tue Dec 17 12:28:43 EST 2002
Michael Hudson wrote:
> jepler at unpythonic.net writes:
>
> > I'd rather just write 'with lock: suite'.
>
> Right. Here's a proposal:
>
> with <exp>:
> <suite>
>
> is equivalent to
>
> _x = <exp>
> _x.__enter__()
> try:
> <suite>
> finally:
> _x.__exit__()
I like the idea. but i wonder if these semantics couldn't
be wrapped into a generic python protocol (the ':' indentation operator)
instead of adding a new keyword. The basic idea is that you can omit
'with' and do
<exp>:
<suite>
which would still hold the exact same equivalence as above.
If the parser and the python grammar allows this construct
unambigously then the ':' + indented block would signal
the 'enter/exit' protocol.
with or without 'with', i wonder if allowing the <exp> part
to manipulate the execution namespaces (globals, locals) of
the <suite> wouldn't provide nice features, e.g.:
class myclass:
def some_method_which_uses_lots_of_attributes(self):
with my_exec_in(self):
# do lots of computations with attributes
#
# use name, email, value directly instead of
#
# self.name, self.email, self.value
return result
def some_const_method(self, *args):
with const_attr(self):
# as above but you can't modify self's name-bindings
for this to work the 'with' construct (or the ':' indentation operator)
would be equivalent to:
_x = <exp>
_x_entered = _x.__enter__()
try:
if _x_entered:
_g,_l = _x_entered
exec code_object(<suite>) in _g,_l
else:
<suite>
finally:
_x.__exit__()
i am not sure how these exec/code_object statements
are implementable, though.
just my 2 keyword-cents,
holger
More information about the Python-list
mailing list