Summary about pythonic style (2): Other scraping

Overview

I searched for python code conventions. Part 1 just summarized PEP8 in my own way. Here is a summary of the contents of other sources. I choose what I think is true.

The page I saw

The Hitchhiker's Guide to Python Be Pythonic Code Like a Pythonista: Idiomatic Python

General

Emphasis on clarity

Avoid black magic as much as possible and make the code easy to understand BAD

def make_complex(*args):
    x, y = args
    return dict(**locals())

GOOD

def make_complex(x, y):
    return {'x': x, 'y': y}

Function variable types and notes

We are all responsible users It seems that python doesn't have a private keyword. As for the culture, it seems that each person is responsible for coating. There are no keywords, but there are conventions. Methods that you don't want to be public should have _ prefix

Open the file with With

You can be assured that the file will be closed no matter what

# Bad
f = open('file.txt')
a = f.read()
print a
f.close()

# Good
with open('file.txt') as f:
    for line in f:
        print line

Tips

# Enumerate
for index, value in enumerate(pi_nums):
    print(index, value)
# 1 3
# 2 1
# 3 4
# 4 1
# 5 5

# Zip
for p, f in zip(pi_nums, fibonacci_nums):
    print(p, f)
# 3 1
# 1 1
# 4 2
# 1 3
# 5 5

#Unpacking after python3
a, *rest = [1, 2, 3]
# a = 1, rest = [2, 3]
a, *middle, c = [1, 2, 3, 4]
# a = 1, middle = [2, 3], c = 4

for _ in range(10):
    print('Tasty')
a = [1] * 4
# a = [1, 1, 1, 1]

# WRONG
b = [[1] * 3] * 3
# b = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
# Because when
b[0][0] = 2
# b = [[2, 1, 1], [2, 1, 1], [2, 1, 1]]

# RIGHT
b = [[1] * 3 for _ in range(3)]

Recommended Posts

Summary about pythonic style (2): Other scraping
Summary about pythonic style (1): PEP8
Summary about Python scraping
About Twitter scraping
Summary about Python3 + OpenCV3
Python Crawling & Scraping Chapter 4 Summary