Introduce a new builtin exception, UnboundLocalError, raised when ceval.c
tries to retrieve or delete a local name that isn't bound to a value.
Currently raises NameError, which makes this behavior a FAQ since the same
error is raised for "missing" global names too: when the user has a global
of the same name as the unbound local, NameError makes no sense to them.
Even in the absence of shadowing, knowing whether a bogus name is local or
global is a real aid to quick understanding.
Example:
D:\src\PCbuild>type local.py
x = 42
def f():
print x
x = 13
return x
f()
D:\src\PCbuild>python local.py
Traceback (innermost last):
File "local.py", line 8, in ?
f()
File "local.py", line 4, in f
print x
UnboundLocalError: x
D:\src\PCbuild>
Note that UnboundLocalError is a subclass of NameError, for compatibility
with existing class-exception code that may be trying to catch this as a
NameError. Unfortunately, I see no way to make this wholly compatible
with -X (see comments in bltinmodule.c): under -X, [UnboundLocalError
is an alias for NameError --GvR].
[The ceval.c patch differs slightly from the second version that Tim
submitted; I decided not to raise UnboundLocalError for DELETE_NAME,
only for DELETE_LOCAL. DELETE_NAME is only generated at the module
level, and since at that level a NameError is raised for referencing
an undefined name, it should also be raised for deleting one.]
displays funny characters, like spaces or control characters, more
clearly (one of my pet peeves in error messages). Also only suppress
the filename if it is None; display it if it is '', since that would
be a genuine (illegal) filename passed in!
involve a filesystem path. To that end:
- Changed IOError to EnvironmentError and added a hack which checks
for arg of len 3. When constructed with a 3-tuple, the third item
is the filename and this is squirreled away in the `filename'
attribute. However, for in-place unpacking backwards
compatibility, self.args still only gets the first two items. Added
a __str__() which prints the filename if it is given.
- IOError now inherits from EnvironmentError
- New class OSError which also inherits from EnvironmentError and is
used by the posix module.
errors are handled (these gave ``TypeError: not enough arguments'').
Also changed its __str__() to correct a typo (missing self.) and
return str(self.msg) to ensure the result is always string.
Also changed the default __str__ to simply return str(self.args).