Skip to content

Commit

Permalink
Undo typing changes, so this works on current pre-3.9 branch
Browse files Browse the repository at this point in the history
  • Loading branch information
ashleysommer committed Nov 1, 2024
1 parent f8f9ee2 commit c843fe1
Showing 1 changed file with 23 additions and 24 deletions.
47 changes: 23 additions & 24 deletions rdflib/namespace/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,9 @@

import logging
import warnings
from collections.abc import Iterable
from functools import lru_cache
from pathlib import Path
from typing import TYPE_CHECKING, Any, Optional
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Set, Tuple, Union
from unicodedata import category
from urllib.parse import urldefrag, urljoin

Expand Down Expand Up @@ -145,7 +144,7 @@ class Namespace(str):
False
"""

def __new__(cls, value: str | bytes) -> Namespace:
def __new__(cls, value: Union[str, bytes]) -> Namespace:
try:
rt = str.__new__(cls, value)
except UnicodeDecodeError:
Expand Down Expand Up @@ -203,7 +202,7 @@ class URIPattern(str):
"""

def __new__(cls, value: str | bytes) -> URIPattern:
def __new__(cls, value: Union[str, bytes]) -> URIPattern:
try:
rt = str.__new__(cls, value)
except UnicodeDecodeError:
Expand All @@ -226,7 +225,7 @@ def __repr__(self) -> str:
# always raise AttributeError if they are not defined and which should not be
# considered part of __dir__ results. These should be all annotations on
# `DefinedNamespaceMeta`.
_DFNS_RESERVED_ATTRS: set[str] = {
_DFNS_RESERVED_ATTRS: Set[str] = {
"_NS",
"_warn",
"_fail",
Expand All @@ -236,7 +235,7 @@ def __repr__(self) -> str:

# Some libraries probe classes for certain attributes or items.
# This is a list of those attributes and items that should be ignored.
_IGNORED_ATTR_LOOKUP: set[str] = {
_IGNORED_ATTR_LOOKUP: Set[str] = {
"_pytestfixturefunction", # pytest tries to look this up on Defined namespaces
"_partialmethod", # sphinx tries to look this up during autodoc generation
"__test__", # pytest checks for this old nose-test style constant
Expand All @@ -250,7 +249,7 @@ class DefinedNamespaceMeta(type):
_NS: Namespace
_warn: bool = True
_fail: bool = False # True means mimic ClosedNamespace
_extras: list[str] = [] # List of non-pythonesque items
_extras: List[str] = [] # List of non-pythonesque items
_underscore_num: bool = False # True means pass "_n" constructs

@lru_cache(maxsize=None)
Expand Down Expand Up @@ -349,9 +348,9 @@ class ClosedNamespace(Namespace):
Trying to create terms not listed is an error
"""

__uris: dict[str, URIRef]
__uris: Dict[str, URIRef]

def __new__(cls, uri: str, terms: list[str]):
def __new__(cls, uri: str, terms: List[str]):
rt = super().__new__(cls, uri)
rt.__uris = {t: URIRef(rt + t) for t in terms} # type: ignore[attr-defined]
return rt
Expand Down Expand Up @@ -381,15 +380,15 @@ def __getattr__(self, name: str) -> URIRef:
def __repr__(self) -> str:
return f"{self.__module__}.{self.__class__.__name__}({str(self)!r})"

def __dir__(self) -> list[str]:
def __dir__(self) -> List[str]:
return list(self.__uris)

def __contains__(self, ref: str) -> bool: # type: ignore[override]
return (
ref in self.__uris.values()
) # test namespace membership with "ref in ns" syntax

def _ipython_key_completions_(self) -> list[str]:
def _ipython_key_completions_(self) -> List[str]:
return dir(self)


Expand Down Expand Up @@ -453,11 +452,11 @@ class NamespaceManager:

def __init__(self, graph: Graph, bind_namespaces: _NamespaceSetString = "rdflib"):
self.graph = graph
self.__cache: dict[str, tuple[str, URIRef, str]] = {}
self.__cache_strict: dict[str, tuple[str, URIRef, str]] = {}
self.__cache: Dict[str, Tuple[str, URIRef, str]] = {}
self.__cache_strict: Dict[str, Tuple[str, URIRef, str]] = {}
self.__log = None
self.__strie: dict[str, Any] = {}
self.__trie: dict[str, Any] = {}
self.__strie: Dict[str, Any] = {}
self.__trie: Dict[str, Any] = {}
# This type declaration is here becuase there is no common base class
# for all namespaces and without it the inferred type of ns is not
# compatible with all prefixes.
Expand Down Expand Up @@ -574,7 +573,7 @@ def normalizeUri(self, rdfTerm: str) -> str: # noqa: N802, N803
qNameParts = self.compute_qname(rdfTerm) # noqa: N806
return ":".join([qNameParts[0], qNameParts[-1]])

def compute_qname(self, uri: str, generate: bool = True) -> tuple[str, URIRef, str]:
def compute_qname(self, uri: str, generate: bool = True) -> Tuple[str, URIRef, str]:
prefix: Optional[str]
if uri not in self.__cache:
if not _is_valid_uri(uri):
Expand Down Expand Up @@ -621,7 +620,7 @@ def compute_qname(self, uri: str, generate: bool = True) -> tuple[str, URIRef, s

def compute_qname_strict(
self, uri: str, generate: bool = True
) -> tuple[str, str, str]:
) -> Tuple[str, str, str]:
# code repeated to avoid branching on strict every time
# if output needs to be strict (e.g. for xml) then
# only the strict output should bear the overhead
Expand Down Expand Up @@ -790,7 +789,7 @@ def bind(

insert_trie(self.__trie, str(namespace))

def namespaces(self) -> Iterable[tuple[str, URIRef]]:
def namespaces(self) -> Iterable[Tuple[str, URIRef]]:
for prefix, namespace in self.store.namespaces():
namespace = URIRef(namespace)
yield prefix, namespace
Expand Down Expand Up @@ -873,8 +872,8 @@ def is_ncname(name: str) -> int:


def split_uri(
uri: str, split_start: list[str] = SPLIT_START_CATEGORIES
) -> tuple[str, str]:
uri: str, split_start: List[str] = SPLIT_START_CATEGORIES
) -> Tuple[str, str]:
if uri.startswith(XMLNS):
return (XMLNS, uri.split(XMLNS)[1])
length = len(uri)
Expand All @@ -896,8 +895,8 @@ def split_uri(


def insert_trie(
trie: dict[str, Any], value: str
) -> dict[str, Any]: # aka get_subtrie_or_insert
trie: Dict[str, Any], value: str
) -> Dict[str, Any]: # aka get_subtrie_or_insert
"""Insert a value into the trie if it is not already contained in the trie.
Return the subtree for the value regardless of whether it is a new value
or not."""
Expand All @@ -920,12 +919,12 @@ def insert_trie(
return trie[value]


def insert_strie(strie: dict[str, Any], trie: dict[str, Any], value: str) -> None:
def insert_strie(strie: Dict[str, Any], trie: Dict[str, Any], value: str) -> None:
if value not in strie:
strie[value] = insert_trie(trie, value)


def get_longest_namespace(trie: dict[str, Any], value: str) -> Optional[str]:
def get_longest_namespace(trie: Dict[str, Any], value: str) -> Optional[str]:
for key in trie:
if value.startswith(key):
out = get_longest_namespace(trie[key], value)
Expand Down

0 comments on commit c843fe1

Please sign in to comment.