"Effective Python 2nd Edition" Chapter 1 <Pythonic Thinking>

Introduction

Execution environment

When posting the sample code, post the result of execution in the following execution environment. We will try to provide it in the form that is as error-free as possible, but please forgive us if it does not work or is wrong.

Chapter 1

import this Do you know "The Zen of Python"? When you start the Python interpreter and execute ʻimport this`, "The Zen of Python" is displayed as shown below.

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Here is ** a maxim of the guiding principles for those who create the programming language "Python" itself **. It was written by Tim Peters, a major contributor to Python, and I think it describes ** the spirit and philosophy of "Python" **. If you're developing software using Python, you'll want to read it once. (But I first learned about it recently ...

There is a Qiita article that is explained in detail along with the Japanese translation, so I think that it will be easier to imagine each maxim if you look at it. The attitude that programmers should have (The Zen of Python) --Qiita

By the way, according to PEP 20 --The Zen of Python, when you run ʻimport this` in the interpreter, it says" The Zen of Python ". Seems to be displayed as an Easter egg.

You should use not somelist instead of len (somelist) == 0 (from item 2)

When you want to find out that a list is empty, you want to evaluate it as ʻif len (somelist) == 0, but instead you should write ʻif not some list. This takes advantage of the fact that when the list is empty it is implicitly evaluated as False, PEP 8 (Python Code Style Guide). It is also written in / ja / latest /).

When evaluating binary values, I think you should write ʻif flag instead of ʻif flag == True, but it may be easier to remember if you think that it is the same.

Do not use ʻelse in forandwhile` (from item 9)

The for and while statements have a ʻelse block that is only ** executed if break` is not executed inside the loop.

for i in range(3):
    print(i)
    if i == 1:
        break
else:
    print("Hello")  #It is not displayed because break is executed

>>>
0
1
for i in range(3):
    print(i)
else:
    print("Hello")  #It is displayed because break was not executed

>>>
0
1
2
Hello

As you can see from the sample code above, you don't know when ʻelse is executed and when ʻelse is not executed. Code that is not intuitive in this way is misleading and buggy and should not be used.

Instead, you can create and implement a helper function like this:

def hoge():
     for i in range(3):
         print(i)
         if i == 1:
             return False
     return True

if not hoge():
    print("Hello")

>>>
0
1
Hello

Substitution formula prevents repetition (from item 10)

Assignment expressions are a new syntax added in Python 3.8. Normally, in the assignment "statement", write ʻa = b, but in the assignment "expression", write ʻa: = b. By using the assignment expression, the part where the code was duplicated in the past can be written concisely as follows.

#So far
count = fresh_fruit.get('lemon', 0)
if count:
    make_lemonade(count)
else:
    out_of_stock()
#From now on (when written using an assignment formula)
if count := fresh_fruit.get('lemon', 0):  #Assignment to count and evaluation can be done in one line at the same time
    make_lemonade(count)
else:
    out_of_stock()

In addition, for example, if you want to write code that extracts a matched string using a regular expression, you can write it concisely as follows.

#So far
import re
string = "abcABC"

match = re.match(r"([a-z]+)", string)
if match:
    print(f"{match.group(1)}")
else:
    print("Not match")

>>>
abc
#From now on (when written using an assignment formula)
import re
string = "abcABC"

if match := re.match(r"([a-z]+)", string):  #Assignment to match and evaluation can be done in one line
    print(f"{match.group(1)}")
else:
    print("Not match")

>>>
abc

By the way, the assignment expression operator : = is called the walrus operator because it resembles a walrus eyeball and fangs. When pronouncing "ʻa: = b`", it is said to pronounce "a Walrus b". You'll want to pronounce it as "a Walrus b", but you'll probably be rephrasing it as "a colon equal b" without being able to communicate with the other party ... lol

Summary

We introduced "Effective Python 2nd Edition" Chapter 1 .

I would like to introduce Chapter 2 and beyond little by little, so let's meet again next time!

Reference site

Recommended Posts

"Effective Python 2nd Edition" Chapter 1 <Pythonic Thinking>
"Effective Python 2nd Edition" Chapter 3 <Functions>
[Effective Python study memo] Chapter 1: Python-style thinking (Pythonic Thinking)
Pythonic thinking
Ant book with python (chapter3 intermediate edition ~)
First Python 3rd Edition
[Python] Chapter 01-01 About Python (First Python)
Effective Python Memo Item 3