Reputation: 491
I am trying to make a function that yields a value. Before anything could be done, I want to make sure function input is valid. Below code creates generator after execution. It raises exception only after next. Is there an elegant structure of the function which throws exception before next?
def foo(value):
if validate(value):
raise ValueError
yield 1
Upvotes: 3
Views: 362
Reputation: 17322
you can't check the value
before using next
, that is the whole point of using gnerators, from the docs:
Each yield temporarily suspends processing, remembering the location execution state (including local variables and pending try-statements). When the generator iterator resumes, it picks up where it left off (in contrast to functions which start fresh on every invocation).
what you can do it is to check the value before using the generator
Upvotes: 3