Many times I have had a need to have a simple function do something different when first called. There are many reasons, but usually I would need a variable initialized differently if the first run through. Sometimes I could handle the problem outside the function or inside, but things could sometimes get messy, and I don't like to use "globals" if I can avoid them.
My solution came from generators. I found that I could "initialize" a function, or "prime" a function as I call it, by using a next() call in the program combined with a reveresed "yield" above a loop in the function. Works like a charm.
Now my question is: Is there a better way that I may be missing?
A WoNUX--working, but non-useful exammple:
o_PrintList = g_PrintThis() ## Creates func object
o_PrintList.next() ## 'Primes' the func
o_PrintList.send(9) ## Sends argument to the func
o_PrintList.send(10) ## Another argument to the func
def g_PrintThis():
v_PrintList = [] ## Inits the variable. If stnd func call this would happen everytime
print("Initialized")
v_Num = yield ## Waits for first send argument
while True: ## Infinite loop. Could be a for loop, etc.
v_PrintList.append(v_Num) ## Reason v_PrintList needs 'primed'
if not v_PrintList:
print("PrintList is empty:")
else:
print("Printlist: %s") %(v_PrintList)
v_Num = yield ## Waits for next send argument, if ever one comes
Thanks.