iter函数返回一个迭代器对象。第一个参数的含义取决于第二个参数是否存在。如果没有第二个参数,参数o必须是collection对象或是支持sequence协议。否则会引起TypeError错误。如果存在第二个参数,该参数是哨兵,那么参数o必须是可调用对象。这种情况下,当每次调用next方法时,迭代器都会不调用o,直到遇见哨兵,触发StopIteration。
iter(o[, sentinel])
Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, o must be a collection object which supports the iteration protocol (the __iter__() method), or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then o must be a callable object. The iterator created in this case will call o with no arguments for each call to its next()method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.
第二种方式下,一个比较有用的应用是,读取一个文件的内容,直到遇到特定的行。下面的例子读取文件直到遇到空字符串:
One useful application of the second form of iter() is to read lines of a file until a certain line is reached. The following example reads a file until the readline() method returns an empty string:
with open('mydata.txt') as fp:
for line in iter(fp.readline, ''):
process_line(line)
该用法在Swift中也有体现,源码如下:
#返回一个函数
def _make_timeout_reader(self, file_like):
def timeout_reader():
with ChunkReadTimeout(self.client_timeout):
return file_like.read(self.network_chunk_size)
return timeout_reader
timeout_reader = self._make_timeout_reader(obj_input)
try:
#这里面用了一个iter的方式来迭代IO数据,感觉很巧妙,见python API文档中关于iter的介绍
#iter的第一个参数是一个可调用的对象或函数,第二个参数是哨兵
#通过for循环,每次迭代调用可调用的对象或函数,直到遇到哨兵为止
for chunk in iter(timeout_reader, ''):
start_time = time.time()
if start_time > upload_expiration:
self.logger.increment('PUT.timeouts')
return HTTPRequestTimeout(request=request)
etag.update(chunk)
upload_size = writer.write(chunk)
elapsed_time += time.time() - start_time
except ChunkReadError:
return HTTPClientDisconnect(request=request)
except ChunkReadTimeout:
return HTTPRequestTimeout(request=request)