How do I create user-defined warnings?

C

Clay Hobbs

I already know how to make user-defined exceptions, like this one:

class MyException(Exception):
pass

But for a module I'm making, I would like to make a warning (so it just
prints the warning to stderr and doesn't crash the program). I have
tried this:

class MyWarning(Warning):
pass

And it behaves like a normal error. Please help me, I can't figure out
what I'm doing wrong.
 
H

Hans Nowak

Clay said:
I already know how to make user-defined exceptions, like this one:

class MyException(Exception):
pass

But for a module I'm making, I would like to make a warning (so it just
prints the warning to stderr and doesn't crash the program). I have
tried this:

class MyWarning(Warning):
pass

And it behaves like a normal error. Please help me, I can't figure out
what I'm doing wrong.

Are you using the warning with 'raise'? Don't do that, use warnings.warn instead:

In [1]: import warnings

In [2]: class MyWarning(Warning): pass
...:

In [3]: warnings.warn(MyWarning("bah humbug"))
/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/IPython/FakeModule.py:1:
MyWarning: bah humbug
# -*- coding: utf-8 -*-
 

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

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top