|
| 1 | +""" |
| 2 | +Should emit: |
| 3 | +B030 - on lines 29, 33, 43 |
| 4 | +""" |
| 5 | +import itertools |
| 6 | +from itertools import groupby |
| 7 | + |
| 8 | +shoppers = ["Jane", "Joe", "Sarah"] |
| 9 | +items = [ |
| 10 | + ("lettuce", "greens"), |
| 11 | + ("tomatoes", "greens"), |
| 12 | + ("cucumber", "greens"), |
| 13 | + ("chicken breast", "meats & fish"), |
| 14 | + ("salmon", "meats & fish"), |
| 15 | + ("ice cream", "frozen items"), |
| 16 | +] |
| 17 | + |
| 18 | +carts = {shopper: [] for shopper in shoppers} |
| 19 | + |
| 20 | + |
| 21 | +def collect_shop_items(shopper, items): |
| 22 | + # Imagine this an expensive database query or calculation that is |
| 23 | + # advantageous to batch. |
| 24 | + carts[shopper] += items |
| 25 | + |
| 26 | + |
| 27 | +# Group by shopping section |
| 28 | +for _section, section_items in groupby(items, key=lambda p: p[1]): |
| 29 | + for shopper in shoppers: |
| 30 | + collect_shop_items(shopper, section_items) |
| 31 | + |
| 32 | +for _section, section_items in groupby(items, key=lambda p: p[1]): |
| 33 | + collect_shop_items("Jane", section_items) |
| 34 | + collect_shop_items("Joe", section_items) |
| 35 | + |
| 36 | + |
| 37 | +for _section, section_items in groupby(items, key=lambda p: p[1]): |
| 38 | + # This is ok |
| 39 | + collect_shop_items("Jane", section_items) |
| 40 | + |
| 41 | +for _section, section_items in itertools.groupby(items, key=lambda p: p[1]): |
| 42 | + for shopper in shoppers: |
| 43 | + collect_shop_items(shopper, section_items) |
| 44 | + |
| 45 | +for group in groupby(items, key=lambda p: p[1]): |
| 46 | + # This is bad, but not detected currently |
| 47 | + collect_shop_items("Jane", group[1]) |
| 48 | + collect_shop_items("Joe", group[1]) |
| 49 | + |
| 50 | + |
| 51 | +# Make sure we ignore - but don't fail on more complicated invocations |
| 52 | +for _key, (_value1, _value2) in groupby( |
| 53 | + [("a", (1, 2)), ("b", (3, 4)), ("a", (5, 6))], key=lambda p: p[1] |
| 54 | +): |
| 55 | + collect_shop_items("Jane", group[1]) |
| 56 | + collect_shop_items("Joe", group[1]) |
| 57 | + |
| 58 | +# Make sure we ignore - but don't fail on more complicated invocations |
| 59 | +for (_key1, _key2), (_value1, _value2) in groupby( |
| 60 | + [(("a", "a"), (1, 2)), (("b", "b"), (3, 4)), (("a", "a"), (5, 6))], |
| 61 | + key=lambda p: p[1], |
| 62 | +): |
| 63 | + collect_shop_items("Jane", group[1]) |
| 64 | + collect_shop_items("Joe", group[1]) |
0 commit comments