bslatkin / effectivepython

Effective Python: Second Edition — Source Code and Errata for the Book
https://effectivepython.com
2.24k stars 718 forks source link

Item #13: Clarification about unpacking assignments with starred expressions #78

Closed bslatkin closed 4 months ago

bslatkin commented 4 years ago

Reported by Toshi

Page 50, Item 13, 1st paragraph

"However, to unpack assignments that contain a starred expression, you must have at least one required part, or else you’ll get a SyntaxError. You can’t use a catch-all expression on its own:"

What about these cases:

*others, = car_ages_descending

, *others = car_ages_descending

bslatkin commented 4 years ago

For *others, = car_ages_descending

This one works because you are making a tuple of size 1 by appending the comma to "*others". Starred expressions are only allowed in assignments when they're part of a tuple, including a tuple of size one. So technically this is allowed. This also copies the original list. I think this type of usage is ugly and should be avoided, but I don't think it's common enough to merit a mention.

, *others = car_ages_descending

This one doesn't work because the expression isn't a valid tuple because there's no value before the first comma. So I don't think there's any reason to call this one out specifically.