syntactic sugar
In programming languages, syntactic sugar is a piece of syntax designed to make code easier to read or write without changing what the language can compute. Peter J. Landin coined the term in 1964 to describe surface forms whose meaning is defined by translation into a smaller core of language primitives.
A construct qualifies as syntactic sugar when removing it would not reduce expressive power, because any program written with it can be rewritten using the underlying constructs.
Common examples appear across many languages:
- Array indexing: writing
a[i]desugars to the pointer dereference*(a + i)in C. - List comprehensions: a comprehension like
[f(x) for x in items]desugars to an explicitforloop. - Decorators: a decorator like
@decabove a definition desugars to the plain function callfunc = dec(func). Python’s documentation explicitly calls decorator syntax syntactic sugar. - f-strings: an f-string desugars to equivalent
str.format()calls or string concatenation. - Operators:
a + bdesugars to a magic method call likea.__add__(b).
Critics argue that excessive sugar complicates language specifications and tooling, while proponents view it as essential for ergonomics and readability.
Related Resources
Tutorial
Syntactic Sugar: Why Python Is Sweet and Pythonic
In this tutorial, you'll learn what syntactic sugar is and how Python uses it to help you create more readable, descriptive, clean, and Pythonic code. You'll also learn how to replace a given piece of syntactic sugar with another syntax construct.
For additional information on related topics, take a look at the following resources:
- Primer on Python Decorators (Tutorial)
- Python List Comprehension: Tutorial With Examples (Tutorial)
- Python's F-String for String Interpolation and Formatting (Tutorial)
- Python 3.12 Preview: More Intuitive and Consistent F-Strings (Tutorial)
- Python's Magic Methods: Leverage Their Power in Your Classes (Tutorial)
- The Walrus Operator: Python's Assignment Expressions (Tutorial)
- Syntactic Sugar: Why Python Is Sweet and Pythonic (Quiz)
- Python Decorators 101 (Course)
- Primer on Python Decorators (Quiz)
- Understanding Python List Comprehensions (Course)
- When to Use a List Comprehension in Python (Quiz)
- Python 3's F-Strings: An Improved String Formatting Syntax (Course)
- Python's F-String for String Interpolation and Formatting (Quiz)
- Python's Magic Methods in Classes (Course)
- Python's Magic Methods: Leverage Their Power in Your Classes (Quiz)
- Python Assignment Expressions and Using the Walrus Operator (Course)
- The Walrus Operator: Python's Assignment Expressions (Quiz)