How to use a generator safely