pythoniteratorscandir

Why does an iterator need to be exhausted and discarded?


scandir.close()

Close the iterator and free acquired resources.

This is called automatically when the iterator is exhausted or garbage collected, or when an error happens during iterating. However it is advisable to call it explicitly or use the with statement.

New in version 3.6.

Dears, I came across this paragraph. It gave me the impression that an iterator needed to be exhausted and discarded. Why so?


Solution

  • The Iterator object in the process of its work can acquire or create certain resources. This is file system handles in case of scandir.

    Therefore, it is desirable that it be exhausted because in this case it will be able to correctly and timely release these resources. But this is not necessary, sometimes there are situations when you need to interrupt the iterating. In this case, we must explicitly tell the object that we no longer want to iterate it and that it can free resources.

    It is better to do this explicitly than to rely on the garbage collector, this gives greater control over the program flow and can prevent you from unexpected errors.