Skip to Content
0 likes
Writing a Custom Iterator Class in Python With __iter__ and __next__ Level: Advanced

A for loop calls iter() once and next() until StopIteration. Write __iter__ and __next__ yourself, avoid the iterator that only works once, and know when a generator in __iter__ does the same job in fewer lines.

0 likes
Writing Your Own Python Context Manager, With a Class or contextlib Level: Advanced

Write a context manager when something must be undone no matter how the block ends. Build one as a class and with @contextmanager, keep yield inside try/finally, and don't swallow errors by accident.