Is there a way which I can return more information to the caller that instantiate the generator function than just the function instance itself?
For example,
def genFn(a, b, c):
# some initialisation / pre-computation
startPt = fn(a, b, c)
data = (yield None)
while True:
# perform some computation
data = (yield result)
f = genFn(5, 6, 7)
start = f.get("startPt") # this line syntax is wrong - just to show what I want
f.send(None)
for data in dataseries[startPt:]:
k = f.send(data)
...
Based on the passed-in parameter (a, b, c), the function has the logic to compute the earliest data it requires. I like to somehow be able to return this information “the earliest data it requires” back to the caller. Although I can certainly get the caller to compute and arrive at the same information – it is a duplication of effort and it isn’t elegant because I want to encapsulate the complexity in the generator function.
Thanks
T
You could return it as the currently unused return value of first
sendcall.By the way,
.send(None)is same as.next().Or you could use a class and use generator as one of its methods. The pre-computation would be done in
__init__and data could be accessed through instance attributes.Yet another idea is to use closures. Function call would return the generator and the start point, for example in a tuple.