Python Note

December 03, 2021

筆記 https://en.wikibooks.org/wiki/Python_Programming/Idioms

http.client

封裝過的http (https) 請求。

基本使用方式:

下例是請求台灣證交所的API

 url = 'openapi.twse.com.tw'
mi_index = '/v1/exchangeReport/MI_INDEX'
client = http.client.HTTPSConnection(f'{url}', 443, timeout=10)
# 呼叫request後才會實際請求。
client.request('GET', f'{mi_index}')
res = client.getresponse()
data = json.loads(res.read()) 

note: url不用加入協定(http, https),由使用的物件決定協定(http.client.HTTPSConnection vs https.client.HTTPConnection)。

注意 request 的port,需要當作參數指定。預設http使用 80 port,https 使用443 port。

python idiom

記錄python的貫用寫法加深印象。

錯誤處理

盡量使用 try ... except 的方式處理錯誤。

python 的哲學以 EAFP (its Easier to Ask Forgiveness then Permission) 取代 LBYL (Look Before You Leap)。

將有可能會發生錯誤的程式碼片段放在 try ... except 區塊內。

屬性使用方式

直接使用屬性,不使用 getter / setter 封裝。

屬性是否為private,使用前綴底線(_prop)區分,依賴約定。

dictionary vs class

變值是動態時使用 dictiory,靜態時使用 class。

discard variable

使用底線代表要被捨棄的變數。如使用tuple接回傳值時、或是指示忽略函式參數。

也可以使用 *_, **_ 搭棄 positional / keyword 拾棄傳進函式的印數。

對應可變參數*args, **kwargs

使用 else

可以在 try, for, while, if 後使用 else。

import 原則

impmort 模組,盡量避免引入 name ( function, class etc)。

若直接引入名稱 ,將會產生新的名稱綁定。而這個命名綁定會跟模組底下的原命名不同(如果兩個名稱任一個被重新賦值)。

可使用 import <module> as <alias> 取個簡單的別名。

若是使用from <module> import <sub-module> 引入子模組,則不太會有問題。

運算

交換值

b, a = a, b

使用nullable 屬性

使用and

a and a.x
a and a.f()

# regular expression 尤其常用
match and match.group(0)

子字串比對

使用 in關鍵字。

next

使用 next 搭配 for 表達示,可以取得集合內特定條件的第一個index或值(find first)。

try:
    x = next(n for n in l if n > 0)
except StopIteration:
    print('No positive numbers')
else:
    print('The first positive number is', x)

else 用法可以將關注點分離。

截斷

使用 del,不用使用重新賦值的方式。

del l[j:]
del l[:i]

# anti pattern
l = l[:j]
l = l[i:]

del 可以直接回收資源。

建構string

很常用的感覺

善用 join()

# ...
# l.append(x)
s = ''.join(l)

# 也可使用 generactor expressiotns
s = ''.join(f(x) for x in l)

使用 + 串接字串的話,每次都會產生新的字串(字串在python內是不可變變數)

可變參數 *args, **kwargs

*args 跟 positional variable相關。 **kargs 與 keyword variable 相關。

ref: https://blog.maxkit.com.tw/2018/12/python-args-kwargs.html



Written by Howard Chang , software engineer, programming lover, from Taiwan