lazr-uri
lazr-uri is a self-contained, easily reusable Python library designed for robust parsing, manipulation, and generation of Uniform Resource Identifiers (URIs). The current version is 1.0.7, released on December 9, 2024. The library maintains an infrequent release cadence, with updates typically addressing Python compatibility and internal optimizations.
Common errors
-
ImportError: cannot import name 'URI' from 'lazr.uri' (...)
cause This usually indicates an outdated version of `lazr-uri` or an issue with the Python environment where a module named `lazr.uri` exists but does not contain the `URI` class, or a namespace conflict.fixEnsure `lazr-uri` is correctly installed and up-to-date with `pip install --upgrade lazr-uri`. Verify no other packages are conflicting with the `lazr.uri` namespace. -
AttributeError: 'URI' object has no attribute 'port' (when expecting a port from a URI without one)
cause When a URI string does not explicitly include a port, the 'port' attribute of the `URI` object will be `None`, leading to an `AttributeError` if you try to access methods or properties directly on it without checking if it's `None`.fixAlways check if URI components like `uri.port` are `None` before attempting operations on them. Example: `if uri.port is not None: print(uri.port)`.
Warnings
- breaking Version 1.0.7 dropped support for Python versions 3.7 and below.
- gotcha Prior to version 1.0.6, `lazr.uri`'s versioning strategy imported `pkg_resources`, which could lead to significant performance overhead in large Python environments during startup.
Install
-
pip install lazr-uri
Imports
- URI
from lazr.uri import URI
- find_uris_in_text
from lazr.uri import find_uris_in_text
Quickstart
from lazr.uri import URI, find_uris_in_text
# Parsing a URI and accessing its parts
uri_str = "https://www.example.com:8080/path/to/resource?query=param&key=value#fragment"
uri = URI(uri_str)
print(f"Scheme: {uri.scheme}")
print(f"Host: {uri.host}")
print(f"Port: {uri.port}")
print(f"Path: {uri.path}")
print(f"Query: {uri.query}")
print(f"Fragment: {uri.fragment}")
# Manipulating a URI
new_uri = uri.replace(scheme='http', port=None)
print(f"Modified URI: {new_uri}")
# Finding URIs within a text block
text_with_uris = "Visit our site at http://example.org or email us at mailto:support@example.net."
found_uris = list(find_uris_in_text(text_with_uris))
for found_uri in found_uris:
print(f"Found URI: {found_uri}")