Syntactic sugar for assignment statements: one value to multiple targets?
gc1223 at gmail.com
Tue Aug 16 21:50:52 CEST 2011
Thanks for all the discussion on this. Very illuminating. Sorry for
the long delay in responding--deadlines intervened.
I will use the list comprehension syntax for the foreseeable future.
Tim, I agree with you about the slurping in final position--it's
actually quite surprising. As I'm sure you realized, that behavior
makes your 'tidier' version:
a,b,c,d,e, *more_dict_generator = (dict() for _ in itertools.count())
break with a MemoryError, which I don't think is the result that most
people would expect.
> While slightly ugly, it doesn't seem ugly enough to justify the
> extra complexity of special syntax for such a special case.
You're probably right (although for my coding this multiple assignment
scenario is a pretty ordinary case.) Anyway, I'll shop the a,b,c =
*dict() syntax over to python-ideas just to see what they say.
Thanks again, everyone! Happy Python.
On Aug 3, 7:25 am, Tim Chase <python.l... at tim.thechases.com> wrote:
> On 08/03/2011 03:36 AM, Katriel Cohn-Gordon wrote:
> > On Wed, Aug 3, 2011 at 9:25 AM, Steven D'Aprano wrote:
> >> a, b, c, d, e = [dict() for i in range(5)]
> > I think this is good code -- if you want five different dicts,
> > then you should call dict five times. Otherwise Python will
> > magically call your expression more than once, which isn't
> > very nice. And what if your datatype constructor has
> > side-effects?
> If the side-effects are correct behavior (perhaps opening files,
> network connections, or even updating a class variable) then
> constructor side-effects are just doing what they're supposed to.
> E.g. something I use somewhat regularly in my code[*]:
> a,b,c,d = (file('file%i.txt', 'w') for i in range(4))
> If the side-effects aren't performing the correct behavior, fix
> the constructor. :)
> [*] okay, it's more like
> ) = (file(fname) for fname in (
> or even
> ) = (
> for line
> in file(fname)
> if line.strip()
> for fname in (
> to load various set() data from text-files.
More information about the Python-list