Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal for CurieNamespace with embedded catalog. #244

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 30 additions & 7 deletions linkml_runtime/utils/curienamespace.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,39 @@
from typing import Optional, Union
from logging import warning
from typing import Optional, Union, Dict

from rdflib import Namespace, URIRef


class CurieNamespace(Namespace):
def __new__(cls, prefix: str, value: Union[str, URIRef]):
value = str(value)
try:
rt = str.__new__(cls, value)
except UnicodeDecodeError:
rt = str.__new__(cls, value, 'utf-8')
# We would prefer to use curies.Converter here, but there doesn't appear to be any way to build it incrementally
catalog: Dict[str, "CurieNamespace"] = dict()

@classmethod
def to_curie(cls, uri: Union[str, URIRef]) -> str:
uri = str(uri)
candidate_ns = ""
for prefix, ns in cls.catalog.items():
if uri.startswith(ns) and len(ns) > len(candidate_ns):
candidate_ns = ns
if candidate_ns:
return candidate_ns.curie(uri[len(candidate_ns):])
return None

@classmethod
def to_uri(cls, curie: str) -> Optional[URIRef]:
prefix, localname = curie.split(':', 1)
ns = CurieNamespace.catalog.get(prefix, None)
return ns[localname] if ns else None

def __new__(cls, prefix: str, ns: Union[str, bytes, URIRef]) -> "CurieNamespace":
rt = Namespace.__new__(cls, str(ns) if not isinstance(ns, bytes) else ns)
rt.prefix = prefix
if prefix in CurieNamespace.catalog:
if CurieNamespace.catalog[prefix] != str(rt):
# prefix is bound to a different namespace
warning(f"Prefix: {prefix} already references {CurieNamespace.catalog[prefix]} - not updated to {rt}")
else:
CurieNamespace.catalog[prefix] = rt
return rt

def curie(self, reference: Optional[str] = '') -> str:
Expand Down
Loading