简体   繁体   English

python 中的 try-block 内的循环头

[英]Loop head inside try-block in python

I define an iterable like this:我定义了一个这样的迭代:

class MyClass:
    
    def __init__(self, arg):
        self.arg = arg
        
    def __iter__(self):       
        for item in self.arg:
            yield item

Unfortunately arg might be None .不幸的是arg可能是None I wonder how to catch this in style.我想知道如何在风格上抓住这一点。 I can do:我可以:

def __iter__(self):
    if self.arg is None:
        return
    for item in self.arg:
        yield item

But this does not comply with python's EAFP style.但这不符合python的EAFP风格。 Maybe this way:也许这样:

def __iter__(self):
    try:
        for item in self.arg:
            yield item
    except TypeError:
        return

But this seems dangerous to me.但这对我来说似乎很危险。 Actually, my loop is much more involved and I do not want any other TypeErrors to pass unnoticed.实际上,我的循环涉及更多,我不希望任何其他 TypeErrors 被忽视。 Can I restrict the try-block to the head of the loop?我可以将 try-block 限制在循环的开头吗?

This depends on whether you consider arg being None to be an error.这取决于您是否认为argNone是一个错误。

If it's a supported value that just means there's nothing to work on then checking for it and returning, as per your first solution, makes the most sense.如果它是一个受支持的值,这意味着没有什么可做的,那么根据您的第一个解决方案检查它并返回是最有意义的。

If it should never be None and someone passing that in is an error then just let the exception happen.如果它永远不应该是None并且有人传递它是一个错误,那么就让异常发生。 Or, my personal choice, check it and throw an exception in __init__ to say the caller passed an invalid argument.或者,我个人的选择,检查它并在__init__中抛出一个异常来说明调用者传递了一个无效的参数。 Exceptions happening earlier (at the time the invalid thing happened) feels better than them happening later once a bunch of other things are going on and it's harder to figure out.较早发生的异常(在无效的事情发生时)感觉比后来发生的要好,一旦发生了一堆其他事情并且更难弄清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM