繁体   English   中英

在Python装饰器中创建参数以供装饰函数使用

[英]Creating parameters in a Python decorator for use by the decorated function

我有几个使用tempfile.mkstemp()的函数来创建和使用在函数被调用后保留在磁盘上的临时文件。 当函数退出时,它们每个都重复相同的脚手架代码以清理文件描述符。 例如:

import tempfile
import zipfile
import os

def write_zip(test_name: str) -> str:
    """
    Given a test name, returns an archive (ZIP) of the files in that test.
    """

    try:
        fd, zip_path = tempfile.mkstemp(suffix='.zip')

        with zipfile.ZipFile(zip_path, 'w') as zf:
            for fpath in _list_files(test_name):  # _list_files() not shown
                zf.write(fpath, arcname=os.path.basename(fpath))
    finally:
        try:
            os.close(locals()['fd'])
        except KeyError:
            pass

    return zip_path

我想把这个最终尝试的脚手架拉到一个装饰器上。 我尝试写一个,但是我有点迷茫,它不起作用:

def _persistent_temp_file(func):
    """
    Decorator for a function that uses a temporary file that should persist on disk after the function has exited.
    Closes the file descriptor in a try-finally block so the function doesn't have to. 
    """

    def scaffolding(suffix=None, prefix=None, dir=None, text=False):
        try:
            fd, temp_file = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir, text=text)
            func(temp_file)

        finally:
            try:
                os.close(locals()['fd'])
            except KeyError:
                pass

    return scaffolding


@_persistent_temp_file
def write_zip(test_name: str) -> str:
    with zipfile.ZipFile(zip_path, 'w') as zf:
        for fpath in _list_files(test_name):  # _list_files() not shown
            zf.write(fpath, arcname=os.path.basename(fpath))

    return zip_path

我不确定如何将zip_file参数传递给此函数(或任何其他装饰函数)。 我不确定我也不知道如何传递mkstemp()所需的参数。 (即调用装饰函数时如何指定文件后缀?)

您想要创建一个上下文管理器,而不是使用装饰 当代码块(上下文)退出时,将通知上下文管理器,因此您可以在此之后自行清理。

具有讽刺意味的是,有一个装饰器可以轻松地编写上下文管理器,称为@contextlib.contextmanager

from contextlib import contextmanager

@contextmanager
def _persistent_temp_file(suffix=None, prefix=None, dir=None, text=False):
    fd = None
    try:
        fd, temp_file = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir, text=text)
        yield temp_file
    finally:
        if fd is not None:
            os.close(fd)

注意yield temp_file行; 这是在其中该功能被暂停的点,并且temp_file值然后从所得的上下文管理器返回__enter__方法,并且变得可用于as子句。

然后在with语句中使用它:

def write_zip(test_name: str) -> str:
    with _persistent_temp_file() as zip_path:
        with zipfile.ZipFile(zip_path, 'w') as zf:
            for fpath in _list_files(test_name):  # _list_files() not shown
                zf.write(fpath, arcname=os.path.basename(fpath))
    return zip_path

并不是说您需要在这里重新发明持久性临时文件轮。 您可以只在这里使用tempfile.NamedTempFile()对象:

from tempfile import NamedTempFile

def write_zip(test_name: str) -> str:
    with NamedTempFile(delete=False) as temp_file:
        with zipfile.ZipFile(temp_file, 'w') as zf:
            for fpath in _list_files(test_name):  # _list_files() not shown
                zf.write(fpath, arcname=os.path.basename(fpath))
    return temp_file.name

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM