-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathcollection_utils.py
37 lines (31 loc) · 1.34 KB
/
collection_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from typing import Union, List, Optional
from rdflib import Graph, URIRef, BNode, RDF
def format_collection(g: Graph, subj: Union[URIRef, BNode], max_entries: int = None, nentries: int = 0) -> Optional[List[str]]:
"""
Return the turtle representation of subj as a collection
:param g: Graph containing subj
:param subj: subject of list
:param max_entries: maximum number of list elements to return, None means all
:param nentries: used for recursion
:return: List of formatted entries if subj heads a well formed collection else None
"""
if subj == RDF.nil:
return [')']
if max_entries is not None and nentries >= max_entries:
return [' ...', ')']
cadr = cdr = None
for p, o in g.predicate_objects(subj):
if p == RDF.first and cadr is None:
cadr = o
elif p == RDF.rest and cdr is None:
cdr = o
else:
return None
# technically this can't happen but it doesn't hurt to address it
if cadr == RDF.nil and cdr is None:
return []
elif cadr is not None and cdr is not None:
return [(' ' if nentries else '(') + cadr.n3(g.namespace_manager)] + format_collection(g, cdr, max_entries,
nentries+1)
else:
return None