Raising an exception in the caller's frame

Alex Martelli aleax at aleax.it
Fri Mar 21 10:11:44 CET 2003


Thomas Heller wrote:
   ...
> Hopefully I can explain it: check_result() is not the 'cause' of the
> error, it's purpose is simply to detect the error. The 'exception'
> really occurrs in dosomething().

Yes, your purpose is very clear to me and I agree there _should_
be a way to achieve it, but I can't think of one.


> The situation is similar to what is explained for the warn() function,
> see the stacklevel parameter.  Maybe I should look into the warnings
> module.

If you're satisfied with a warning, yes, but when you turn the
warning into an error the stacklevel doesn't seem to work, e.g.:

>>> import warnings as w
>>> class mywa(Warning, ValueError): pass
...
>>> w.filterwarnings('error', category=mywa)
>>> def checkeven(value):
...     if value%2: w.warn("Value not even", mywa, 2)
...     return value
...
>>> def somework(value):
...     return checkeven(value+1)
...
>>> somework(23)
24
>>> somework(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in somework
  File "<stdin>", line 2, in checkeven
  File "/usr/local/lib/python2.3/warnings.py", line 49, in warn
    warn_explicit(message, category, filename, lineno, module, registry)
  File "/usr/local/lib/python2.3/warnings.py", line 84, in warn_explicit
    raise message
__main__.mywa: Value not even
>>>


Alex





More information about the Python-list mailing list