Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/fsspec/registry.py: 73%
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": "Install adlfs to access Azure Datalake Gen1",
70 },
71 "arrow_hdfs": {
72 "class": "fsspec.implementations.arrow.HadoopFileSystem",
73 "err": "pyarrow and local java libraries required for HDFS",
74 },
75 "asynclocal": {
76 "class": "morefs.asyn_local.AsyncLocalFileSystem",
77 "err": "Install 'morefs[asynclocalfs]' to use AsyncLocalFileSystem",
78 },
79 "az": {
80 "class": "adlfs.AzureBlobFileSystem",
81 "err": "Install adlfs to access Azure Datalake Gen2 and Azure Blob Storage",
82 },
83 "blockcache": {"class": "fsspec.implementations.cached.CachingFileSystem"},
84 "box": {
85 "class": "boxfs.BoxFileSystem",
86 "err": "Please install boxfs to access BoxFileSystem",
87 },
88 "cached": {"class": "fsspec.implementations.cached.CachingFileSystem"},
89 "dask": {
90 "class": "fsspec.implementations.dask.DaskWorkerFileSystem",
91 "err": "Install dask distributed to access worker file system",
92 },
93 "data": {"class": "fsspec.implementations.data.DataFileSystem"},
94 "dbfs": {
95 "class": "fsspec.implementations.dbfs.DatabricksFileSystem",
96 "err": "Install the requests package to use the DatabricksFileSystem",
97 },
98 "dir": {"class": "fsspec.implementations.dirfs.DirFileSystem"},
99 "dropbox": {
100 "class": "dropboxdrivefs.DropboxDriveFileSystem",
101 "err": (
102 'DropboxFileSystem requires "dropboxdrivefs","requests" and "'
103 '"dropbox" to be installed'
104 ),
105 },
106 "dvc": {
107 "class": "dvc.api.DVCFileSystem",
108 "err": "Install dvc to access DVCFileSystem",
109 },
110 "file": {"class": "fsspec.implementations.local.LocalFileSystem"},
111 "filecache": {"class": "fsspec.implementations.cached.WholeFileCacheFileSystem"},
112 "ftp": {"class": "fsspec.implementations.ftp.FTPFileSystem"},
113 "gcs": {
114 "class": "gcsfs.GCSFileSystem",
115 "err": "Please install gcsfs to access Google Storage",
116 },
117 "gdrive": {
118 "class": "gdrivefs.GoogleDriveFileSystem",
119 "err": "Please install gdrivefs for access to Google Drive",
120 },
121 "generic": {"class": "fsspec.generic.GenericFileSystem"},
122 "git": {
123 "class": "fsspec.implementations.git.GitFileSystem",
124 "err": "Install pygit2 to browse local git repos",
125 },
126 "github": {
127 "class": "fsspec.implementations.github.GithubFileSystem",
128 "err": "Install the requests package to use the github FS",
129 },
130 "gs": {
131 "class": "gcsfs.GCSFileSystem",
132 "err": "Please install gcsfs to access Google Storage",
133 },
134 "hdfs": {
135 "class": "fsspec.implementations.arrow.HadoopFileSystem",
136 "err": "pyarrow and local java libraries required for HDFS",
137 },
138 "hf": {
139 "class": "huggingface_hub.HfFileSystem",
140 "err": "Install huggingface_hub to access HfFileSystem",
141 },
142 "http": {
143 "class": "fsspec.implementations.http.HTTPFileSystem",
144 "err": 'HTTPFileSystem requires "requests" and "aiohttp" to be installed',
145 },
146 "https": {
147 "class": "fsspec.implementations.http.HTTPFileSystem",
148 "err": 'HTTPFileSystem requires "requests" and "aiohttp" to be installed',
149 },
150 "jlab": {
151 "class": "fsspec.implementations.jupyter.JupyterFileSystem",
152 "err": "Jupyter FS requires requests to be installed",
153 },
154 "jupyter": {
155 "class": "fsspec.implementations.jupyter.JupyterFileSystem",
156 "err": "Jupyter FS requires requests to be installed",
157 },
158 "lakefs": {
159 "class": "lakefs_spec.LakeFSFileSystem",
160 "err": "Please install lakefs-spec to access LakeFSFileSystem",
161 },
162 "libarchive": {
163 "class": "fsspec.implementations.libarchive.LibArchiveFileSystem",
164 "err": "LibArchive requires to be installed",
165 },
166 "local": {"class": "fsspec.implementations.local.LocalFileSystem"},
167 "memory": {"class": "fsspec.implementations.memory.MemoryFileSystem"},
168 "oci": {
169 "class": "ocifs.OCIFileSystem",
170 "err": "Install ocifs to access OCI Object Storage",
171 },
172 "ocilake": {
173 "class": "ocifs.OCIFileSystem",
174 "err": "Install ocifs to access OCI Data Lake",
175 },
176 "oss": {
177 "class": "ossfs.OSSFileSystem",
178 "err": "Install ossfs to access Alibaba Object Storage System",
179 },
180 "reference": {"class": "fsspec.implementations.reference.ReferenceFileSystem"},
181 "root": {
182 "class": "fsspec_xrootd.XRootDFileSystem",
183 "err": (
184 "Install fsspec-xrootd to access xrootd storage system. "
185 "Note: 'root' is the protocol name for xrootd storage systems, "
186 "not referring to root directories"
187 ),
188 },
189 "s3": {"class": "s3fs.S3FileSystem", "err": "Install s3fs to access S3"},
190 "s3a": {"class": "s3fs.S3FileSystem", "err": "Install s3fs to access S3"},
191 "sftp": {
192 "class": "fsspec.implementations.sftp.SFTPFileSystem",
193 "err": 'SFTPFileSystem requires "paramiko" to be installed',
194 },
195 "simplecache": {"class": "fsspec.implementations.cached.SimpleCacheFileSystem"},
196 "smb": {
197 "class": "fsspec.implementations.smb.SMBFileSystem",
198 "err": 'SMB requires "smbprotocol" or "smbprotocol[kerberos]" installed',
199 },
200 "ssh": {
201 "class": "fsspec.implementations.sftp.SFTPFileSystem",
202 "err": 'SFTPFileSystem requires "paramiko" to be installed',
203 },
204 "tar": {"class": "fsspec.implementations.tar.TarFileSystem"},
205 "wandb": {"class": "wandbfs.WandbFS", "err": "Install wandbfs to access wandb"},
206 "webdav": {
207 "class": "webdav4.fsspec.WebdavFileSystem",
208 "err": "Install webdav4 to access WebDAV",
209 },
210 "webhdfs": {
211 "class": "fsspec.implementations.webhdfs.WebHDFS",
212 "err": 'webHDFS access requires "requests" to be installed',
213 },
214 "zip": {"class": "fsspec.implementations.zip.ZipFileSystem"},
215}
217assert list(known_implementations) == sorted(
218 known_implementations
219), "Not in alphabetical order"
222def get_filesystem_class(protocol):
223 """Fetch named protocol implementation from the registry
225 The dict ``known_implementations`` maps protocol names to the locations
226 of classes implementing the corresponding file-system. When used for the
227 first time, appropriate imports will happen and the class will be placed in
228 the registry. All subsequent calls will fetch directly from the registry.
230 Some protocol implementations require additional dependencies, and so the
231 import may fail. In this case, the string in the "err" field of the
232 ``known_implementations`` will be given as the error message.
233 """
234 if not protocol:
235 protocol = default
237 if protocol not in registry:
238 if protocol not in known_implementations:
239 raise ValueError(f"Protocol not known: {protocol}")
240 bit = known_implementations[protocol]
241 try:
242 register_implementation(protocol, _import_class(bit["class"]))
243 except ImportError as e:
244 raise ImportError(bit["err"]) from e
245 cls = registry[protocol]
246 if getattr(cls, "protocol", None) in ("abstract", None):
247 cls.protocol = protocol
249 return cls
252s3_msg = """Your installed version of s3fs is very old and known to cause
253severe performance issues, see also https://github.com/dask/dask/issues/10276
255To fix, you should specify a lower version bound on s3fs, or
256update the current installation.
257"""
260def _import_class(fqp: str):
261 """Take a fully-qualified path and return the imported class or identifier.
263 ``fqp`` is of the form "package.module.klass" or
264 "package.module:subobject.klass".
266 Warnings
267 --------
268 This can import arbitrary modules. Make sure you haven't installed any modules
269 that may execute malicious code at import time.
270 """
271 if ":" in fqp:
272 mod, name = fqp.rsplit(":", 1)
273 else:
274 mod, name = fqp.rsplit(".", 1)
276 is_s3 = mod == "s3fs"
277 mod = importlib.import_module(mod)
278 if is_s3 and mod.__version__.split(".") < ["0", "5"]:
279 warnings.warn(s3_msg)
280 for part in name.split("."):
281 mod = getattr(mod, part)
283 if not isinstance(mod, type):
284 raise TypeError(f"{fqp} is not a class")
286 return mod
289def filesystem(protocol, **storage_options):
290 """Instantiate filesystems for given protocol and arguments
292 ``storage_options`` are specific to the protocol being chosen, and are
293 passed directly to the class.
294 """
295 if protocol == "arrow_hdfs":
296 warnings.warn(
297 "The 'arrow_hdfs' protocol has been deprecated and will be "
298 "removed in the future. Specify it as 'hdfs'.",
299 DeprecationWarning,
300 )
302 cls = get_filesystem_class(protocol)
303 return cls(**storage_options)
306def available_protocols():
307 """Return a list of the implemented protocols.
309 Note that any given protocol may require extra packages to be importable.
310 """
311 return list(known_implementations)