METADATA 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. Metadata-Version: 2.1
  2. Name: universal_pathlib
  3. Version: 0.2.6
  4. Summary: pathlib api extended to use fsspec backends
  5. Author-email: Andrew Fulton <andrewfulton9@gmail.com>
  6. Maintainer: Norman Rzepka
  7. Maintainer-email: Andreas Poehlmann <andreas@poehlmann.io>
  8. License: MIT License
  9. Project-URL: Homepage, https://github.com/fsspec/universal_pathlib
  10. Project-URL: Changelog, https://github.com/fsspec/universal_pathlib/blob/main/CHANGELOG.md
  11. Keywords: filesystem-spec,pathlib
  12. Classifier: Programming Language :: Python :: 3
  13. Classifier: Programming Language :: Python :: 3.8
  14. Classifier: Programming Language :: Python :: 3.9
  15. Classifier: Programming Language :: Python :: 3.10
  16. Classifier: Programming Language :: Python :: 3.11
  17. Classifier: Programming Language :: Python :: 3.12
  18. Classifier: Programming Language :: Python :: 3.13
  19. Classifier: Development Status :: 4 - Beta
  20. Requires-Python: >=3.8
  21. Description-Content-Type: text/markdown
  22. License-File: LICENSE
  23. Requires-Dist: fsspec!=2024.3.1,>=2022.1.0
  24. Provides-Extra: tests
  25. Requires-Dist: pytest>=8; extra == "tests"
  26. Requires-Dist: pytest-sugar>=0.9.7; extra == "tests"
  27. Requires-Dist: pytest-cov>=4.1.0; extra == "tests"
  28. Requires-Dist: pytest-mock>=3.12.0; extra == "tests"
  29. Requires-Dist: pylint>=2.17.4; extra == "tests"
  30. Requires-Dist: mypy>=1.10.0; extra == "tests"
  31. Requires-Dist: pytest-mypy-plugins>=3.1.2; extra == "tests"
  32. Requires-Dist: packaging; extra == "tests"
  33. Provides-Extra: dev
  34. Requires-Dist: adlfs; extra == "dev"
  35. Requires-Dist: aiohttp; extra == "dev"
  36. Requires-Dist: requests; extra == "dev"
  37. Requires-Dist: gcsfs; extra == "dev"
  38. Requires-Dist: s3fs; extra == "dev"
  39. Requires-Dist: moto[s3,server]; extra == "dev"
  40. Requires-Dist: webdav4[fsspec]; extra == "dev"
  41. Requires-Dist: paramiko; extra == "dev"
  42. Requires-Dist: wsgidav; extra == "dev"
  43. Requires-Dist: cheroot; extra == "dev"
  44. Requires-Dist: pydantic; extra == "dev"
  45. Requires-Dist: pydantic-settings; extra == "dev"
  46. Requires-Dist: smbprotocol; extra == "dev"
  47. Requires-Dist: typing_extensions; python_version < "3.11" and extra == "dev"
  48. # Universal Pathlib
  49. [![PyPI](https://img.shields.io/pypi/v/universal_pathlib.svg)](https://pypi.org/project/universal_pathlib/)
  50. [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/universal_pathlib)](https://pypi.org/project/universal_pathlib/)
  51. [![PyPI - License](https://img.shields.io/pypi/l/universal_pathlib)](https://github.com/fsspec/universal_pathlib/blob/main/LICENSE)
  52. [![Conda (channel only)](https://img.shields.io/conda/vn/conda-forge/universal_pathlib?label=conda)](https://anaconda.org/conda-forge/universal_pathlib)
  53. [![Tests](https://github.com/fsspec/universal_pathlib/actions/workflows/tests.yml/badge.svg)](https://github.com/fsspec/universal_pathlib/actions/workflows/tests.yml)
  54. [![GitHub issues](https://img.shields.io/github/issues/fsspec/universal_pathlib)](https://github.com/fsspec/universal_pathlib/issues)
  55. [![Codestyle black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
  56. [![Changelog](https://img.shields.io/badge/changelog-Keep%20a%20Changelog-%23E05735)](./CHANGELOG.md)
  57. Universal Pathlib is a Python library that extends the [`pathlib.Path`][pathlib]
  58. API to support a variety of backend filesystems via [`filesystem_spec`][fsspec].
  59. [pathlib]: https://docs.python.org/3/library/pathlib.html
  60. [fsspec]: https://filesystem-spec.readthedocs.io/en/latest/intro.html
  61. ## Installation
  62. Install the latest version of `universal_pathlib` with pip or conda. Please note
  63. that while this will install `fsspec` as a dependency, for some filesystems, you
  64. have to install additional packages. For example, to use S3, you need to install
  65. `s3fs`, or better depend on `fsspec[s3]`:
  66. ### PyPI
  67. ```bash
  68. python -m pip install universal_pathlib
  69. ```
  70. ### conda
  71. ```bash
  72. conda install -c conda-forge universal_pathlib
  73. ```
  74. ### Adding universal_pathlib to your project
  75. Below is a `pyproject.toml` based example for adding `universal_pathlib` to your
  76. project as a dependency if you want to use it with `s3` and `http` filesystems:
  77. ```toml
  78. [project]
  79. name = "myproject"
  80. requires-python = ">=3.8"
  81. dependencies = [
  82. "universal_pathlib>=0.2.5",
  83. "fsspec[s3,http]",
  84. ]
  85. ```
  86. See [filesystem_spec/pyproject.toml][fsspec-pyproject-toml] for an overview of the available
  87. fsspec extras.
  88. [fsspec-pyproject-toml]:
  89. https://github.com/fsspec/filesystem_spec/blob/master/pyproject.toml#L26
  90. ## Basic Usage
  91. ```pycon
  92. # pip install universal_pathlib fsspec[s3]
  93. >>> from upath import UPath
  94. >>>
  95. >>> s3path = UPath("s3://test_bucket") / "example.txt"
  96. >>> s3path.name
  97. example.txt
  98. >>> s3path.stem
  99. example
  100. >>> s3path.suffix
  101. .txt
  102. >>> s3path.exists()
  103. True
  104. >>> s3path.read_text()
  105. 'Hello World'
  106. ```
  107. For more examples, see the [example notebook here][example-notebook].
  108. [example-notebook]: notebooks/examples.ipynb
  109. ### Currently supported filesystems (and protocols)
  110. - `file:` and `local:` Local filesystem
  111. - `memory:` Ephemeral filesystem in RAM
  112. - `az:`, `adl:`, `abfs:` and `abfss:` Azure Storage _(requires `adlfs`)_
  113. - `data:` RFC 2397 style data URLs _(requires `fsspec>=2023.12.2`)_
  114. - `github:` GitHub repository filesystem
  115. - `http:` and `https:` HTTP(S)-based filesystem
  116. - `hdfs:` Hadoop distributed filesystem
  117. - `gs:` and `gcs:` Google Cloud Storage _(requires `gcsfs`)_
  118. - `s3:` and `s3a:` AWS S3 _(requires `s3fs` to be installed)_
  119. - `sftp:` and `ssh:` SFTP and SSH filesystems _(requires `paramiko`)_
  120. - `smb:` SMB filesystems _(requires `smbprotocol`)_
  121. - `webdav`, `webdav+http:` and `webdav+https:` WebDAV-based filesystem on top of
  122. HTTP(S) _(requires `webdav4[fsspec]`)_
  123. It is likely, that other fsspec-compatible filesystems are supported through the
  124. default implementation. But because they are not tested in the universal_pathlib
  125. test-suite, correct behavior is not guaranteed. If you encounter any issues with
  126. a specific filesystem using the default implementation, please open an issue. We
  127. are happy to add support for other filesystems via custom UPath implementations.
  128. And of course, contributions for new filesystems are welcome!
  129. ### Class hierarchy
  130. The class hierarchy for `UPath` implementations and their relation to the stdlib
  131. `pathlib` classes are visualized in the following diagram:
  132. ```mermaid
  133. flowchart TB
  134. subgraph s0[pathlib]
  135. A---> B
  136. A--> AP
  137. A--> AW
  138. B--> BP
  139. AP---> BP
  140. B--> BW
  141. AW---> BW
  142. end
  143. subgraph s1[upath]
  144. B ---> U
  145. U --> UP
  146. U --> UW
  147. BP --> UP
  148. BW --> UW
  149. U --> UL
  150. U --> US3
  151. U --> UH
  152. U -.-> UO
  153. end
  154. A(PurePath)
  155. AP(PurePosixPath)
  156. AW(PureWindowsPath)
  157. B(Path)
  158. BP(PosixPath)
  159. BW(WindowsPath)
  160. U(UPath)
  161. UP(PosixUPath)
  162. UW(WindowsUPath)
  163. UL(FilePath)
  164. US3(S3Path)
  165. UH(HttpPath)
  166. UO(...Path)
  167. classDef np fill:#f7f7f7,stroke:#2166ac,stroke-width:2px,color:#333
  168. classDef nu fill:#f7f7f7,stroke:#b2182b,stroke-width:2px,color:#333
  169. class A,AP,AW,B,BP,BW,UP,UW np
  170. class U,UL,US3,UH,UO nu
  171. style UO stroke-dasharray: 3 3
  172. style s0 fill:none,stroke:#07b,stroke-width:3px,stroke-dasharray:3,color:#07b
  173. style s1 fill:none,stroke:#d02,stroke-width:3px,stroke-dasharray:3,color:#d02
  174. ```
  175. When instantiating `UPath` the returned instance type is determined by the path,
  176. or better said, the "protocol" that was provided to the constructor. The `UPath`
  177. class will return a registered implementation for the protocol, if available. If
  178. no specialized implementation can be found but the protocol is available through
  179. `fsspec`, it will return a `UPath` instance and provide filesystem access with a
  180. default implementation. Please note the default implementation can not guarantee
  181. correct behavior for filesystems that are not tested in the test-suite.
  182. ### Local paths and url paths
  183. If a local path is provided `UPath` will return a `PosixUPath` or `WindowsUPath`
  184. instance. These two implementations are 100% compatible with the `PosixPath` and
  185. `WindowsPath` classes of their specific Python version. They're tested against a
  186. large subset of the CPython pathlib test-suite to ensure compatibility.
  187. If a local urlpath is provided, i.e. a "file://" or "local://" URI, the returned
  188. instance type will be a `FilePath` instance. This class is a subclass of `UPath`
  189. that provides file access via `LocalFileSystem` from `fsspec`. You can use it to
  190. ensure that all your local file access is done through `fsspec` as well.
  191. ### UPath public class API
  192. The public class interface of `UPath` extends `pathlib.Path` via attributes that
  193. simplify interaction with `filesystem_spec`. Think of the `UPath` class in terms
  194. of the following code:
  195. ```python
  196. from pathlib import Path
  197. from typing import Any, Mapping
  198. from fsspec import AbstractFileSystem
  199. class UPath(Path):
  200. # the real implementation is more complex, but this is the general idea
  201. @property
  202. def protocol(self) -> str:
  203. """The fsspec protocol for the path."""
  204. @property
  205. def storage_options(self) -> Mapping[str, Any]:
  206. """The fsspec storage options for the path."""
  207. @property
  208. def path(self) -> str:
  209. """The path that a fsspec filesystem can use."""
  210. @property
  211. def fs(self) -> AbstractFileSystem:
  212. """The cached fsspec filesystem instance for the path."""
  213. ```
  214. These attributes are used to provide a public interface to move from the `UPath`
  215. instance to more fsspec specific code:
  216. ```python
  217. from upath import UPath
  218. from fsspec import filesystem
  219. p = UPath("s3://bucket/file.txt", anon=True)
  220. fs = filesystem(p.protocol, **p.storage_options) # equivalent to p.fs
  221. with fs.open(p.path) as f:
  222. data = f.read()
  223. ```
  224. ## Advanced Usage
  225. If you want to create your own UPath implementations, there are multiple ways to
  226. customize your subclass behavior. Here are a few things to keep in mind when you
  227. create your own UPath implementation:
  228. ### UPath's constructor, `upath.registry`, and subclassing
  229. When instantiating `UPath(...)` the `UPath.__new__()` method determines the path
  230. protocol and returns a registered implementation for the protocol, if available.
  231. The registered implementations are mapped in the `upath.registry` module. When a
  232. protocol is not registered, `universal_pathlib` checks if the protocol is mapped
  233. to an `fsspec` filesystem. If so, it returns an instance of `UPath` and provides
  234. filesystem access through the default implementation. The protocol is determined
  235. by either looking at the URI scheme of the first argument to the constructor, or
  236. by using the `protocol` keyword argument:
  237. ```python
  238. from upath import UPath
  239. from upath.implementations.cloud import S3Path
  240. from upath.implementations.memory import MemoryPath
  241. p0 = UPath("s3://bucket/file.txt")
  242. assert p0.protocol == "s3"
  243. assert type(p0) is S3Path
  244. assert isinstance(p0, UPath)
  245. p1 = UPath("/some/path/file.txt", protocol="memory")
  246. assert p1.protocol == "memory"
  247. assert type(p1) is MemoryPath
  248. assert isinstance(p1, UPath)
  249. # the ftp filesystem current has no custom UPath implementation and is not
  250. # tested in the universal_pathlib test-suite. Therefore, the default UPath
  251. # implementation is returned, and a warning is emitted on instantiation.
  252. p2 = UPath("ftp://ftp.ncbi.nih.gov/snp/archive")
  253. assert p2.protocol == "ftp"
  254. assert type(p2) is UPath
  255. ```
  256. This has some implications for custom UPath subclasses. We'll go through the two
  257. main cases where you might want to create a custom UPath implementation:
  258. #### Case 1: Custom filesystem works with default UPath implementation
  259. Let's say you would like to add a new implementation of your "myproto" protocol.
  260. You already built a custom AbstractFileSystem implementation for "myproto" which
  261. you have registered through `fsspec.registry`. In some cases it is possible that
  262. the custom filesystem class already works with `UPath`'s default implementation,
  263. and you don't need to necessarily create a custom UPath implementation:
  264. ```python
  265. import fsspec.registry
  266. from fsspec.spec import AbstractFileSystem
  267. class MyProtoFileSystem(AbstractFileSystem):
  268. protocol = ("myproto",)
  269. ... # your custom implementation
  270. fsspec.registry.register_implementation("myproto", MyProtoFileSystem)
  271. from upath import UPath
  272. p = UPath("myproto:///my/proto/path")
  273. assert type(p) is UPath
  274. assert p.protocol == "myproto"
  275. assert isinstance(p.fs, MyProtoFileSystem)
  276. ```
  277. #### Case 2: Custom filesystem requires a custom UPath implementation
  278. Sometimes the default implementation isn't sufficient and some method(s) have to
  279. be overridden to provide correct behavior. In this case, create a custom `UPath`
  280. implementation:
  281. ```python
  282. from upath import UPath
  283. class MyProtoPath(UPath):
  284. def mkdir(self, mode=0o777, parents=False, exist_ok=False):
  285. something = {...: ...} # fixes to make MyProtoFileSystem.mkdir work
  286. self.fs.mkdir(self.path, **something)
  287. def path(self):
  288. path = super().path
  289. if path.startswith("/"):
  290. return path[1:] # MyProtoFileSystem needs the path without "/"
  291. return path
  292. ```
  293. If you use your implementation directly via `MyProtoPath("myproto:///a/b")`, you
  294. can use this implementation already as is. If you want a call to `UPath(...)` to
  295. return your custom implementation when the detected protocol is `"myproto"`, you
  296. need to register your implementation. The next section explains your options.
  297. Also note: In case you develop a custom `UPath` implementation, please feel free
  298. to open an issue to discuss integrating it in `universal_pathlib`.
  299. #### Implementation registration dynamically from Python
  300. You can register your custom UPath implementation dynamically from Python:
  301. ```python
  302. # for example: mymodule/submodule.py
  303. from upath import UPath
  304. from upath.registry import register_implementation
  305. class MyProtoPath(UPath):
  306. ... # your custom implementation
  307. register_implementation("myproto", MyProtoPath)
  308. ```
  309. #### Implementation registration on installation via entry points
  310. If you distribute your implementation in your own Python package, you can inform
  311. `universal_pathlib` about your implementation via the `entry_points` mechanism:
  312. ```
  313. # pyproject.toml
  314. [project.entry-points."universal_pathlib.implementations"]
  315. myproto = "my_module.submodule:MyPath"
  316. ```
  317. ```
  318. # setup.cfg
  319. [options.entry_points]
  320. universal_pathlib.implementations =
  321. myproto = my_module.submodule:MyPath
  322. ```
  323. Chose the method that fits your use-case best. If you have questions, open a new
  324. issue in the `universal_pathlib` repository. We are happy to help you!
  325. ### Customization options for UPath subclasses
  326. #### Filesystem access methods
  327. Once you thoroughly test your custom UPath implementation, it's likely that some
  328. methods need to be overridden to provide correct behavior compared to `stdlib`'s
  329. `pathlib.Path` class. The most common issue is that for certain edge cases, your
  330. implementation is not raising the same exceptions compared to the `pathlib.Path`
  331. class. Or that the `UPath.path` property needs some prefix removed or added.
  332. ```python
  333. class MyProtoPath(UPath):
  334. @property
  335. def path(self) -> str:
  336. if p := self.path.startswith("/"):
  337. p = p[1:]
  338. return p
  339. def mkdir(self, mode=0o777, parents=False, exist_ok=False):
  340. if some_edge_case:
  341. raise FileExistsError(str(self))
  342. super().mkdir(mode=mode, parents=parents, exist_ok=exist_ok)
  343. def is_file(self):
  344. return self.fs.isfile(self.path, myproto_option=123)
  345. ```
  346. #### Storage option parsing
  347. It's possible that you might want to extract additional storage options from the
  348. user provided arguments to you constructor. You can provide a custom classmethod
  349. for `_parse_storage_options`:
  350. ```python
  351. import os
  352. class MyProtoPath(UPath):
  353. @classmethod
  354. def _parse_storage_options(
  355. cls, urlpath: str, protocol: str, storage_options: Mapping[str, Any]
  356. ) -> dict[str, Any]:
  357. if "SOME_VAR" in os.environ:
  358. storage_options["some_var"] = os.environ["SOME_VAR"]
  359. storage_options["my_proto_caching"] = True
  360. storage_options["extra"] = get_setting_from_path(urlpath)
  361. return storage_options
  362. ```
  363. #### Fsspec filesystem instantiation
  364. To have more control over fsspec filesystem instantiation you can write a custom
  365. `_fs_factory` classmethod:
  366. ```python
  367. class MyProtoPath(UPath):
  368. @classmethod
  369. def _fs_factory(
  370. cls, urlpath: str, protocol: str, storage_options: Mapping[str, Any]
  371. ) -> AbstractFileSystem:
  372. myfs = ... # custom code that creates a AbstractFileSystem instance
  373. return myfs
  374. ```
  375. #### Init argument parsing
  376. In special cases you need to take more control over how the init args are parsed
  377. for your custom subclass. You can override `__init__` or the `UPath` classmethod
  378. `_transform_init_args`. The latter handles pickling of your custom subclass in a
  379. better way in case you modify storage options or the protocol.
  380. ```python
  381. class MyProtoPath(UPath):
  382. @classmethod
  383. def _transform_init_args(
  384. cls,
  385. args: tuple[str | os.PathLike, ...],
  386. protocol: str,
  387. storage_options: dict[str, Any],
  388. ) -> tuple[tuple[str | os.PathLike, ...], str, dict[str, Any]]:
  389. # check the cloud, http or webdav implementations for examples
  390. ...
  391. return args, protocol, storage_options
  392. ```
  393. #### Stopping UPath's subclass dispatch mechanism
  394. There are cases for which you want to disable the protocol dispatch mechanism of
  395. the `UPath.__new__` constructor. For example if you want to extend the class API
  396. of your `UPath` implementation, and use it as the base class for other, directly
  397. instantiated subclasses. Together with other customization options this can be a
  398. useful feature. Please be aware that in this case all protocols are handled with
  399. the default implementation in UPath. Please always feel free to open an issue in
  400. the issue tracker to discuss your use case. We're happy to help with finding the
  401. most maintainable solution.
  402. ```python
  403. class ExtraUPath(UPath):
  404. _protocol_dispatch = False # disable the registry return an ExtraUPath
  405. def some_extra_method(self) -> str:
  406. return "hello world"
  407. assert ExtraUPath("s3://bucket/file.txt").some_extra_method() == "hello world"
  408. ```
  409. ## Migration Guide
  410. UPath's internal implementation is likely going to change with larger changes in
  411. CPython's stdlib `pathlib` landing in the next Python versions (`3.13`, `3.14`).
  412. To reduce the problems for user code, when these changes are landing in `UPath`,
  413. there have been some significant changes in `v0.2.0`. This migration guide tries
  414. to help migrating code that extensively relies on private implementation details
  415. of the `UPath` class of versions `v0.1.x` to the new and better supported public
  416. interface of `v0.2.0`
  417. ### migrating to `v0.2.0`
  418. ### _FSSpecAccessor subclasses with custom filesystem access methods
  419. If you implemented a custom accessor subclass, it is now recommended to override
  420. the corresponding `UPath` methods in your subclass directly:
  421. ```python
  422. # OLD: v0.1.x
  423. from upath.core import UPath, _FSSpecAccessor
  424. class MyAccessor(_FSSpecAccessor):
  425. def exists(self, path, **kwargs):
  426. # custom code
  427. return path.fs.exists(self._format_path(path), **kwargs)
  428. def touch(self, path, **kwargs):
  429. # custom
  430. return path.fs.touch(self._format_path(path), **kwargs)
  431. class MyPath(UPath):
  432. _default_accessor = MyAccessor
  433. # NEW: v0.2.0+
  434. from upath import UPath
  435. class MyPath(UPath):
  436. def exists(self, *, follow_symlinks=True):
  437. kwargs = {} # custom code
  438. return self.fs.exists(self.path, **kwargs)
  439. def touch(self, mode=0o666, exist_ok=True):
  440. kwargs = {} # custom code
  441. self.fs.touch(self.path, **kwargs)
  442. ```
  443. ### _FSSpecAccessor subclasses with custom `__init__` method
  444. If you implemented a custom `__init__` method for your accessor subclass usually
  445. the intention is to customize how the fsspec filesystem instance is created. You
  446. have two options to recreate this with the new implementation. Chose one or both
  447. dependent on the level of control you need.
  448. ```python
  449. # OLD: v0.1.x
  450. import fsspec
  451. from upath.core import UPath, _FSSpecAccessor
  452. class MyAccessor(_FSSpecAccessor):
  453. def __init__(self, parsed_url: SplitResult | None, **kwargs: Any) -> None:
  454. # custom code
  455. protocol = ...
  456. storage_options = ...
  457. self._fs = fsspec.filesystem(protocol, storage_options)
  458. class MyPath(UPath):
  459. _default_accessor = MyAccessor
  460. # NEW: v0.2.0+
  461. from upath import UPath
  462. class MyPath(UPath):
  463. @classmethod
  464. def _parse_storage_options(
  465. cls, urlpath: str, protocol: str, storage_options: Mapping[str, Any]
  466. ) -> dict[str, Any]:
  467. # custom code to change storage_options
  468. storage_options = ...
  469. return storage_options
  470. @classmethod
  471. def _fs_factory(
  472. cls, urlpath: str, protocol: str, storage_options: Mapping[str, Any]
  473. ) -> AbstractFileSystem:
  474. # custom code to instantiate fsspec filesystem
  475. protocol = ...
  476. storage_options = ... # note changes to storage_options here won't
  477. # show up in MyPath().storage_options
  478. return fsspec.filesystem(protocol, **storage_options)
  479. ```
  480. ### Access to `._accessor`
  481. The `_accessor` attribute and the `_FSSpecAccessor` class is deprecated. In case
  482. you need direct access to the underlying filesystem, just access `UPath().fs`.
  483. ```python
  484. # OLD: v0.1.x
  485. from upath.core import UPath
  486. class MyPath(UPath):
  487. def mkdir(self, mode=0o777, parents=False, exist_ok=False):
  488. self._accessor.mkdir(...) # custom access to the underlying fs...
  489. # NEW: v0.2.0+
  490. from upath import UPath
  491. class MyPath(UPath):
  492. def mkdir(self, mode=0o777, parents=False, exist_ok=False):
  493. self.fs.mkdir(...)
  494. ```
  495. ### Access to `._path`, `._kwargs`, `._drv`, `._root`, `._parts`
  496. If you access one of the listed private attributes directly, move your code over
  497. to the following public versions:
  498. | _deprecated_ | `v0.2.0+` |
  499. |:------------------|:--------------------------|
  500. | `UPath()._path` | `UPath().path` |
  501. | `UPath()._kwargs` | `UPath().storage_options` |
  502. | `UPath()._drv` | `UPath().drive` |
  503. | `UPath()._root` | `UPath().root` |
  504. | `UPath()._parts` | `UPath().parts` |
  505. ### Access to `._url`
  506. Be aware that the `._url` attribute will likely be deprecated once `UPath()` has
  507. support for uri fragments and uri query parameters through a public api. In case
  508. you are interested in contributing this functionality, please open an issue!
  509. ### Calling `_from_parts`, `_parse_args`, `_format_parsed_parts`
  510. If your code is currently calling any of the three above listed classmethods, it
  511. relies on functionality based on the implementation of `pathlib` in Python up to
  512. `3.11`. In `universal_pathlib` we vendor code that allows the `UPath()` class to
  513. be based on the `3.12` implementation of `pathlib.Path` alone. Usually, usage of
  514. those classmethods occurs when copying some code of the internal implementations
  515. of methods of the `UPath` `0.1.4` classes.
  516. - To reproduce custom `_format_parsed_parts` methods in `v0.2.0`, try overriding
  517. `UPath().path` and/or `UPath().with_segments()`.
  518. - Custom `_from_parts` and `_parse_args` classmethods can now be implemented via
  519. the `_transform_init_args` method or via more functionality in the new flavour
  520. class. Please open an issue for discussion in case you have this use case.
  521. ### Custom `_URIFlavour` classes
  522. The `_URIFlavour` class was removed from `universal_pathlib` and the new flavour
  523. class for fsspec filesystem path operations now lives in `upath._flavour`. As of
  524. now the internal FSSpecFlavour is experimental. In a future Python version, it's
  525. likely that a flavour or flavour-like base class will become public, that allows
  526. us to base our internal implementation on. Until then, if you find yourself in a
  527. situation where a custom path flavour would solve your problem, please feel free
  528. to open an issue for discussion. We're happy to find a maintainable solution.
  529. ### Using `.parse_parts()`, `.casefold()`, `.join_parsed_parts()` of `._flavour`
  530. These methods of the `._flavour` attribute of `pathlib.Path()` and `UPath()` are
  531. specific to `pathlib` of Python versions up to `3.11`. `UPath()` is now based on
  532. the `3.12` implementation of `pathlib.Path`. Please refer to the implementations
  533. of the `upath._flavour` submodule to see how you could avoid using them.
  534. ## Known issues solvable by installing newer upstream dependencies
  535. Some issues in `UPath`'s behavior with specific fsspec filesystems are fixed via
  536. installation of a newer version of its upstream dependencies. Below you can find
  537. a list of known issues and their solutions. We attempt to keep this list updated
  538. whenever we encounter more:
  539. - **UPath().glob()**:
  540. `fsspec` fixed glob behavior when handling `**` patterns in `fsspec>=2023.9.0`
  541. - **GCSPath().mkdir()**:
  542. a few mkdir quirks are solved by installing `gcsfs>=2022.7.1`
  543. - **fsspec.filesystem(WebdavPath().protocol)**
  544. the webdav protocol was added to fsspec in version `fsspec>=2022.5.0`
  545. - **stat.S_ISDIR(HTTPPath().stat().st_mode)**
  546. requires `fsspec>=2024.2.0` to correctly return `True` for directories
  547. ## Contributing
  548. Contributions are very welcome.
  549. To learn more, see the [Contributor Guide](CONTRIBUTING.rst).
  550. ## License
  551. Distributed under the terms of the [MIT license](LICENSE),
  552. *universal_pathlib* is free and open source software.
  553. ## Issues
  554. If you encounter any problems, or if you create your own implementations and run
  555. into limitations, please [file an issue][issues] with a detailed description. We
  556. are always happy to help with any problems you might encounter.
  557. [issues]: https://github.com/fsspec/universal_pathlib/issues