你使用過 Python 3.6 中針對文件系統(tǒng)的這個神奇方法嗎?
Python 3.6 首次發(fā)布于 2016 年,盡管它已經(jīng)發(fā)布了一段時間,但它引入的許多特性都沒有得到充分利用,而且相當(dāng)酷。下面是其中的三個。
分隔數(shù)字常數(shù)
快回答哪個更大,10000000 還是 200000?你在看代碼時能正確回答嗎?根據(jù)當(dāng)?shù)氐牧?xí)慣,在寫作中,你會用 10,000,000 或 10.000.000 來表示第一個數(shù)字。問題是,Python 使用逗號和句號是用于其他地方。
幸運的是,從 Python 3.6 開始,你可以使用下劃線來分隔數(shù)字。這在代碼中和使用字符串的 int() 轉(zhuǎn)換器時都可以使用:
- import math
- math.log(10_000_000) / math.log(10)
- 7.0
- math.log(int("10_000_000")) / math.log(10)
- 7.0
Tau 是對的
45 度角用弧度表示是多少?一個正確的答案是 π/4,但這有點難記。記住 45 度角是一個八分之一的轉(zhuǎn)角要容易得多。正如 Tau Manifesto 所解釋的,2π,稱為 Τ,是一個更自然的常數(shù)。
在 Python 3.6 及以后的版本中,你的數(shù)學(xué)代碼可以使用更直觀的常數(shù):
- print("Tan of an eighth turn should be 1, got", round(math.tan(math.tau/8), 2))
- print("Cos of an sixth turn should be 1/2, got", round(math.cos(math.tau/6), 2))
- print("Sin of a quarter turn should be 1, go", round(math.sin(math.tau/4), 2))
- Tan of an eighth turn should be 1, got 1.0
- Cos of an sixth turn should be 1/2, got 0.5
- Sin of a quarter turn should be 1, go 1.0
os.fspath
從 Python 3.6 開始,有一個神奇的方法表示“轉(zhuǎn)換為文件系統(tǒng)路徑”。當(dāng)給定一個 str 或 bytes 時,它返回輸入。
對于所有類型的對象,它尋找 __fspath__ 方法并調(diào)用它。這允許傳遞的對象是“帶有元數(shù)據(jù)的文件名”。
像 open() 或 stat 這樣的普通函數(shù)仍然能夠使用它們,只要 __fspath__ 返回正確的東西。
例如,這里有一個函數(shù)將一些數(shù)據(jù)寫入一個文件,然后檢查其大小。它還將文件名記錄到標(biāo)準(zhǔn)輸出,以便追蹤:
- def write_and_test(filename):
- print("writing into", filename)
- with open(filename, "w") as fpout:
- fpout.write("hello")
- print("size of", filename, "is", os.path.getsize(filename))
你可以用你期望的方式來調(diào)用它,用一個字符串作為文件名:
- write_and_test("plain.txt")
- writing into plain.txt
- size of plain.txt is 5
然而,可以定義一個新的類,為文件名的字符串表示法添加信息。這樣可以使日志記錄更加詳細(xì),而不改變原來的功能:
- class DocumentedFileName:
- def __init__(self, fname, why):
- self.fname = fname
- self.why = why
- def __fspath__(self):
- return self.fname
- def __repr__(self):
- return f"DocumentedFileName(fname={self.fname!r}, why={self.why!r})"
用 DocumentedFileName 實例作為輸入運行該函數(shù),允許 open 和 os.getsize 函數(shù)繼續(xù)工作,同時增強日志:
- write_and_test(DocumentedFileName("documented.txt", "because it's fun"))
- writing into DocumentedFileName(fname='documented.txt', why="because it's fun")
- size of DocumentedFileName(fname='documented.txt', why="because it's fun") is 5
歡迎來到 2016 年
Python 3.6 是在五年前發(fā)布的,但是在這個版本中首次出現(xiàn)的一些特性非??幔覜]有得到充分利用。如果你還沒使用,那么將他們添加到你的工具箱中。