Skip to content

Instantly share code, notes, and snippets.

@dlenski
Created June 10, 2025 19:15
Show Gist options
  • Save dlenski/7a5c1958d7f86ffc4c4eef7903e67c33 to your computer and use it in GitHub Desktop.
Save dlenski/7a5c1958d7f86ffc4c4eef7903e67c33 to your computer and use it in GitHub Desktop.
Monkey-patch a backport of `pathlib.Path.from_uri` from Python 3.13+
'''
This is a monkey-patched backport to Python 3.4+ of a useful `pathlib.Path` method added in Python 3.13:
https://docs.python.org/3/library/pathlib.html#pathlib.Path.from_uri
'''
import sys
assert sys.version_info >= (3, 4), "Python 3.4+ is required for `pathlib` support (https://docs.python.org/3/library/pathlib.html)"
if sys.version_info < (3, 13):
from pathlib import PurePath
from urllib.request import url2pathname as _url2pathname
def _from_uri(cls, uri: str) -> Path:
'''Return a new path object from parsing a ‘file’ URI.
Backport of `pathlib.Path.from_uri` from Python 3.13+'''
if not uri.startswith('file:'):
raise ValueError(f"URI {uri!r} does not start with 'file:'")
# "For historical reasons, the given value must omit the file: scheme prefix."
# https://docs.python.org/3/library/urllib.request.html#urllib.request.url2pathname
p = cls(_url2pathname(uri[5:]))
if not p.is_absolute():
raise ValueError(f"URI {uri!r} does not reference an absolute path")
return p
# Monkey-patch the base class, so that all derived classes will inherit it as well.
PurePath.from_uri = classmethod(_from_uri)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment