Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/fsspec/registry.py: 71%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1from __future__ import annotations
3import importlib
4import types
5import warnings
7__all__ = ["registry", "get_filesystem_class", "default"]
9# internal, mutable
10_registry: dict[str, type] = {}
12# external, immutable
13registry = types.MappingProxyType(_registry)
14default = "file"
17def register_implementation(name, cls, clobber=False, errtxt=None):
18 """Add implementation class to the registry
20 Parameters
21 ----------
22 name: str
23 Protocol name to associate with the class
24 cls: class or str
25 if a class: fsspec-compliant implementation class (normally inherits from
26 ``fsspec.AbstractFileSystem``, gets added straight to the registry. If a
27 str, the full path to an implementation class like package.module.class,
28 which gets added to known_implementations,
29 so the import is deferred until the filesystem is actually used.
30 clobber: bool (optional)
31 Whether to overwrite a protocol with the same name; if False, will raise
32 instead.
33 errtxt: str (optional)
34 If given, then a failure to import the given class will result in this
35 text being given.
36 """
37 if isinstance(cls, str):
38 if name in known_implementations and clobber is False:
39 if cls != known_implementations[name]["class"]:
40 raise ValueError(
41 f"Name ({name}) already in the known_implementations and clobber "
42 f"is False"
43 )
44 else:
45 known_implementations[name] = {
46 "class": cls,
47 "err": errtxt or f"{cls} import failed for protocol {name}",
48 }
50 else:
51 if name in registry and clobber is False:
52 if _registry[name] is not cls:
53 raise ValueError(
54 f"Name ({name}) already in the registry and clobber is False"
55 )
56 else:
57 _registry[name] = cls
60# protocols mapped to the class which implements them. This dict can be
61# updated with register_implementation
62known_implementations = {
63 "abfs": {
64 "class": "adlfs.AzureBlobFileSystem",
65 "err": "Install adlfs to access Azure Datalake Gen2 and Azure Blob Storage",
66 },
67 "adl": {
68 "class": "adlfs.AzureDatalakeFileSystem",
69 "err": (
70 "Azure Data Lake Storage Gen1 is retired and no longer supported. Please "
71 "install adlfs and use the `az://` protocol to access Azure Blob Storage "
72 "and Azure Data Lake Storage Gen2 instead."
73 ),
74 },
75 "arrow_hdfs": {
76 "class": "fsspec.implementations.arrow.HadoopFileSystem",
77 "err": "pyarrow and local java libraries required for HDFS",
78 },
79 "async_wrapper": {
80 "class": "fsspec.implementations.asyn_wrapper.AsyncFileSystemWrapper",
81 },
82 "asynclocal": {
83 "class": "morefs.asyn_local.AsyncLocalFileSystem",
84 "err": "Install 'morefs[asynclocalfs]' to use AsyncLocalFileSystem",
85 },
86 "asyncwrapper": {
87 "class": "fsspec.implementations.asyn_wrapper.AsyncFileSystemWrapper",
88 },
89 "az": {
90 "class": "adlfs.AzureBlobFileSystem",
91 "err": "Install adlfs to access Azure Datalake Gen2 and Azure Blob Storage",
92 },
93 "blockcache": {"class": "fsspec.implementations.cached.CachingFileSystem"},
94 "box": {
95 "class": "boxfs.BoxFileSystem",
96 "err": "Please install boxfs to access BoxFileSystem",
97 },
98 "cached": {"class": "fsspec.implementations.cached.CachingFileSystem"},
99 "dask": {
100 "class": "fsspec.implementations.dask.DaskWorkerFileSystem",
101 "err": "Install dask distributed to access worker file system",
102 },
103 "data": {"class": "fsspec.implementations.data.DataFileSystem"},
104 "dbfs": {
105 "class": "fsspec.implementations.dbfs.DatabricksFileSystem",
106 "err": "Install the requests package to use the DatabricksFileSystem",
107 },
108 "dir": {"class": "fsspec.implementations.dirfs.DirFileSystem"},
109 "dropbox": {
110 "class": "dropboxdrivefs.DropboxDriveFileSystem",
111 "err": (
112 'DropboxFileSystem requires "dropboxdrivefs","requests" and "'
113 '"dropbox" to be installed'
114 ),
115 },
116 "dvc": {
117 "class": "dvc.api.DVCFileSystem",
118 "err": "Install dvc to access DVCFileSystem",
119 },
120 "file": {"class": "fsspec.implementations.local.LocalFileSystem"},
121 "filecache": {"class": "fsspec.implementations.cached.WholeFileCacheFileSystem"},
122 "ftp": {"class": "fsspec.implementations.ftp.FTPFileSystem"},
123 "gcs": {
124 "class": "gcsfs.GCSFileSystem",
125 "err": "Please install gcsfs to access Google Storage",
126 },
127 "gdrive": {
128 "class": "gdrive_fsspec.GoogleDriveFileSystem",
129 "err": "Please install gdrive_fs for access to Google Drive",
130 },
131 "generic": {"class": "fsspec.generic.GenericFileSystem"},
132 "gist": {
133 "class": "fsspec.implementations.gist.GistFileSystem",
134 "err": "Install the requests package to use the gist FS",
135 },
136 "git": {
137 "class": "fsspec.implementations.git.GitFileSystem",
138 "err": "Install pygit2 to browse local git repos",
139 },
140 "github": {
141 "class": "fsspec.implementations.github.GithubFileSystem",
142 "err": "Install the requests package to use the github FS",
143 },
144 "gs": {
145 "class": "gcsfs.GCSFileSystem",
146 "err": "Please install gcsfs to access Google Storage",
147 },
148 "hdfs": {
149 "class": "fsspec.implementations.arrow.HadoopFileSystem",
150 "err": "pyarrow and local java libraries required for HDFS",
151 },
152 "hf": {
153 "class": "huggingface_hub.HfFileSystem",
154 "err": "Install huggingface_hub to access HfFileSystem",
155 },
156 "http": {
157 "class": "fsspec.implementations.http.HTTPFileSystem",
158 "err": 'HTTPFileSystem requires "requests" and "aiohttp" to be installed',
159 },
160 "https": {
161 "class": "fsspec.implementations.http.HTTPFileSystem",
162 "err": 'HTTPFileSystem requires "requests" and "aiohttp" to be installed',
163 },
164 "ia": {
165 "class": "fsspec.implementations.ia.InternetArchiveFileSystem",
166 "err": 'InternetArchiveFileSystem requires "requests" and "aiohttp" to be installed',
167 },
168 "jlab": {
169 "class": "fsspec.implementations.jupyter.JupyterFileSystem",
170 "err": "Jupyter FS requires requests to be installed",
171 },
172 "jupyter": {
173 "class": "fsspec.implementations.jupyter.JupyterFileSystem",
174 "err": "Jupyter FS requires requests to be installed",
175 },
176 "lakefs": {
177 "class": "lakefs_spec.LakeFSFileSystem",
178 "err": "Please install lakefs-spec to access LakeFSFileSystem",
179 },
180 "libarchive": {
181 "class": "fsspec.implementations.libarchive.LibArchiveFileSystem",
182 "err": "LibArchive requires to be installed",
183 },
184 "local": {"class": "fsspec.implementations.local.LocalFileSystem"},
185 "memory": {"class": "fsspec.implementations.memory.MemoryFileSystem"},
186 "oci": {
187 "class": "ocifs.OCIFileSystem",
188 "err": "Install ocifs to access OCI Object Storage",
189 },
190 "ocilake": {
191 "class": "ocifs.OCIFileSystem",
192 "err": "Install ocifs to access OCI Data Lake",
193 },
194 "oss": {
195 "class": "ossfs.OSSFileSystem",
196 "err": "Install ossfs to access Alibaba Object Storage System",
197 },
198 "pyscript": {
199 "class": "pyscript_fsspec_client.client.PyscriptFileSystem",
200 "err": "This only runs in a pyscript context",
201 },
202 "reference": {"class": "fsspec.implementations.reference.ReferenceFileSystem"},
203 "root": {
204 "class": "fsspec_xrootd.XRootDFileSystem",
205 "err": (
206 "Install fsspec-xrootd to access xrootd storage system. "
207 "Note: 'root' is the protocol name for xrootd storage systems, "
208 "not referring to root directories"
209 ),
210 },
211 "s3": {"class": "s3fs.S3FileSystem", "err": "Install s3fs to access S3"},
212 "s3a": {"class": "s3fs.S3FileSystem", "err": "Install s3fs to access S3"},
213 "sftp": {
214 "class": "fsspec.implementations.sftp.SFTPFileSystem",
215 "err": 'SFTPFileSystem requires "paramiko" to be installed',
216 },
217 "simplecache": {"class": "fsspec.implementations.cached.SimpleCacheFileSystem"},
218 "smb": {
219 "class": "fsspec.implementations.smb.SMBFileSystem",
220 "err": 'SMB requires "smbprotocol" or "smbprotocol[kerberos]" installed',
221 },
222 "ssh": {
223 "class": "fsspec.implementations.sftp.SFTPFileSystem",
224 "err": 'SFTPFileSystem requires "paramiko" to be installed',
225 },
226 "tar": {"class": "fsspec.implementations.tar.TarFileSystem"},
227 "tos": {
228 "class": "tosfs.TosFileSystem",
229 "err": "Install tosfs to access ByteDance volcano engine Tinder Object Storage",
230 },
231 "tosfs": {
232 "class": "tosfs.TosFileSystem",
233 "err": "Install tosfs to access ByteDance volcano engine Tinder Object Storage",
234 },
235 "wandb": {"class": "wandbfs.WandbFS", "err": "Install wandbfs to access wandb"},
236 "webdav": {
237 "class": "webdav4.fsspec.WebdavFileSystem",
238 "err": "Install webdav4 to access WebDAV",
239 },
240 "webhdfs": {
241 "class": "fsspec.implementations.webhdfs.WebHDFS",
242 "err": 'webHDFS access requires "requests" to be installed',
243 },
244 "zip": {"class": "fsspec.implementations.zip.ZipFileSystem"},
245}
247assert list(known_implementations) == sorted(known_implementations), (
248 "Not in alphabetical order"
249)
252def get_filesystem_class(protocol):
253 """Fetch named protocol implementation from the registry
255 The dict ``known_implementations`` maps protocol names to the locations
256 of classes implementing the corresponding file-system. When used for the
257 first time, appropriate imports will happen and the class will be placed in
258 the registry. All subsequent calls will fetch directly from the registry.
260 Some protocol implementations require additional dependencies, and so the
261 import may fail. In this case, the string in the "err" field of the
262 ``known_implementations`` will be given as the error message.
263 """
264 if not protocol:
265 protocol = default
267 if protocol not in registry:
268 if protocol not in known_implementations:
269 raise ValueError(f"Protocol not known: {protocol}")
270 bit = known_implementations[protocol]
271 try:
272 register_implementation(protocol, _import_class(bit["class"]))
273 except ImportError as e:
274 raise ImportError(bit.get("err")) from e
275 cls = registry[protocol]
276 if getattr(cls, "protocol", None) in ("abstract", None):
277 cls.protocol = protocol
279 return cls
282s3_msg = """Your installed version of s3fs is very old and known to cause
283severe performance issues, see also https://github.com/dask/dask/issues/10276
285To fix, you should specify a lower version bound on s3fs, or
286update the current installation.
287"""
290def _import_class(fqp: str):
291 """Take a fully-qualified path and return the imported class or identifier.
293 ``fqp`` is of the form "package.module.klass" or
294 "package.module:subobject.klass".
296 Warnings
297 --------
298 This can import arbitrary modules. Make sure you haven't installed any modules
299 that may execute malicious code at import time.
300 """
301 if ":" in fqp:
302 mod, name = fqp.rsplit(":", 1)
303 else:
304 mod, name = fqp.rsplit(".", 1)
306 is_s3 = mod == "s3fs"
307 mod = importlib.import_module(mod)
308 if is_s3 and mod.__version__.split(".") < ["0", "5"]:
309 warnings.warn(s3_msg)
310 for part in name.split("."):
311 mod = getattr(mod, part)
313 if not isinstance(mod, type):
314 raise TypeError(f"{fqp} is not a class")
316 return mod
319def filesystem(protocol, **storage_options):
320 """Instantiate filesystems for given protocol and arguments
322 ``storage_options`` are specific to the protocol being chosen, and are
323 passed directly to the class.
324 """
325 if protocol == "arrow_hdfs":
326 warnings.warn(
327 "The 'arrow_hdfs' protocol has been deprecated and will be "
328 "removed in the future. Specify it as 'hdfs'.",
329 DeprecationWarning,
330 )
332 cls = get_filesystem_class(protocol)
333 return cls(**storage_options)
336def available_protocols():
337 """Return a list of the implemented protocols.
339 Note that any given protocol may require extra packages to be importable.
340 """
341 return list(known_implementations)