UnicodeError instead of UnicodeWarning

M

Michael Ströder

HI!

For tracking the cause of a UnicodeWarning I'd like to make the Python
interpreter to raise an UnicodeError exception with full stack trace. Is there
a short trick to achieve this?

Many thanks in advance.

Ciao, Michael.
 
C

Chris Rebert

2011/10/25 Michael Ströder said:
HI!

For tracking the cause of a UnicodeWarning I'd like to make the Python
interpreter to raise an UnicodeError exception with full stack trace. Is there
a short trick to achieve this?

from exceptions import UnicodeWarning
from warnings import filterwarnings
filterwarnings(action="error", category=UnicodeWarning)

This will cause UnicodeWarnings to be raised as exceptions when they occur.

Cheers,
Chris
 
P

Peter Otten

Michael said:
For tracking the cause of a UnicodeWarning I'd like to make the Python
interpreter to raise an UnicodeError exception with full stack trace. Is
there a short trick to achieve this?

You can control warning behaviour with the -W commandline option:

$ cat unicodewarning_demo.py
# -*- coding: utf-8 -*-

def g():
"ä" == u"ä"

def f(n=3):
if n:
f(n-1)
else:
g()

if __name__ == "__main__":
f()

$ python unicodewarning_demo.py
unicodewarning_demo.py:4: UnicodeWarning: Unicode equal comparison failed to
convert both arguments to Unicode - interpreting them as being unequal
"ä" == u"ä"
$ python -W error::UnicodeWarning unicodewarning_demo.py
Traceback (most recent call last):
File "unicodewarning_demo.py", line 13, in <module>
f()
File "unicodewarning_demo.py", line 8, in f
f(n-1)
File "unicodewarning_demo.py", line 8, in f
f(n-1)
File "unicodewarning_demo.py", line 8, in f
f(n-1)
File "unicodewarning_demo.py", line 10, in f
g()
File "unicodewarning_demo.py", line 4, in g
"ä" == u"ä"
UnicodeWarning: Unicode equal comparison failed to convert both arguments to
Unicode - interpreting them as being unequal
$
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,157
Messages
2,570,879
Members
47,413
Latest member
KeiraLight

Latest Threads

Top