【问题标题】:Skip to the next iteration if a warning is raised如果发出警告,则跳至下一次迭代
【发布时间】:2023-02-14 00:34:28
【问题描述】:

如果发出警告,如何跳过迭代

假设我有下面的代码

import warnings

# The function that might raise a warning
def my_func(x):
    if x % 2 != 0:
        warnings.warn("This is a warning")
        return "Problem"     
    else:
        return "No Problem"
        

for i in range(10):
    try:
        # code that may raise a warning
        k = my_func(i)
    except Warning:
        # skip to the next iteration if a warning is raised
        continue
        
    # rest of the code
    print(i, " : ",k) # Only print this if warning was not raised in try:except

我希望它只打印偶数,因为 my_funct(i) 会对奇数发出警告

【问题讨论】:

标签: python


【解决方案1】:

而不是使用 warn 函数抛出一个 except 将检测到的警告对象。

代码:

import warnings

# The function that might raise a warning
def my_func(x):
    if x % 2 != 0:
        raise Warning('This is a warming')
    else:
        return "No Problem"
    

for i in range(10):
    try:
        # code that may raise a warning
        k = my_func(i)
    except Warning:
        continue
    print(i, " : ",k) 

输出:

0 : No Problem
2 : No Problem
4 : No Problem
6 : No Problem
8 : No Problem

【讨论】:

    【解决方案2】:

    默认情况下,警告不会抛出异常。 您可以指定警告以引发异常。 导入后立即运行

    warnings.simplefilter("error")
    

    或者,您可以只检查函数的结果。检查结果是“有问题”还是“没问题”。

    for i in range(10):
        k = my_func(i)
        if k == "Problem":
            continue
            
        # rest of the code
        print(i, " : ",k)
    

    【讨论】:

      猜你喜欢
      • 2021-04-26
      • 2017-10-05
      • 2010-10-03
      • 2020-11-20
      • 2015-11-11
      • 2014-01-07
      • 1970-01-01
      • 2013-10-03
      • 2021-10-26
      相关资源
      最近更新 更多