What are the lesser-known but useful features of the Python programming language?
- Try to limit answers to Python core.
- One feature per answer.
- Give an example and short description of the feature, not just a link to documentation.
- Label the feature using a title as the first line.
Quick links to answers:
- Argument Unpacking
- Braces
- Chaining Comparison Operators
- Decorators
- Default Argument Gotchas / Dangers of Mutable Default arguments
- Descriptors
- Dictionary default
.get
value - Docstring Tests
- Ellipsis Slicing Syntax
- Enumeration
- For/else
- Function as iter() argument
- Generator expressions
import this
- In Place Value Swapping
- List stepping
__missing__
items- Multi-line Regex
- Named string formatting
- Nested list/generator comprehensions
- New types at runtime
.pth
files- ROT13 Encoding
- Regex Debugging
- Sending to Generators
- Tab Completion in Interactive Interpreter
- Ternary Expression
try/except/else
- Unpacking+
print()
function with
statement
The step argument in slice operators. For example:
The special case
x[::-1]
is a useful idiom for 'x reversed'.Readable regular expressions
In Python you can split a regular expression over multiple lines, name your matches and insert comments.
Example verbose syntax (from Dive into Python):
Example naming matches (from Regular Expression HOWTO)
You can also verbosely write a regex without using
re.VERBOSE
thanks to string literal concatenation.iter() can take a callable argument
For instance:
The
iter(callable, until_value)
function repeatedly callscallable
and yields its result untiluntil_value
is returned.In-place value swapping
The right-hand side of the assignment is an expression that creates a new tuple. The left-hand side of the assignment immediately unpacks that (unreferenced) tuple to the names
a
andb
.After the assignment, the new tuple is unreferenced and marked for garbage collection, and the values bound to
a
andb
have been swapped.As noted in the Python tutorial section on data structures,
To add more python modules (espcially 3rd party ones), most people seem to use PYTHONPATH environment variables or they add symlinks or directories in their site-packages directories. Another way, is to use *.pth files. Here's the official python doc's explanation:
Operator overloading for the
set
builtin:More detail from the standard library reference: Set Types