Syntax for dictionnary unpacking to variables

Thanks for pointing out these posts.
Well the only conficts I can see between our 3 proposals are:

  • use brackets or not: {target, variables} versus target, variables
  • allow versus disallow the existance of keys not matching target variables

Not difficult to decide after discussion, whatever the result is.

That seems to be a shame that you have to write the names of the target variables when they are already written once in the dict.

I can agree, but for execution speed the python interpreter must know the set of local variables before execution, also to specify the extracted keys allows to extract only what is needed and prevent overriding of other variables in the scope.

your data is coming in from another language … but you want to use English variables. Or some of your keys are not legal identifiers.

You can already say that for unpacking dictionnaries as function arguments. Since it is an accepted behavior in the case of functions arguments, I see no point against the same with variable assignment.

This point has already been discussed recently don’t you agree ?

Python mostly looks like executable pseudo-code. For most features, you don’t need to be a Python expert to guess what it does. Unpacking is an exception, it has to be learned and memorised.

You are right on this, but since users already need to memorize the trick of iterable unnpacking and dict unpacking to arguments, I expect one will find dict unpacking to variables quite intuitive.

I think that the advantage of a dict is when you don’t know what they keys will be. If you do know what the keys will be, and they are all legal identifiers, a much better data structure is a named tuple, or a SimpleNamespace, or some other object with named fields/attributes such as a dataclass.

This is not the only use case for returning dict: you can use it also when there is too much things to return to use a simple tuple. Because it asks the user to memorize the precise order of values, where a dictionnary let him extract the values he really wants.
A dictionnary on the other hand just ask the user to know the names of the field(s) it wants, and let it not care about the rest.

I don’t consider a namedtuple to be a good option since it must be declared beforehand. meaning if you have N functions with a different dictionnary result, you have first to declare N namedtuples just to be used at one place each.
SimpleNamespace is more convenient, but provides no ability to extract a bunch of members, so it is just like a dictionnary.

1 Like