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
Get the python regex parse tree to debug your regex.
Regular expressions are a great feature of python, but debugging them can be a pain, and it's all too easy to get a regex wrong.
Fortunately, python can print the regex parse tree, by passing the undocumented, experimental, hidden flag
re.DEBUG
(actually, 128) tore.compile
.Once you understand the syntax, you can spot your errors. There we can see that I forgot to escape the
[]
in[/font]
.Of course you can combine it with whatever flags you want, like commented regexes:
enumerate
Wrap an iterable with enumerate and it will yield the item along with its index.
For example:
References:
enumerate
Conditional Assignment
It does exactly what it sounds like: "assign 3 to x if y is 1, otherwise assign 2 to x". Note that the parens are not necessary, but I like them for readability. You can also chain it if you have something more complicated:
Though at a certain point, it goes a little too far.
Note that you can use if ... else in any expression. For example:
Here func1 will be called if y is 1 and func2, otherwise. In both cases the corresponding function will be called with arguments arg1 and arg2.
Analogously, the following is also valid:
where class1 and class2 are two classes.
Dictionaries have a get() method
Dictionaries have a 'get()' method. If you do d['key'] and key isn't there, you get an exception. If you do d.get('key'), you get back None if 'key' isn't there. You can add a second argument to get that item back instead of None, eg: d.get('key', 0).
It's great for things like adding up numbers:
sum[value] = sum.get(value, 0) + 1
Sending values into generator functions. For example having this function:
You can:
Named formatting
% -formatting takes a dictionary (also applies %i/%s etc. validation).
And since locals() is also a dictionary, you can simply pass that as a dict and have % -substitions from your local variables. I think this is frowned upon, but simplifies things..
New Style Formatting