python - using function attributes to store results for lazy (potential) processing -
i'm doing collision detection , use same function in 2 different contexts. in 1 context, like
def detect_collisions(item, others): return any(collides(item, other) other in others)
and in another, be
def get_collisions(item, others): return [other other in others if collides(item, other)]
i hate idea of writing 2 functions here. keeping names straight 1 turnoff , complicating interface collision detecting another. thinking:
def peek(gen): try: first = next(gen) except stopiteration: return false else: return it.chain((first,), gen) def get_collisions(item, others): get_collisions.all = peek(other other in others if collides(item, other)) return get_collisions.all
now when want check, can say:
if get_collisions(item, others): # aw snap
or
if not get_collisions(item, others): # w00t
and in other context want examine them, can do:
if get_collisions(item, others): collision in get_collisions.all: # fix
and in both cases, don't more processing need to.
i recognize more code first 2 functions has advantage of:
keeping interface collision detection tree node @ top level instead of mid level. seems simpler.
hooking myself handy peek function. if use 1 other time, i'm writing less code. (in response yagni, if have it, will)
so. if proverbial homicidal maniac knows live, expecting visit if wrote above code? if so, how approach situation?
just make get_collisions
return generator:
def get_collisions(item, others): return (other other in others if collides(item, other))
then, if want check:
for collision in get_collisions(item, others): print 'collision!' break else: print 'no collisions!'
Comments
Post a Comment