支持文件名、路径和缓冲区输入。

4

在我的Python包中常见的要求是允许文件输入,可以是字符串文件名、pathlib.Path或已打开的缓冲区。我通常将缓冲区分离出来,例如:

def foo_from_file(filename, *args, **kwargs):
    with open(filename) as f:
        foo_from_buffer(f, *args, **kwargs)


def foo_from_buffer(f):
    f.readline()
    # do something
    return

但从用户的角度来看,更清晰的方法可能是

def foo(file_or_buffer):
    if hasattr(file_or_buffer, "readline"):  # ???
        f = file_or_buffer
    else:
        f = open(file_or_buffer)

    f.readline()

(这个特定的实现方式不是很好,因为它没有在失败时执行close()。)

file_or_buffer 是 Python 方法中常见的参数吗?还是你要区分这两者?如何最好地实现它?

1个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
1

根据我之前关于已打开的数据库连接可以作为参数传递或不传递的类似问题进行调整,您可以使用nullcontext来在任何你传递进来的内容拥有readline时“什么都不做”:

from contextlib import nullcontext
from pathlib import Path
from io import StringIO

def foo(file_or_buffer):
    if hasattr(file_or_buffer, "readline"):
        cm = nullcontext(file_or_buffer)
    else:
        cm = open(file_or_buffer)

    with cm as f:
        line = f.readline()
        print(line)
    
pa = Path(__file__)

foo(pa)
foo(f"{pa}")

with pa.open() as fi:
    foo(fi)
with pa.open() as fi:
    buffer = StringIO(fi.read())
foo(buffer)

输出:

from contextlib import nullcontext

from contextlib import nullcontext

from contextlib import nullcontext

from contextlib import nullcontext

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,