open_file#
- open_file(path_arg, mode='r')[source]#
用于确保文件的干净打开和关闭的装饰器。
- 参数:
- path_arg字符串或整数
作为路径的参数的名称或索引。
- mode字符串
打开模式的字符串。
- 返回值:
- _open_file函数
干净地执行 I/O 的函数。
注意
请注意,此装饰器解决了路径参数指定为字符串时的问题,但它不处理函数希望接受默认值 None(然后处理)的情况。
以下是如何处理这种情况的示例
@open_file("path") def some_function(arg1, arg2, path=None): if path is None: fobj = tempfile.NamedTemporaryFile(delete=False) else: # `path` could have been a string or file object or something # similar. In any event, the decorator has given us a file object # and it will close it for us, if it should. fobj = path try: fobj.write("blah") finally: if path is None: fobj.close()
通常,我们会想使用“with”来确保 fobj 被关闭。然而,装饰器会将
path
为我们转换为文件对象,而使用“with”会意外地关闭该文件对象。相反,我们使用 try 块,如上所示。当我们退出函数时,fobj 将由装饰器关闭(如果需要的话)。示例
像这样装饰函数
@open_file(0, "r") def read_function(pathname): pass @open_file(1, "w") def write_function(G, pathname): pass @open_file(1, "w") def write_function(G, pathname="graph.dot"): pass @open_file("pathname", "w") def write_function(G, pathname="graph.dot"): pass @open_file("path", "w+") def another_function(arg, **kwargs): path = kwargs["path"] pass