您是否正在为 Python 3.6 的文件系统使用这种神奇的方法?

探索 os.fspath 和另外两个未被充分利用但仍然有用的 Python 功能。
53 位读者喜欢这篇文章。
Computer screen with files or windows open

Opensource.com

这是关于 Python 3.x 版本中首次出现的功能系列文章的第七篇。Python 3.6 于 2016 年首次发布,尽管已经发布了一段时间,但它引入的许多功能仍然未被充分利用且非常酷。以下是其中三个。

分隔的数字常量

快速回答,10000000200000 哪个更大?您能在浏览代码时正确回答吗?根据当地的习惯,在散文写作中,您会使用 10,000,000 或 10.000.000 来表示第一个数字。问题是,Python 使用逗号和句点还有其他原因。

幸运的是,自 Python 3.6 以来,您可以使用下划线来分隔数字。这在代码中直接使用以及从字符串使用 int() 转换器时都有效

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 度角是一个转角的八分之一要容易得多。正如 Tau 宣言 所解释的那样,,称为 Τ,是一个更自然的常数。

在 Python 3.6 及更高版本中,您的数学代码可以使用更直观的常数

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 开始,有一个神奇的方法表示“转换为文件系统路径”。当给定 strbytes 时,它返回输入。

对于所有类型的对象,它会查找 __fspath__ 方法并调用它。这允许传递“带有元数据的文件名”对象。

open()stat 这样的普通函数仍然可以使用它们,只要 __fspath__ 返回正确的东西。

例如,这是一个将一些数据写入文件然后检查其大小的函数。它还记录文件名到标准输出以进行跟踪

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))

您可以像期望的那样调用它,使用字符串作为文件名

write_and_test("plain.txt")
    writing into plain.txt
    size of plain.txt is 5

但是,可以定义一个新类,将信息添加到文件名的字符串表示形式中。这允许日志记录更详细,而无需更改原始函数

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 实例作为输入运行该函数允许 openos.getsize 函数继续工作,同时增强日志记录

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 大约在五年前发布,但此版本中首次出现的一些功能很酷且未被充分利用。如果您还没有,请将它们添加到您的工具包中。

接下来阅读什么
标签
Moshe sitting down, head slightly to the side. His t-shirt has Guardians of the Galaxy silhoutes against a background of sound visualization bars.
自 1998 年以来,Moshe 一直参与 Linux 社区,帮助举办 Linux “安装聚会”。他从 1999 年开始编写 Python 程序,并为核心 Python 解释器做出了贡献。Moshe 在这些术语出现之前就一直是 DevOps/SRE,他非常关心软件可靠性、构建可重现性以及其他此类事情。

评论已关闭。

Creative Commons License本作品根据 Creative Commons 许可协议 授权,许可协议为署名-相同方式共享 4.0 国际许可。
© . All rights reserved.