List of all syntactic sugar?

B

Bas

Hi group,

just out of curiosity, is there a list of all the syntactic sugar that
is used in python? If there isn't such a list, could it be put on a
wiki somewhere? The bit of sugar that I do know have helped me a lot in
understanding the inner workings of python.

To give a few examples (might not be totally correct):

x -> x.__getitem__(i)
x[a:b] -> x.__getitem__(slice(a,b,None))
x+y -> x._add__(y)
x.method(a) -> call (x.__dict__[method], self, a) ??
for i in x: f(i) -> it = iter(x); while True: i = it.next(); f(i) ....
except stop: pass

TIA,
Bas
 
S

Steven D'Aprano

Hi group,

just out of curiosity, is there a list of all the syntactic sugar that
is used in python? If there isn't such a list, could it be put on a
wiki somewhere? The bit of sugar that I do know have helped me a lot in
understanding the inner workings of python.

That kind of depends on what you mean by syntactic sugar. For instance, I
wouldn't call any of your examples syntactic sugar. The problem with
(e.g.) calling x syntactic sugar for x.__getitem__(i) is that it gets
the relationship backwards: x _is_ the syntax, it isn't the sugar.
Magic methods like __getitem__ are there as a mechanism to allow custom
classes to use the same syntax as built-in classes.

However, I would call these syntactic sugar:

"hello" " " "world" -> "hello world" # literal string concatenation

r'raw strings'

x[-n] -> x[len(x)-n]

x[:] -> x[0:len(x)]

print obj -> sys.stdout.write(str(obj) + '\n')

print obj, -> sys.stdout.write(str(obj))

s.find(target) ->
try:
return s.index(target)
except IndexError:
return -1
# not really syntax, perhaps "method sugar" is a better name?

import a, b, c -> import a; import b; import c

raise Exception, string -> raise Exception(string)


Of course, one person's syntactic sugar is another person's essential
syntactic carbohydrates.
 
B

Bas

That kind of depends on what you mean by syntactic sugar.

Mightbe I was misusing the name of syntactic sugar, but I what I
intended to say was "all the possible 'transformations' that can be
made to reduce all the 'advanced' syntax to some sort of minimal core
of the language".

Bas
 
D

Diez B. Roggisch

That kind of depends on what you mean by syntactic sugar. For instance, I
wouldn't call any of your examples syntactic sugar.

AFAIK that is exactly what syntactic sugar means. Apart from non-strictness,
all syntax can be expressed by function application. Even

foo.bar()

is nothing but

bar(self)

So - he used the term right I'd say.

Regards,

Diez
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,710
Latest member
bernietqt

Latest Threads

Top