Make Python's `warnings.warn()` not mention itself

后端 未结 3 667
遇见更好的自我
遇见更好的自我 2021-01-11 22:13

My minimum example is

#!/usr/bin/python3

import warnings

warnings.warn(\'Run Forest run!\', stacklevel=2)
warnings.warn(\'Run Forest run!\')
3条回答
  •  一向
    一向 (楼主)
    2021-01-11 22:24

    The reason you are getting the "redundant" line is because if you don't provide the stacklevel parameter the default stacklevel is 1, which is basically telling the user the exact line of code that the warning originated from, which is your warning function call warnings.warn('Run Forest Run!').

    If you're not happy with the way it functions, you can use the warnings.warn_explicit() function to customise it.

    https://docs.python.org/3.1/library/warnings.html#available-functions

提交回复
热议问题