import warnings
warnings.warn("Warning...........Message")

See the python documentation: here

Answer from necromancer on Stack Overflow
🌐
Python
docs.python.org › 3 › library › warnings.html
Warning control — Python 3.14.4 documentation
January 29, 2026 - Rules can be added to the filter by calling filterwarnings() and reset to its default state by calling resetwarnings(). The printing of warning messages is done by calling showwarning(), which may be overridden; the default implementation of ...
Discussions

python - Print only the message on warnings - Stack Overflow
0 Python - Replacing warnings with a simple message · 0 How to print only first occurrence of python warning? More on stackoverflow.com
🌐 stackoverflow.com
How to raise a warning in Python without interrupting execution? - Ask a Question - TestMu AI Community
How to Raise a Warning in Python Without Interrupting the Program? I’m trying to raise a warning in Python without causing the program to crash or interrupt its execution. Here is the simple function I’m using to check if the user passed a non-zero number. More on community.testmuai.com
🌐 community.testmuai.com
0
December 18, 2024
Python warning message output - Stack Overflow
Is there any way of getting rid of the first 3 lines of the output and only display "RuntimeWarning: Python 3.x is required!" ? ... You’ll notice that by default the warning message includes the source line that generated it, when available. It’s not all that useful to see the line of code ... More on stackoverflow.com
🌐 stackoverflow.com
Default warning formatting improvements - Ideas - Discussions on Python.org
Introduction Recent python versions have made some very nice improvements to the readability of exception messages. I think, that the current default warning formatting isn’t very good and could use some polish. Compare the current warning formatting: /usr/lib/python3.11/site-packages/th... More on discuss.python.org
🌐 discuss.python.org
11
May 25, 2022
🌐
GeeksforGeeks
geeksforgeeks.org › python › warnings-in-python
Warnings in Python - GeeksforGeeks
January 23, 2020 - The warn() function defined in the 'warning' module is used to show warning messages. The warning module is actually a subclass of Exception which is a built-in class in Python. ... # program to display warning a message import warnings ...
🌐
Python Module of the Week
pymotw.com › 2 › warnings
warnings – Non-fatal alerts - Python Module of the Week
So that when warn() is called, the warnings are emitted with the rest of the log messages. $ python warnings_showwarning.py WARNING:root:warnings_showwarning.py:24: UserWarning:This is a warning message
🌐
Coderz Column
coderzcolumn.com › tutorials › python › warnings-simple-guide-to-handle-warning-messages-in-python
warnings - Simple Guide to Handle Warning Messages in Python by Sunny Solanki
As a part of our sixth example, we'll demonstrate usage of formatwarning() method. This method has the same format and usage as that of showwarning()but it returns a warning message as a string instead of printing it.
🌐
Reuven Lerner
lerner.co.il › home › blog › python › working with warnings in python (or: when is an exception not an exception?)
Working with warnings in Python (Or: When is an exception not an exception?) — Reuven Lerner
May 12, 2020 - Let’s say that you want to warn the user about something. You can do so by importing the “warnings” module, and then by using “warnings.warn” to tell them what’s wrong: import warnings print('Hello') warnings.warn('I am a warning!') print('Goodbye')
Find elsewhere
🌐
TestMu AI Community
community.testmuai.com › ask a question
How to raise a warning in Python without interrupting execution? - Ask a Question - TestMu AI Community
December 18, 2024 - How to Raise a Warning in Python Without Interrupting the Program? I’m trying to raise a warning in Python without causing the program to crash or interrupt its execution. Here is the simple function I’m using to check…
🌐
Plain English
python.plainenglish.io › controlling-warning-messages-in-python-4ca7ed37ca94
Controlling Warning Messages in Python | Python in Plain English
October 27, 2024 - Any warnings triggered by the warnings.warn() function are now logged to the warnings.log file instead of being printed to the console.
🌐
W3Schools
w3schools.com › python › ref_module_warnings.asp
Python warnings Module
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... import warnings warnings.warn('This is a warning message') print('Program continues...') ...
🌐
LabEx
labex.io › tutorials › python-how-to-capture-python-runtime-warnings-425664
How to capture Python runtime warnings | LabEx
import warnings ## Filter specific custom warnings warnings.filterwarnings("error", category=LabExWarning) try: warnings.warn("Critical configuration", category=LabExWarning) except LabExWarning: print("Handled custom warning") ... By mastering warning customization, developers can create more informative and manageable Python applications with LabEx's advanced warning techniques.
🌐
Python.org
discuss.python.org › ideas
Default warning formatting improvements - Ideas - Discussions on Python.org
May 25, 2022 - Introduction Recent python versions have made some very nice improvements to the readability of exception messages. I think, that the current default warning formatting isn’t very good and could use some polish. Compare the current warning formatting: /usr/lib/python3.11/site-packages/the_package/the_module/the_file.py:6: SuperImportantWarning: The warning message is the most important part. warnings.warn( And exception formatting: Traceback (most recent call last): File "/usr/lib/pytho...
🌐
Python Module of the Week
pymotw.com › 3 › warnings
warnings — Non-fatal Alerts
import warnings warnings.simplefilter('error', UserWarning) print('Before the warning') warnings.warn('This is a warning message') print('After the warning') In this example, the simplefilter() function adds an entry to the internal filter list to tell the warnings module to raise an exception when a UserWarning warning is issued. $ python3 -u warnings_warn_raise.py Before the warning Traceback (most recent call last): File "warnings_warn_raise.py", line 15, in <module> warnings.warn('This is a warning message') UserWarning: This is a warning message
🌐
GitHub
github.com › PyTables › PyTables › issues › 992
Use python's warning system instead of printing to stderr · Issue #992 · PyTables/PyTables
January 6, 2023 - pytables is a library, as such it is very annoying that warnings are printed to stderr and not using the python standard warnings system. It makes it much harder to e.g. make tests fail for resourc...
Author   maxnoe
Top answer
1 of 5
12

The globals aren't doing much for you, so get rid of them.

Your code will not do the right thing if an argument fails to print: the colour will not be reset. Add a finally to handle this case.

You're too aggressive with your style reset. Just reset the fore colour and nothing else.

Add type hints.

am I horribly misusing *arg?

No, it's fine.

is it okay to use PASS as a variable, as lower-case pass is a reserved word?

Not really. The convention to get around keywords is an underscore suffix, as in pass_.

from typing import Any

import colorama


def print_colour(fore_colour: str, *text: Any) -> None:
    print(fore_colour, end='')
    try:
        print(*text, end='')
    finally:
        print(colorama.Fore.RESET)


def okay(*text: Any) -> None:
    print_colour(colorama.Fore.GREEN, *text)


def warn(*text: Any) -> None:
    print_colour(colorama.Fore.YELLOW, *text)


def fail(*text: Any) -> None:
    print_colour(colorama.Fore.RED, *text)


def test() -> None:
    class BadClass:
        def __str__(self):
            raise ValueError()

    try:
        fail(BadClass())
    except ValueError:
        pass

    print('Should be in default colour')

    warn("Unfragmented text")
    warn("Fragmented", "text")

    fail("Unfragmented text")
    fail("Fragmented", "text")

    okay("Unfragmented text")
    okay("Fragmented", "text")


if __name__ == '__main__':
    test()
2 of 5
7

am I horribly misusing *arg? I've never used it before, and so often stuff that just works can backfire in unexpected ways once I try to get it to do more.

I wouldn't say you are misusing it (though my preference would be to make the caller provide a sequence in every situation), but you are overusing it. Every one of your functions assumes it will receive at least one argument, so you should formalize that with a required first parameter.

For example,

def warn(first, *txt):
    a = list(txt)
    first = WARN + first
    a[-1] += WTXT
    print(first, *a)
🌐
Reddit
reddit.com › r/python › why is ´print´ not recommended in linters?
r/Python on Reddit: Why is ´print´ not recommended in linters?
December 4, 2023 -

I am writing a mini-program for basic payment calculation, and after the calculation the results are printed in the terminal. However, I get the following warnings from Ruff (the Python linter that I use):

src/pf_example/food_payment.py:39:5: T201 print found src/pf_example/food_payment.py:51:5: T201 print found src/pf_example/food_payment.py:52:5: T201 print found src/pf_example/food_payment.py:54:5: T201 print found src/pf_example/food_payment.py:56:9: T201 print found

I know that I can turn off this check in the settings, BUT I don't why print is bad in the code. What would be the alternatives if not using print?

Top answer
1 of 2
4

The reference manual is a great source. For the warnings module, it says:

The printing of warning messages is done by calling showwarning(), which may be overridden

And later:

warnings.showwarning(message, category, filename, lineno, file=None, line=None)

... You may replace this function with any callable by assigning to warnings.showwarning.

So just declare your own function special_showwarning with the same parameters, format the output the way you want and simply do: logging.showwarning = special_showwarning.


An equivalent way is possible for exception by overriding sys.excepthook:

sys.excepthook(type, value, traceback)

This function prints out a given traceback and exception to sys.stderr.

When an exception is raised and uncaught, the interpreter calls sys.excepthook with three arguments... The handling of such top-level exceptions can be customized by assigning another three-argument function to sys.excepthook.

Unfortunately, this may not work when executing python code in an IDE, for example IDLE uses a custom loop and does not call sys.excepthook. In that case, you could simply wrap your current main in a try block and catch anything. It is then easy to display what you want:

def main():
    # your code ...

if __name__ == '__main__':
    try:
        main()
    except:
        type, value, traceback = sys.exc_info()
        # add your error formatting here
2 of 2
1

If you change your source code slightly to a real life situation it becomes maybe clearer why the behavior is like this:

import warnings
warn = 'This is a warning'
exception = 'This is an exception'

def main():
    warnings.warn(warn)
    raise RuntimeError(exception)

if __name__=='__main__':
    main()

Now the output is:

test_exception.py:6: UserWarning: This is a warning
  warnings.warn(warn)
Traceback (most recent call last):
  File "C:\Users\11ldornbusch\Desktop\2del.py", line 10, in <module>
    main()
  File "C:\Users\11ldornbusch\Desktop\2del.py", line 7, in main
    raise RuntimeError(exception)
RuntimeError: This is an exception

So if you use variables your output shows in one line the content of the variable, and in the other the name. This can give you more context on what the problem is, for example a "Nothing" as output will gives you also the name of the variable which is nothing.

You can also use logging or Hook the output in python to modify the output of the warning: From the documentation available here: https://docs.python.org/3/library/warnings.html

The printing of warning messages is done by calling showwarning(), which may be overridden; the default implementation of this function formats the message by calling formatwarning(), which is also available for use by custom implementations.