5.9. Summary¶
All programming languages have their own idioms and best practices. This chapter focuses on the particular ways that Python programmers have come to write “pythonic” code to make the best use of Python’s syntax.
At the core of pythonic code are the 20 aphorisms from the Zen of Python, which are rough guidelines for writing Python. These aphorisms are opinions and not strictly necessary for writing Python code, but they are good to keep in mind.
Python’s significant indentation (not to be confused with significant whitespace) provokes the most protest from new Python programmers. Although almost all programming languages commonly use indentation to make code readable, Python requires it in place of the more typical braces that other languages use.
Although many Python programmers use the range(len()) convention for for loops, the enumerate() function offers a cleaner approach to getting the index and value while iterating over a sequence. Similarly, the with state- ment is a cleaner and less bug-prone way to handle files compared to calling open() and close() manually. The with statement ensures that close() gets called whenever the execution moves outside the with statement’s block.
Python has had several ways to interpolate strings. The original way was to use the %s conversion specifier to mark where strings should be included in the original string. The modern way as of Python 3.6 is to use f-strings. F-strings prefix the string literal with the letter f and use braces to mark where you can place strings (or entire expressions) inside the string.
The [:] syntax for making shallow copies of lists is a bit odd-looking and not necessarily pythonic, but it’s become a common way to quickly cre- ate a shallow list.
Dictionaries have a get() and setdefault() method for dealing with nonexistent keys. Alternatively, a collections.defaultdict dictionary will use a default value for nonexistent keys. Also, although there is no switch statement in Python, using a dictionary is a terse way to implement its equivalent without using several if - elif - else statements, and you can use ternary operators when evaluating between two values.
A chain of == operators can check whether multiple variables are equal to each other, whereas the in operator can check whether a variable is one of many possible values.
This chapter covered several Python language idioms, providing you with hints for how to write more pythonic code. In the next chapter, you’ll learn about some of the Python gotchas and pitfalls that beginners fall into.