Fluent Python

Record some trick of python3

reference

Building Lists of Lists

1
2
3
4
5
6
7
8
9
10
11
12
>>> board = [['_'] * 3 for i in range(3)]
>>> board
[['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']] >>> board[1][2] = 'X'
>>> board [['_', '_', '_'], ['_', '_', 'X'], ['_', '_', '_']]

# A list with three references to the same list is useless
>>> weird_board = [['_'] * 3] * 3
>>> weird_board
[['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']]
>>> weird_board[1][2] = 'O'
>>> weird_board
[['_', '_', 'O'], ['_', '_', 'O'], ['_', '_', 'O']]

A += Assignment Puzzler

1
2
3
4
5
6
7
>>> t = (1, 2, [10, 20])
>>> t[2] += [1, 1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> t
(1, 2, [10, 20, 1, 1])

difference between dir and dict in python

PyCharm

The Python IDE for Professional Developers https://www.jetbrains.com/pycharm/

issue

Record issue that I cannot find in google

.DS_Store

after operation in some one folder, there is .DS_Store. Then I run following code

1
2
3
4
5
6
7
8
9
10
11
for fn in os.listdir("migrations/versions"):
if fn == "__pycache__":
continue
with open(f"migrations/versions/{fn}") as f:
first_line = f.readline()

# error is UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa9 in position 1087: invalid start byte
first_line = f.readline()
File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/codecs.py", line 322, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb2 in position 319: invalid start byte

after deleting .DS_Store, all is good.