Failing on string exceptions in 2.4

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Jun 15 03:22:27 CEST 2007


En Thu, 14 Jun 2007 18:45:08 -0300, Stephen R Laniel <steve at laniels.org>  
escribió:

> Reading the Python docs, it looks like string exceptions
> will be a DeprecationWarning in Python 2.5. Is there any way
> to make them so in 2.4? Now how about if I want to turn all
> DeprecationWarnings into compile-time errors? Is there some
> way to do this?

Yes, using the warnings module.
First thing is to start Python using the -Wd argument so you can see ALL  
the warnings, even the supressed ones:

C:\temp>python24 -Wd

Then see what happens when you raise a string exception:

py> raise "Error"
__main__:1: PendingDeprecationWarning: raising a string exception is  
deprecated
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
Error

Now we know it is a PendingDeprecationWarning, and the message says  
"raising a string exception is deprecated"
With this information we can build a filter. Do this at startup of your  
program:

 from warnings import filterwarnings
filterwarnings(action="error", message="raising a string exception",  
category=PendingDeprecationWarning)

Or maybe, place it in sitecustomize.py.
Or, start Python using -W:

C:\temp>python24 -W "error:raising a string  
exception:PendingDeprecationWarning"
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on  
win32
Type "help", "copyright", "credits" or "license" for more information.
py> raise "Error"
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "c:\apps\python\lib\warnings.py", line 61, in warn
     warn_explicit(message, category, filename, lineno, module, registry,
   File "c:\apps\python\lib\warnings.py", line 96, in warn_explicit

PendingDeprecationWarning: raising a string exception is deprecated

(btw, the right format for the -W option isn't documented, or at least  
I've been unable to find it; each time I want to use -W I have to reread  
the warnings module source...)

> End goal being that string exceptions would cause
> compilation to fail. A few times now, I've found myself
> doing
>
> class SomeClass:
>     """docstring"""
>     pass
>
> raise SomeClass, "Some description"
>
> and I've gotten a weird compiler error about the constructor
> for SomeClass. I'd prefer it just to fail there and not let
> me raise an exception that isn't subclassed beneath
> Exception.

The compiler won't complain here - you will have to inspect the code (or  
use a tool like pylint or pychecker). The easy fix is just inherit from  
Exception.

-- 
Gabriel Genellina




More information about the Python-list mailing list