[Python-3000] self-contained exceptions
Greg Falcon
veloso at verylowsodium.com
Wed Jan 10 18:05:59 CET 2007
Well, now I have to delurk.
I've been watching with growing excitement. Between the changes to
the scope rules for list comprehensions, and this change for except
blocks, I wondered if Python might have been moving in the direction
of block scoped variables where appropriate as a philosophy.
I almost posted about this yesterday, but didn't. I thought that the
fact these two changes had to do with scope was pure coincidence.
(After all, one change is meant to add a symmetry to the language, and
one is meant to fix potential gc problems.)
But, on 1/10/07, Guido van Rossum <guido at python.org> wrote:
> BTW perhaps we should add the same semantics and syntax to 'with expr
> as var'? I can't think of a reasonable use case for keeping var alive
> after the with-statement terminates either. (Nor for using anything
> more complex than a local variable, BTW.)
+1, though I'm probably +1 for the wrong reasons. :) If it is
desirable for Python to delete local variables in the face of certain
syntactic constructs, then there simply does not exist a more
appropriate time to do so than 'with x as y'. (Before your post, I
thought the motivation of this proposal was "we'd rather not delete
this variable at all, but the user will create cycles if we don't, so
it's a necessary evil.")
I'm coming from a philosophy, though, that believes any time a
syntactic construct creates a local binding and a new suite to use it
in, the binding shouldn't escape that suite. Yes, I'm really talking
about 'for', and I know this is probably a controversial view. But
don't the same arguments apply? (It's probably an error to use the
variable outside the suite, and if you really need to, you could be
explicit and store another reference to it in a separate local.)
I'd also like to add that this "foo=none; del foo" approach to fake
block-scopes is clever, but probably deserves a bit of extra error
checking as well. Specifically, Python should generate a
SyntaxWarning whenever one of these block-scope constructs binds to a
local that was previously assigned to. I'm worried about this mistake
going unnoticed:
re = get_resource()
...
try:
something()
except RareException as re:
... # handle it
...
re.use_resource()
Which *appears* to work fine most of the time, but when the
RareException is raised and handled, suddenly the use_resource() line
generates a surprising UnboundLocalError. These are the sort of
things that should be caught ahead of time if possible.
Greg F
More information about the Python-3000
mailing list