Hi Mirmojtaba, thanks for your suggestion.
I doubt this idea will fly with this syntax because it could easily be
confused with the walrus operator.
x := 0
is *almost* legal syntax currently. In fact
(x := 0)
is legal, and it is quite possible that at some time in the future
(Dic[fruit]:=0)
will also be made legal.
Your particular example can be written
Dic = {}
for fruit in fruits:
Dic[fruit] = Dic.get(fruit, 0) + 1 # 0 is default value if key not
in dict
Actually I can see this idea being more useful with ordinary variables.
At the moment we can write something like this:
try:
count = count + 1
except NameError: # count has not been initialised yet
count = 1
which is fairly clumsy, and with your idea would be more concise:
count := 0 # or a different syntax, maybe count <== 0 or something
count += 1
(NB In fact if PEP 463 "Exception-catching expressions" had been
accepted, we could write something like
count = count + 1 except NameError: 1
but the PEP has been rejected, regrettably in my opinion. 🙁)
That said, in most real examples, one could write
count = 0
initially, and
count = count +1
to increment.
So I think it is up to you to provide further convincing examples in
favour of your idea.
Best wishes
Rob Cliffe
On 05/02/2022 20:18, Mirmojtaba Gharibi wrote:
Hello there,
I have an idea for initializing a variable the first time it’s
created; it can especially be helpful with containers, and dicts
specifically. Let me demonstrate with some examples:
Dic = {} # format fruit:count
for fruit in fruits:
If fruit in Dic:
Dic[fruit]+=1
Else:
Dic[fruit]=1
With my proposal, using := to init (similar to how in math parlance,
the := is used for defining something for the first time)
Dic = {} # format fruit:count
For fruit in fruits:
Dic[fruit]:= 0
Dic[fruit]+=1
Would be great to hear your feedback. Thanks.
Moj
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/python-ideas@python.org/message/G4KJNQZYROB3NDWWLWSR5OHD7ZDCQQT4/
Code of Conduct: http://python.org/psf/codeofconduct/
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/python-ideas@python.org/message/FQTCYQ4B3UNBWEJTFDY556A4SFR4BLQP/
Code of Conduct: http://python.org/psf/codeofconduct/