4

docsall相当于:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

那为什么我会得到这个输出:

# expecting: False

$ python -c "print( all( (isinstance('foo', int), int('foo')) ) )"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'foo'

什么时候:

# expecting: False

$ python -c "print( isinstance('foo', int) )"
False
4

4 回答 4

7

获得所需行为的一种(相当难看的)方法是通过 lambdas:

all(f() for f in (lambda: isinstance('foo', int), lambda: int('foo')))
于 2013-06-28T14:29:17.573 回答
5

在调用函数之前评估参数。在这种情况下,首先您必须创建传递给的元组all

all从来没有机会检查它们,在此之前引发了异常。

>>> int('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'foo'
于 2013-06-28T14:21:00.127 回答
2

你的直觉all是正确的;您只需要更加努力地设置一个惰性序列。例如:

def lazy():
    yield isinstance("foo", int)   # False
    yield int("foo")               # raises an error, but we won't get here

>>> all(lazy())
False
>>> list(lazy())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in lazy
ValueError: invalid literal for int() with base 10: 'foo'
于 2013-06-28T14:59:36.030 回答
1

如果在第一个条件之后停止评估的愿望False是专门执行类型检查,那么这样的事情会更好:

if not isinstance(other, MyClass):
    return False
else:
    return all((self.attr1 == other.attr2,
                self.attr2 == other.attr2)) # etc.

@catchmeifyoutry的简化版本:

return isinstance(other, MyClass) and all((self.attr1 == other.attr2,
                                           self.attr2 == other.attr2)) # etc.
于 2013-06-28T14:33:24.607 回答