Coverage for rdflib_ocdm / graph_utils.py: 93%

17 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-03-21 12:35 +0000

1#!/usr/bin/python 

2 

3# SPDX-FileCopyrightText: 2025 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 = context.identifier if hasattr(context, 'identifier') else context 

30 if isinstance(context_identifier, URIRef): 

31 if not str(context_identifier).startswith('urn:x-rdflib:'): 

32 return context_identifier 

33 return None 

34 

35 

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

37 """ 

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

39 

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

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

42 

43 :param dataset: The Dataset to search in 

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

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

46 """ 

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

48 graph_iri = _extract_graph_iri_from_context(c) 

49 if graph_iri is not None: 

50 return graph_iri 

51 return None