7

When I try to unpack lists in a list comprehension:

[*parent.rules for parent in parents if hasattr(parent, "rules")]

I get the error:

SyntaxError: iterable unpacking cannot be used in comprehension

While I understand there are other ways to do this, this seems like the most obvious and Pythonic way. Why does Python disallow this behaviour?

TheInitializer
  • 566
  • 7
  • 20
  • why are you unpacking `parent`? What type is it? – touch my body Apr 07 '18 at 20:59
  • 1
    I'd recommend removing all that stuff about your metaclass from the question and just ask about the unpacking. As you can see, people are confused about the irrelevant part of your question. – Aran-Fey Apr 07 '18 at 21:00
  • 3
    PEP 448 mentions that this might be allowed the future. In the meantime, you can use `chain.from_iterable(parent.rules for parent in parents if hasattr(parent, "rules"))`. (I might use `getattr(parent, "rules", [])` in this case to avoid the condition.) – chepner Apr 07 '18 at 21:05
  • @Ry Thanks for marking my question as a duplicate - might it be better to give the original question a better name so people can find it more easily? – TheInitializer Apr 07 '18 at 21:08
  • 2
    @TheInitializer: People can find it through your question now =) That’s the point of duplicates. – Ry- Apr 07 '18 at 21:31

0 Answers0