osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Proposal: named return values through dict initialization and unpacking


On Tue, Jun 21, 2016 at 9:41 PM Steven D'Aprano <steve at pearwood.info> wrote:

> On Tue, 21 Jun 2016 05:34 pm, Ari Freund wrote:
> >          var3, var1, var2 = **d
>
> But I don't want to use the key names your function uses. I want to
> use names which makes sense for my application
>

Note that my dict unpacking syntax proposal would solve this quite nicely.

    {'var1': width, 'var2': counter, 'var3': aardvark} = d

But the current syntax ain't so bad either. Maybe it's even better, more
readable despite being less concise.

    expected = {'var1', 'var2', 'var3'}
    excess = d.keys() - expected
    if excess:
        raise ValueError('unexpected keys {!r}'.format(excess))
    width = d['var1']
    counter = d['var2']
    aardvark = d['var3']