what does := means simply?

Ian Kelly ian.g.kelly at gmail.com
Thu May 17 11:27:46 EDT 2018


On Thu, May 17, 2018 at 9:06 AM, Chris Angelico <rosuav at gmail.com> wrote:
> On Fri, May 18, 2018 at 12:30 AM, bartc <bc at freeuk.com> wrote:
>> Anyway, try this:
>>
>>     def showarg(x): print(x)
>>
>>     def dummy(*args,**kwargs): pass
>>
>>     dummy(a=showarg(1),*[showarg(2),showarg(3)])
>>
>> This displays 2,3,1 showing that evaluation is not left to right.
>>
>
> Keyword args are evaluated after positional args. It's a bad idea to
> put positional after keyword; you risk mis-identifying your args:
>
>>>> def dummy(a, b, c): pass
> ...
>>>> dummy(a=showarg(1),*[showarg(2),showarg(3)])
> 2
> 3
> 1
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: dummy() got multiple values for argument 'a'
>
> Evaluation is not always left to right, but it is always well-defined.

I wasn't actually aware it was allowed to place keyword args before
positional args; this must be relatively new in Python 3.

This raises a new issue for me w.r.t. PEP 572. The spelling of :=
makes it unlikely to accidentally use in place of ==, but what about
:= and = confusion? For example, say I mean to write this:

    foo(a := 42, b, c)

but accidentally write this instead:

    foo(a = 42, b, c)

Hopefully for many functions this would just be a TypeError
("unexpected keyword argument"). At the same time, it's a fairly
common practice to pass a variable to a function that happens to have
the same name as the argument being passed. Has there been any
discussion of whether this is likely to be a source of confusion?



More information about the Python-list mailing list