Initialize variables inline with ~> such as `0 ~> total += value`

Add a shorthand notation for initializing a variable in place such as

Example 1:

#Current
total = 0
for i in range(0,10):
    total += i
#Proposed
for i in range(0,10):
    0 ~> total += i

Example 2:

#Current
items = []
for num in numbers:
    if num > 10:
        items.append(num)
#Proposed
for num in numbers:
    if num > 10:
        [] ~> items.append(num)

Example 3:

#Current
sale = {}
for p, q in zip(products, quantities):
    if p in sale:
        sale[p] += q
    else:
        sale[p] = q
#Proposed
sale = {}
for p, q in zip(products, quantities):
    0 ~> sale[p] += q

This doesn’t allow you to do anything new, it just saves you a few lines at the cost of new syntax. Explicit variable initialization is not a problem to be solved, IMO.

As to your last example:

from collections import defaultdict

sale = defaultdict(lambda: 0)
for p, q in zip(products, quantities):
    sale[p] += q
1 Like

or just defaultdict(int)

2 Likes

Shows you how often I actually reach for defaultdict…

2 Likes

Yes, defaultdict is one way for dicts. I think to have a generic syntax that covers every single variable type is still valuable, since you don’t need to remember how to handle each variable type.

Yeah we have that, it’s an assignment statement. It’s not worth the complexity and added syntax to save one line of code.

3 Likes

This is a bug magnet. Consider this (rather silly) example:

stuff = [1, 4, 2, 8, 5, 7]
for num in stuff:
    total = 0
    for i in range(num):
        total += num * i
    print(num, total)

This is perfectly reasonable and easy to wrap your head around. Try defining reasonable semantics for the “initialize” semantics that won’t surprise people.

2 Likes

or just Counter()

2 Likes

aw dangit :joy:

1 Like

Note for this use case I generally opt for defaultdict(int) over Counter() because it is very slightly more performant. Just wanted to point it out though because Counter() is perhaps easier to remember.

If you must use a normal dict for whatever reason, you can also do sale.setdefault(p, 0)

(and in the case the value is mutable you can even fit it all on one line, e.g. d.setdefault(k, []).append(v))

3 Likes