MCPcopy Index your code
hub / github.com/pydata/xarray / CachingFileManager

Class CachingFileManager

xarray/backends/file_manager.py:58–298  ·  view source on GitHub ↗

Wrapper for automatically opening and closing file objects. Unlike files, CachingFileManager objects can be safely pickled and passed between processes. They should be explicitly closed to release resources, but a per-process least-recently-used cache for open files ensures that you

Source from the content-addressed store, hash-verified

56
57
58class CachingFileManager(FileManager[T_File]):
59 """Wrapper for automatically opening and closing file objects.
60
61 Unlike files, CachingFileManager objects can be safely pickled and passed
62 between processes. They should be explicitly closed to release resources,
63 but a per-process least-recently-used cache for open files ensures that you
64 can safely create arbitrarily large numbers of FileManager objects.
65
66 Don't directly close files acquired from a FileManager. Instead, call
67 FileManager.close(), which ensures that closed files are removed from the
68 cache as well.
69
70 Example usage::
71
72 manager = FileManager(open, "example.txt", mode="w")
73 f = manager.acquire()
74 f.write(...)
75 manager.close() # ensures file is closed
76
77 Note that as long as previous files are still cached, acquiring a file
78 multiple times from the same FileManager is essentially free::
79
80 f1 = manager.acquire()
81 f2 = manager.acquire()
82 assert f1 is f2
83
84 """
85
86 def __init__(
87 self,
88 opener: Callable[..., T_File],
89 *args: Any,
90 mode: Any = _OMIT_MODE,
91 kwargs: Mapping[str, Any] | None = None,
92 lock: Lock | None | Literal[False] = None,
93 cache: MutableMapping[Any, T_File] | None = None,
94 manager_id: Hashable | None = None,
95 ref_counts: dict[Any, int] | None = None,
96 ):
97 """Initialize a CachingFileManager.
98
99 The cache, manager_id and ref_counts arguments exist solely to
100 facilitate dependency injection, and should only be set for tests.
101
102 Parameters
103 ----------
104 opener : callable
105 Function that when called like ``opener(*args, **kwargs)`` returns
106 an open file object. The file object must implement a ``close()``
107 method.
108 *args
109 Positional arguments for opener. A ``mode`` argument should be
110 provided as a keyword argument (see below). All arguments must be
111 hashable.
112 mode : optional
113 If provided, passed as a keyword argument to ``opener`` along with
114 ``**kwargs``. ``mode='w' `` has special treatment: after the first
115 call it is replaced by ``mode='a'`` in all subsequent function to

Calls

no outgoing calls

Used in the wild real call sites across dependent graphs

searching dependent graphs…