我有一个对象,我希望能够使用with关键字.我对实施上下文管理器的实际情况感到满意,但我正面对最佳实践问题.
该对象是文件的包装器.我计划用一个字符串(文件的路径)或者像文件一样初始化我的对象,这可以直接处理(文件里面有文件的可能性 - 所以我预见到一个明确的用例这与BytesIO等...)
所以__init__看起来像这样:
def __init__(self, file_to_process):
if isinstance(file_to_process, str):
self._underlying_stream = open(file_to_process, "rb") # it's the path to a file
elif isinstance(file_to_process, io.IOBase):
self._underlying_stream = file_to_process # its the file itself
else:
raise TypeError()
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,_underlying_stream在我的__exit__()功能中关闭它是最好的做法/接受/明智吗?当它成为一条小路时,它完全有道理,但如果它是一条小溪传入,它最让我感到不礼貌,最坏的情况是关闭self._underlying_stream- 我是否正确思考,如果是这样,是否有一个整洁的方式这个?
(注意:我考虑用a来包装流io.BufferedReader,但事实证明,关闭也将关闭底层流...)