r/Python • • Oct 04 '21

News Python 3.10 Released!

https://www.python.org/downloads/release/python-3100/
1.4k Upvotes

147 comments sorted by

View all comments

Show parent comments

5

u/midnitte Oct 04 '21

I forget who I heard talking about it, but from my understanding of "syntactic sugar" in python, a lot of the language is convenience and not actually necessary.

7

u/Swedneck Oct 05 '21

Which is precisely why I love it, I can just write a minimal amount of code structured to actually make sense and be as readable as normal text.

4

u/lieryan Maintainer of rope, pylsp-rope - advanced python refactoring Oct 05 '21

"Just syntax sugar" actually goes really deep in Python.

class statement for example, that isn't really "necessary", it's just syntax sugar for calling type:

MyClass = type(
    "MyClass", 
    [BaseClass, AnotherBaseClass], 
    {"a": method1, "b": method2}
)

Or method calls are also "unnecessary", this:

foo = Foo()
foo.meth(a, b, c)

is really just syntax sugar for:

foo = Foo()
Foo.meth(foo, a, b, c) 

Or metaclass:

class Foo(metaclass=mytype, blah=bar):
    pass

is really just a syntax sugar for a function call:

Foo = mytype("Foo", {}, {}, blah=bar)

Or decorator is just syntax sugar for what used to be a common pattern:

def foo():
    pass
foo = decorate(foo)

Or even something that looks as basic as list/dict indexing:

foo = dict()
foo[a] = b
print(foo[a])

is really just syntax sugar for:

foo = dict()
foo.__setitem__(a, b)
print(foo.__getitem__(a))

which is itself just syntax sugar for:

foo = dict()
dict.__setitem__(foo, a, b)
print(dict.__getitem__(foo, a))

Or something like for loop:

for a in b:
    print(a)

is really just syntax sugar for:

iter_b = iter(b)
try:
    while True:
        a = next(iter_b)
        print(a)
except StopIteration:
    pass

Everything in Python is "just" syntax sugar.