Variable scope in a Python generator expression -


i have written function creates dictionary mapping strings -> generator expression. generator expression filters list of items based on 2 criteria, 2 criteria being different each generator in dictionary.

def iters(types):     iterators = {}     tname in types:         inst, type = tname.split('|')         iterators[tname] = (t t in transactions() if t['institution_type'] == inst , t['type'] == type)     return iterators 

the issue i'm running of generators filtered according last values of inst , type, presumably because 2 variables re-used in each iteration of loop. how can around issue?

yes, inst , type names used closures; time iterating on generators, these bound last values in loop.

create new scope names; function can this:

def iters(types):     def build_gen(tname):         inst, type = tname.split('|')         return (t t in transactions()                 if t['institution_type'] == inst , t['type'] == type)     iterators = {}     tname in types:         iterators[tname] = build_gen(tname)     return iterators 

you replace last lines dict comprehension too:

def iters(types):     def build_gen(tname):         inst, type = tname.split('|')         return (t t in transactions()                  if t['institution_type'] == inst , t['type'] == type)     return {tname: build_gen(tname) tname in types} 

Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -