我有一个函数,我想从(生成器行为)生成字节,并根据是否设置了 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 指出 g
中 with
的需要。)
关于python - python 函数可以既是生成器又是 "non-generator"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76352280/