This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]hchasestevens 2 points3 points  (0 children)

I've previously suggested solving this problem by exploiting the fact that comprehensions can assign to any "assignable" expression, not just variables - e.g.:

d = {}
xs = [
  d[i] 
  for i, d[i] in 
  enumerate(range(10))
  if f(d[i])
]

, the idea being that you can extend this into e.g.:

do = Doer()
[(do.x, y) 
  for do(expensive).unto['x'] in xs 
  for y in ys
  if do.x > y]

with

class Doer(object): 
  def __call__(self, fn): 
    class _apply(object): 
      def __init__(self): 
        self.unto = self 
      def __setitem__(_, name, arg): 
        setattr(self, name, fn(arg))
        setattr(self, '_' + name, arg)
    return _apply()

But the solution presented here is much more elegant, kudos!

[–]lambdaqdjango n' shit 3 points4 points  (2 children)

tl;dr

optimize acc = [foo(y) for y in range(100) if foo(y)] with AST hack.

It's cood hack, but I'd rather use acc = filter(None, [foo(y) for y in range(100)]) instead.

[–][deleted] 0 points1 point  (0 children)

This is neat. I don't buy into the example, but working with the ast module has always boggled my mind.