Syntactic sugar for assignment statements: one value to multiple targets?

Tim Chase python.list at tim.thechases.com
Wed Aug 3 07:25:34 EDT 2011


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. :)

-tkc


[*] okay, it's more like

(features,
  adjustments,
  internet,
  ) = (file(fname) for fname in (
    'features.txt',
    'adjustments.txt',
    'internet.txt'
    )

or even

(features,
  adjustments,
  internet,
  ) = (
    set(
      line.strip().upper()
      for line
      in file(fname)
      if line.strip()
      )
    for fname in (
    'features.txt',
    'adjustments.txt',
    'internet.txt'
    )

to load various set() data from text-files.



More information about the Python-list mailing list