Custom warnings in Python

Angwalt
2 min readMar 7, 2021

--

As it turns out creating a Custom warning in Python is just as easy as creating a Custom exception.

The classes you need to be familiar with at least to simply get started are Warning, UserWarning and warnings.

If all you require is to control the generated warnings for example how they are represented as often the default string representation is as follows:

<ipython-input-8-de78e3ed91ab>:14: customWarning: 'Custom Warning

Where the default format is:

file_name_where_warning_occured:line_no_in_file_name:warning_category:warning_message

If you simply want to change this then all you have to do is override the .formatwarning() method from the warnings class(or set it to a custom method) and this will change.

If you want to output the warning to some kind of log file utilize the .showwarning() method from the warnings class that will represent the warning as stipulated by .formatwarning().

def warning_formatter(msg, category, filename, lineno,   line=None):
return 'Custom formatting'
warnings.formatwarning = warning_formatterwarnings.warn('Message')//returns 'Custom formatting' for every warning issued

Moreover, if you want to control warnings in terms of ignoring others, showing an error only once if it appears multiple times, always showing when a certain warning category is issued ,or elevating others to full-blown exceptions that disrupt the execution of your program among other options, this is also a job for the warnings class. You can utilize the handy warnings.simplefilter() method using the 1st parameter in [‘error’, ‘ignore’, ‘default’, ‘module’, ‘always’, ‘once’] to control how all warnings are dealt with or using a second parameter Category in order to only have the simplefilter() method controls only some warnings. For example:

warnings.simplefilter("ignore",customWarning)

It is also worth noting the handy context manager warnings.catchwarnings() that can temporarily change the default control of how warnings are dealt with then revert back automatically. To learn more about this check out the official documentation here.

And in order to create and issue your own warnings you can create a custom warning by extending either the Warning or UserWarning class whereby it is worth noting that the UserWarning class inherits from the Warning class but to display the warning you will use the warnings.warn() or warnings.warn_explicitly() method

There might seem to be some confusion but as long as you remember that the Warning class is inherited from in order to create custom warning classes while the control of an issued warning is done using the warnings class, you need not have any issues.

import warningsclass customWarning(Warning):
def __init__(self, message):
self.message = message
def __str__(self):
return repr(self.message)
if True:
warnings.warn('Custom Warning',customWarning)

It is also worth noting that if all you want is just to show a warning in your code and not necessarily create one. You can use the warnings.warn() method with one parameter which will serve as the message from the warning and Python will use the UserWarning class as the warning category explicitly.

if True:
warnings.warn('Custom Warning')

--

--