python - python 函数可以既是生成器又是 "non-generator"吗?

标签 python generator

我有一个函数,我想从(生成器行为)生成字节,并根据是否设置了 save bool 值写入文件(非生成器行为)。这可能吗?

def encode_file(source, save=False, destination=None):
    # encode the contents of an input file 3 bytes at a time
    print('hello')
    with open(source, 'rb') as infile:
        # save bytes to destination file
        if save:
            print(f'saving to file {destination}')
            with open(destination, 'wb') as outfile:
                while (bytes_to_encode := infile.read(3)):
                    l = len(bytes_to_encode)
                    if l < 3:
                        bytes_to_encode += (b'\x00' * (3 - l))
                    outfile.write(bytes_to_encode)
            return
        # yield bytes to caller
        else:
            while (bytes_to_encode := infile.read(3)):
                l = len(bytes_to_encode)
                if l < 3:
                    bytes_to_encode += (b'\x00' * (3 - l)) # pad bits if short
                yield encode(bytes_to_encode)
            return

在上面的实现中,函数始终充当生成器。当我打电话时

encode_file('file.bin', save=True, destination='output.base64')

它不会打印“hello”,而是返回一个生成器对象。这对我来说没有意义。难道不应该打印“hello”,然后不应该将控制定向到代码的 if save: 部分,从而避免函数中完全产生的部分吗?

最佳答案

函数不能生成器,也不能是生成器,但是当然您可以通过定义辅助函数来决定是否返回生成器对象。为了避免在两者之间重复(读取)with(并减少一般冗余),请将一个分支作为另一个分支的客户端:

def encode_file(source, save=False, destination=None):
    # encode the contents of an input file 3 bytes at a time
    print('hello')
    # save bytes to destination file
    if save:
        print(f'saving to file {destination}')
        with open(destination, 'wb') as outfile:
            for bytes_to_encode in encode_file(source):
                outfile.write(bytes_to_encode)
    # yield bytes to caller
    else:
        def g():
            with open(source, 'rb') as infile:
                while (bytes_to_encode := infile.read(3)):
                    l = len(bytes_to_encode)
                    if l < 3:
                        bytes_to_encode += (b'\x00' * (3 - l)) # pad bits if short
                    yield encode(bytes_to_encode)
        return g()

(感谢 interjay 指出 gwith 的需要。)

关于python - python 函数可以既是生成器又是 "non-generator"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76352280/

相关文章:

python - Pandas 中的字符串清理问题

python - 使用 python 和 xpath 进行字符串连接

python - Python 生成器中的反向 next()

python - python中的HTTPConnection请求socket.gaierror

python - 动态报告的 Django 和 reportlab 问题

python - 当在查询中使用fields选项时,elasticsearch-py搜索返回列表对象

Python 生成器 : confusing result

python - 使用生成器对生成器进行排序?

python - 在这种情况下使用生成器有什么好处?

python - Python 中的控制台菜单生成器