Coverage for rdflib_ocdm / graph_utils.py: 93%

17 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-05-30 21:23 +0000

1#!/usr/bin/python 

2 

3# SPDX-FileCopyrightText: 2025-2026 Arcangelo Massari <arcangelo.massari@unibo.it> 

4# 

5# SPDX-License-Identifier: ISC 

6 

7from __future__ import annotations 

8 

9from typing import TYPE_CHECKING, Optional 

10 

11if TYPE_CHECKING: 

12 from rdflib import Dataset 

13 

14from rdflib import URIRef 

15 

16 

17def _extract_graph_iri_from_context(context) -> Optional[URIRef]: 

18 """ 

19 Extract a valid graph IRI from a context object. 

20 

21 Returns the context identifier if it's a non-default named graph. 

22 Default graphs (starting with 'urn:x-rdflib:') are ignored. 

23 

24 :param context: The context object (usually from quad or _spoc) 

25 :return: The graph IRI as URIRef, or None if not valid 

26 """ 

27 if context is None: 27 ↛ 28line 27 didn't jump to line 28 because the condition on line 27 was never true

28 return None 

29 context_identifier = ( 

30 context.identifier if hasattr(context, "identifier") else context 

31 ) 

32 if isinstance(context_identifier, URIRef): 

33 if not str(context_identifier).startswith("urn:x-rdflib:"): 

34 return context_identifier 

35 return None 

36 

37 

38def _extract_graph_iri(dataset: Dataset, subject: URIRef) -> Optional[URIRef]: 

39 """ 

40 Extract the graph IRI for a given subject from a Dataset. 

41 

42 Returns the first non-default named graph IRI found for the subject. 

43 Default graphs (starting with 'urn:x-rdflib:') are ignored. 

44 

45 :param dataset: The Dataset to search in 

46 :param subject: The subject URIRef to find the graph IRI for 

47 :return: The graph IRI as URIRef, or None if not found 

48 """ 

49 for _, _, _, c in dataset.quads((subject, None, None, None)): 

50 graph_iri = _extract_graph_iri_from_context(c) 

51 if graph_iri is not None: 

52 return graph_iri 

53 return None