[Python-3000] self-contained exceptions
Phillip J. Eby
pje at telecommunity.com
Wed Jan 10 18:57:23 CET 2007
At 12:05 PM 1/10/2007 -0500, Greg Falcon wrote:
>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.)
Breaking out of a loop with a found value is way too common a use case to
want to delete the iteration variable.
>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.
We could go even further, and say it's a syntax error to bind or refer to
<name> outside the except suite where it's bound, unless it's being used in
another except suite.
Or, we could look at it this way: "except <expr> as <tmpvar>" and "with
<expr> as <tmpvar> (,<tmpvar>)*", and say that a tmpvar is a normal local
variable, *except* that it may only be used within the block where it is
defined, or in another block that uses it as a <tmpvar>.
So, you can do as many "as" bindings of the same name as you want, but you
can't use that name for any "non-as" use.
We could also, for that matter, prohibit:
with x as y:
with z as y:
since when the inner block exits, y will no longer be bound.
But I'm not sure whether we really care about any of these points.
More information about the Python-3000
mailing list