0

Question related to this which asks about side effects in list comprehensions.

def side_effects_only(x):
    # ...side effects...
    return # None

used as

{side_effects_only(x) for x in Y}
# where Y is large...

This shouldn't generate some giant set if Y is large. Since it is a set with a single None. Or ...?

Thanks!

k1m190r
  • 1,213
  • 15
  • 26
  • 1
    The set is still built and thrown away. The same reasons there apply here. – Pranav Hosangadi Aug 25 '21 at 15:27
  • I don't think it would be slow since the set is small, but still a normal loop would be more readable – mousetail Aug 25 '21 at 15:27
  • If you absolutely cannot spare *two* lines for this, you can even do it on one line: `for x in Y: side_effects_only(x)`. And it's still a character shorter than the set comprehension. – deceze Aug 25 '21 at 15:28
  • I just like how comprehensions read :). Hence my question. – k1m190r Aug 25 '21 at 15:29
  • 2
    The reason has more to do with clearly stating your *intent* than performance issues (though performance can be *an* important reason). Do you want a set? Use a set comprehension. No? Don't use a set comprehension. – chepner Aug 25 '21 at 15:30
  • 1
    The general consensus is that that's a bad reason to abuse a comprehension for a loop. You can abuse your own code as much as you like, but most other Python programmers will frown upon you. – deceze Aug 25 '21 at 15:30
  • 1
    If you absolutely must have something like this (cf. Perl statement modifiers), I would just define a wrapper function like `def __(g): for _ in g: pass`, then write `__(side_effects_only(x) for x in Y)`. It's the generator you want, not the comprehension, and `__` is about the simplest way possible to fully consume an iterator with no additional side effects. – chepner Aug 25 '21 at 15:38
  • Oh yeah this is nice! – k1m190r Aug 25 '21 at 15:54

0 Answers0