What is the difference between warnings.warn() and logging.warn() in terms of what they do and how they should be used?
Besides the canonical explanation in official documentation
warnings.warn() in library code if the issue is avoidable and the client application should be modified to eliminate the warning
logging.warning() if there is nothing the client application can do about the situation, but the event should still be noted
It is also worth noting that, by default warnings.warn("same message")
will show up only once. That is a major noticeable difference. Quoted from official doc
Repetitions of a particular warning for the same source location are typically suppressed.
>>> import warnings
>>> warnings.warn("foo")
__main__:1: UserWarning: foo
>>> warnings.warn("foo")
>>> warnings.warn("foo")
>>>
>>> import logging
>>> logging.warn("bar")
WARNING:root:bar
>>> logging.warn("bar")
WARNING:root:bar
>>> logging.warn("bar")
WARNING:root:bar
>>>
>>>
>>> warnings.warn("fur")
__main__:1: UserWarning: fur
>>> warnings.warn("fur")
>>> warnings.warn("fur")
>>>