warnings.warn() vs. logging.warning()

后端 未结 4 1691
眼角桃花
眼角桃花 2020-12-13 11:38

What is the difference between warnings.warn() and logging.warn() in terms of what they do and how they should be used?

4条回答
  •  轮回少年
    2020-12-13 12:29

    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")
    >>>
    

提交回复
热议问题