List of all syntactic sugar?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Fri Apr 14 06:46:25 EDT 2006


On Fri, 14 Apr 2006 02:54:11 -0700, Bas wrote:

> 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[i] syntactic sugar for x.__getitem__(i) is that it gets
the relationship backwards: x[i] _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.



-- 
Steven.




More information about the Python-list mailing list