Coverage for rdflib_ocdm/graph_utils.py: 87%

19 statements  

« prev     ^ index     » next       coverage.py v7.6.12, created at 2025-11-01 22:02 +0000

1#!/usr/bin/python 

2# -*- coding: utf-8 -*- 

3# Copyright 2025 Arcangelo Massari <arcangelo.massari@unibo.it> 

4# 

5# Permission to use, copy, modify, and/or distribute this software for any purpose 

6# with or without fee is hereby granted, provided that the above copyright notice 

7# and this permission notice appear in all copies. 

8# 

9# THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH 

10# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND 

11# FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, 

12# OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, 

13# DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS 

14# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS 

15# SOFTWARE. 

16 

17from __future__ import annotations 

18 

19from typing import TYPE_CHECKING, Optional 

20 

21if TYPE_CHECKING: 21 ↛ 22line 21 didn't jump to line 22 because the condition on line 21 was never true

22 from rdflib import Dataset 

23 

24from rdflib import URIRef 

25 

26 

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

28 """ 

29 Extract a valid graph IRI from a context object. 

30 

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

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

33 

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

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

36 """ 

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

38 return None 

39 context_identifier = context.identifier if hasattr(context, 'identifier') else context 

40 if isinstance(context_identifier, URIRef): 

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

42 return context_identifier 

43 return None 

44 

45 

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

47 """ 

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

49 

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

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

52 

53 :param dataset: The Dataset to search in 

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

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

56 """ 

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

58 graph_iri = _extract_graph_iri_from_context(c) 

59 if graph_iri is not None: 

60 return graph_iri 

61 return None