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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
|
"""
This module defines the different types of terms. Terms are the kinds of
objects that can appear in a quoted/asserted triple. This includes those
that are core to RDF:
* :class:`Blank Nodes <rdflib.term.BNode>`
* :class:`URI References <rdflib.term.URIRef>`
* :class:`Literals <rdflib.term.Literal>` (which consist of a literal value,datatype and language tag)
Those that extend the RDF model into N3:
* :class:`Formulae <rdflib.graph.QuotedGraph>`
* :class:`Universal Quantifications (Variables) <rdflib.term.Variable>`
And those that are primarily for matching against 'Nodes' in the
underlying Graph:
* REGEX Expressions
* Date Ranges
* Numerical Ranges
"""
import re
from fractions import Fraction
__all__ = [
"bind",
"_is_valid_uri",
"Node",
"IdentifiedNode",
"Identifier",
"URIRef",
"BNode",
"Literal",
"Variable",
]
import logging
import math
import warnings
import xml.dom.minidom
from base64 import b64decode, b64encode
from binascii import hexlify, unhexlify
from collections import defaultdict
from datetime import date, datetime, time, timedelta
from decimal import Decimal
from re import compile, sub
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
)
from urllib.parse import urldefrag, urljoin, urlparse
from isodate import (
Duration,
duration_isoformat,
parse_date,
parse_datetime,
parse_duration,
parse_time,
)
import rdflib
import rdflib.util
from rdflib.compat import long_type
if TYPE_CHECKING:
from .namespace import NamespaceManager
from .paths import AlternativePath, InvPath, NegatedPath, Path, SequencePath
_SKOLEM_DEFAULT_AUTHORITY = "https://rdflib.github.io"
logger = logging.getLogger(__name__)
skolem_genid = "/.well-known/genid/"
rdflib_skolem_genid = "/.well-known/genid/rdflib/"
skolems: Dict[str, "BNode"] = {}
_invalid_uri_chars = '<>" {}|\\^`'
def _is_valid_uri(uri: str) -> bool:
for c in _invalid_uri_chars:
if c in uri:
return False
return True
_lang_tag_regex = compile("^[a-zA-Z]+(?:-[a-zA-Z0-9]+)*$")
def _is_valid_langtag(tag: str) -> bool:
return bool(_lang_tag_regex.match(tag))
def _is_valid_unicode(value: Union[str, bytes]) -> bool:
"""
Verify that the provided value can be converted into a Python
unicode object.
"""
if isinstance(value, bytes):
coding_func, param = getattr(value, "decode"), "utf-8"
else:
coding_func, param = str, value
# try to convert value into unicode
try:
coding_func(param)
except UnicodeError:
return False
return True
class Node:
"""
A Node in the Graph.
"""
__slots__ = ()
class Identifier(Node, str): # allow Identifiers to be Nodes in the Graph
"""
See http://www.w3.org/2002/07/rdf-identifer-terminology/
regarding choice of terminology.
"""
__slots__ = ()
def __new__(cls, value: str) -> "Identifier":
return str.__new__(cls, value)
def eq(self, other: Any) -> bool:
"""A "semantic"/interpreted equality function,
by default, same as __eq__"""
return self.__eq__(other)
def neq(self, other: Any) -> bool:
"""A "semantic"/interpreted not equal function,
by default, same as __ne__"""
return self.__ne__(other)
def __ne__(self, other: Any) -> bool:
return not self.__eq__(other)
def __eq__(self, other: Any) -> bool:
"""
Equality for Nodes.
>>> BNode("foo")==None
False
>>> BNode("foo")==URIRef("foo")
False
>>> URIRef("foo")==BNode("foo")
False
>>> BNode("foo")!=URIRef("foo")
True
>>> URIRef("foo")!=BNode("foo")
True
>>> Variable('a')!=URIRef('a')
True
>>> Variable('a')!=Variable('a')
False
"""
if type(self) == type(other):
return str(self) == str(other)
else:
return False
def __gt__(self, other: Any) -> bool:
"""
This implements ordering for Nodes,
This tries to implement this:
http://www.w3.org/TR/sparql11-query/#modOrderBy
Variables are not included in the SPARQL list, but
they are greater than BNodes and smaller than everything else
"""
if other is None:
return True # everything bigger than None
elif type(self) == type(other):
return str(self) > str(other)
elif isinstance(other, Node):
return _ORDERING[type(self)] > _ORDERING[type(other)]
return NotImplemented
def __lt__(self, other: Any) -> bool:
if other is None:
return False # Nothing is less than None
elif type(self) == type(other):
return str(self) < str(other)
elif isinstance(other, Node):
return _ORDERING[type(self)] < _ORDERING[type(other)]
return NotImplemented
def __le__(self, other: Any) -> bool:
r = self.__lt__(other)
if r:
return True
return self == other
def __ge__(self, other: Any) -> bool:
r = self.__gt__(other)
if r:
return True
return self == other
# type error: Argument 1 of "startswith" is incompatible with supertype "str"; supertype defines the argument type as "Union[str, Tuple[str, ...]]"
# FIXME: this does not accommodate prefix of type Tuple[str, ...] which is a
# valid for str.startswith
def startswith(self, prefix: str, start=..., end=...) -> bool: # type: ignore[override] # FIXME
return str(self).startswith(str(prefix))
# use parent's hash for efficiency reasons
# clashes of 'foo', URIRef('foo') and Literal('foo') are typically so rare
# that they don't justify additional overhead. Notice that even in case of
# clash __eq__ is still the fallback and very quick in those cases.
__hash__ = str.__hash__
class IdentifiedNode(Identifier):
"""
An abstract class, primarily defined to identify Nodes that are not Literals.
The name "Identified Node" is not explicitly defined in the RDF specification, but can be drawn from this section: https://www.w3.org/TR/rdf-concepts/#section-URI-Vocabulary
"""
def __getnewargs__(self) -> Tuple[str]:
return (str(self),)
def toPython(self) -> str: # noqa: N802
return str(self)
class URIRef(IdentifiedNode):
"""
RDF 1.1's IRI Section https://www.w3.org/TR/rdf11-concepts/#section-IRIs
.. note:: Documentation on RDF outside of RDFLib uses the term IRI or URI whereas this class is called URIRef. This is because it was made when the first version of the RDF specification was current, and it used the term *URIRef*, see `RDF 1.0 URIRef <http://www.w3.org/TR/rdf-concepts/#section-Graph-URIref>`_
An IRI (Internationalized Resource Identifier) within an RDF graph is a Unicode string that conforms to the syntax defined in RFC 3987.
IRIs in the RDF abstract syntax MUST be absolute, and MAY contain a fragment identifier.
IRIs are a generalization of URIs [RFC3986] that permits a wider range of Unicode characters.
"""
__slots__ = ()
__or__: Callable[["URIRef", Union["URIRef", "Path"]], "AlternativePath"]
__invert__: Callable[["URIRef"], "InvPath"]
__neg__: Callable[["URIRef"], "NegatedPath"]
__truediv__: Callable[["URIRef", Union["URIRef", "Path"]], "SequencePath"]
def __new__(cls, value: str, base: Optional[str] = None) -> "URIRef":
if base is not None:
ends_in_hash = value.endswith("#")
# type error: Argument "allow_fragments" to "urljoin" has incompatible type "int"; expected "bool"
value = urljoin(base, value, allow_fragments=1) # type: ignore[arg-type]
if ends_in_hash:
if not value.endswith("#"):
value += "#"
if not _is_valid_uri(value):
logger.warning(
"%s does not look like a valid URI, trying to serialize this will break."
% value
)
try:
rt = str.__new__(cls, value)
except UnicodeDecodeError:
# type error: No overload variant of "__new__" of "str" matches argument types "Type[URIRef]", "str", "str"
rt = str.__new__(cls, value, "utf-8") # type: ignore[call-overload]
return rt
def n3(self, namespace_manager: Optional["NamespaceManager"] = None) -> str:
"""
This will do a limited check for valid URIs,
essentially just making sure that the string includes no illegal
characters (``<, >, ", {, }, |, \\, `, ^``)
:param namespace_manager: if not None, will be used to make up
a prefixed name
"""
if not _is_valid_uri(self):
raise Exception(
'"%s" does not look like a valid URI, I cannot serialize this as N3/Turtle. Perhaps you wanted to urlencode it?'
% self
)
if namespace_manager:
return namespace_manager.normalizeUri(self)
else:
return "<%s>" % self
def defrag(self) -> "URIRef":
if "#" in self:
url, frag = urldefrag(self)
return URIRef(url)
else:
return self
@property
def fragment(self) -> str:
"""
Return the URL Fragment
>>> URIRef("http://example.com/some/path/#some-fragment").fragment
'some-fragment'
>>> URIRef("http://example.com/some/path/").fragment
''
"""
return urlparse(self).fragment
def __reduce__(self) -> Tuple[Type["URIRef"], Tuple[str]]:
return (URIRef, (str(self),))
def __repr__(self) -> str:
if self.__class__ is URIRef:
clsName = "rdflib.term.URIRef" # noqa: N806
else:
clsName = self.__class__.__name__ # noqa: N806
return """%s(%s)""" % (clsName, super(URIRef, self).__repr__())
def __add__(self, other) -> "URIRef":
return self.__class__(str(self) + other)
def __radd__(self, other) -> "URIRef":
return self.__class__(other + str(self))
def __mod__(self, other) -> "URIRef":
return self.__class__(str(self) % other)
def de_skolemize(self) -> "BNode":
"""Create a Blank Node from a skolem URI, in accordance
with http://www.w3.org/TR/rdf11-concepts/#section-skolemization.
This function accepts only rdflib type skolemization, to provide
a round-tripping within the system.
.. versionadded:: 4.0
"""
if isinstance(self, RDFLibGenid):
parsed_uri = urlparse("%s" % self)
return BNode(value=parsed_uri.path[len(rdflib_skolem_genid) :])
elif isinstance(self, Genid):
bnode_id = "%s" % self
if bnode_id in skolems:
return skolems[bnode_id]
else:
retval = BNode()
skolems[bnode_id] = retval
return retval
else:
raise Exception("<%s> is not a skolem URI" % self)
class Genid(URIRef):
__slots__ = ()
@staticmethod
def _is_external_skolem(uri: Any) -> bool:
if not isinstance(uri, str):
uri = str(uri)
parsed_uri = urlparse(uri)
gen_id = parsed_uri.path.rfind(skolem_genid)
if gen_id != 0:
return False
return True
class RDFLibGenid(Genid):
__slots__ = ()
@staticmethod
def _is_rdflib_skolem(uri: Any) -> bool:
if not isinstance(uri, str):
uri = str(uri)
parsed_uri = urlparse(uri)
if (
parsed_uri.params != ""
or parsed_uri.query != ""
or parsed_uri.fragment != ""
):
return False
gen_id = parsed_uri.path.rfind(rdflib_skolem_genid)
if gen_id != 0:
return False
return True
def _unique_id() -> str:
# Used to read: """Create a (hopefully) unique prefix"""
# now retained merely to leave internal API unchanged.
# From BNode.__new__() below ...
#
# acceptable bnode value range for RDF/XML needs to be
# something that can be serialzed as a nodeID for N3
#
# BNode identifiers must be valid NCNames" _:[A-Za-z][A-Za-z0-9]*
# http://www.w3.org/TR/2004/REC-rdf-testcases-20040210/#nodeID
return "N" # ensure that id starts with a letter
def _serial_number_generator() -> Callable[[], str]:
"""
Generates UUID4-based but ncname-compliant identifiers.
"""
from uuid import uuid4
def _generator():
return uuid4().hex
return _generator
class BNode(IdentifiedNode):
"""
RDF 1.1's Blank Nodes Section: https://www.w3.org/TR/rdf11-concepts/#section-blank-nodes
Blank Nodes are local identifiers for unnamed nodes in RDF graphs that are used in
some concrete RDF syntaxes or RDF store implementations. They are always locally
scoped to the file or RDF store, and are not persistent or portable identifiers for
blank nodes. The identifiers for Blank Nodes are not part of the RDF abstract
syntax, but are entirely dependent on particular concrete syntax or implementation
(such as Turtle, JSON-LD).
---
RDFLib's ``BNode`` class makes unique IDs for all the Blank Nodes in a Graph but you
should *never* expect, or reply on, BNodes' IDs to match across graphs, or even for
multiple copies of the same graph, if they are regenerated from some non-RDFLib
source, such as loading from RDF data.
"""
__slots__ = ()
def __new__(
cls,
value: Optional[str] = None,
_sn_gen: Callable[[], str] = _serial_number_generator(),
_prefix: str = _unique_id(),
) -> "BNode":
"""
# only store implementations should pass in a value
"""
if value is None:
# so that BNode values do not collide with ones created with
# a different instance of this module at some other time.
node_id = _sn_gen()
value = "%s%s" % (_prefix, node_id)
else:
# TODO: check that value falls within acceptable bnode value range
# for RDF/XML needs to be something that can be serialzed
# as a nodeID for N3 ?? Unless we require these
# constraints be enforced elsewhere?
pass # assert is_ncname(str(value)), "BNode identifiers
# must be valid NCNames" _:[A-Za-z][A-Za-z0-9]*
# http://www.w3.org/TR/2004/REC-rdf-testcases-20040210/#nodeID
# type error: Incompatible return value type (got "Identifier", expected "BNode")
return Identifier.__new__(cls, value) # type: ignore[return-value]
def n3(self, namespace_manager: Optional["NamespaceManager"] = None) -> str:
return "_:%s" % self
def __reduce__(self) -> Tuple[Type["BNode"], Tuple[str]]:
return (BNode, (str(self),))
def __repr__(self) -> str:
if self.__class__ is BNode:
clsName = "rdflib.term.BNode" # noqa: N806
else:
clsName = self.__class__.__name__ # noqa: N806
return """%s('%s')""" % (clsName, str(self))
def skolemize(
self, authority: Optional[str] = None, basepath: Optional[str] = None
) -> URIRef:
"""Create a URIRef "skolem" representation of the BNode, in accordance
with http://www.w3.org/TR/rdf11-concepts/#section-skolemization
.. versionadded:: 4.0
"""
if authority is None:
authority = _SKOLEM_DEFAULT_AUTHORITY
if basepath is None:
basepath = rdflib_skolem_genid
skolem = "%s%s" % (basepath, str(self))
return URIRef(urljoin(authority, skolem))
class Literal(Identifier):
__doc__ = """
RDF 1.1's Literals Section: http://www.w3.org/TR/rdf-concepts/#section-Graph-Literal
Literals are used for values such as strings, numbers, and dates.
A literal in an RDF graph consists of two or three elements:
* a lexical form, being a Unicode string, which SHOULD be in Normal Form C
* a datatype IRI, being an IRI identifying a datatype that determines how the lexical form maps to a literal value, and
* if and only if the datatype IRI is ``http://www.w3.org/1999/02/22-rdf-syntax-ns#langString``, a non-empty language tag. The language tag MUST be well-formed according to section 2.2.9 of `Tags for identifying languages <http://tools.ietf.org/html/bcp47>`_.
A literal is a language-tagged string if the third element is present. Lexical representations of language tags MAY be converted to lower case. The value space of language tags is always in lower case.
---
For valid XSD datatypes, the lexical form is optionally normalized
at construction time. Default behaviour is set by rdflib.NORMALIZE_LITERALS
and can be overridden by the normalize parameter to __new__
Equality and hashing of Literals are done based on the lexical form, i.e.:
>>> from rdflib.namespace import XSD
>>> Literal('01') != Literal('1') # clear - strings differ
True
but with data-type they get normalized:
>>> Literal('01', datatype=XSD.integer) != Literal('1', datatype=XSD.integer)
False
unless disabled:
>>> Literal('01', datatype=XSD.integer, normalize=False) != Literal('1', datatype=XSD.integer)
True
Value based comparison is possible:
>>> Literal('01', datatype=XSD.integer).eq(Literal('1', datatype=XSD.float))
True
The eq method also provides limited support for basic python types:
>>> Literal(1).eq(1) # fine - int compatible with xsd:integer
True
>>> Literal('a').eq('b') # fine - str compatible with plain-lit
False
>>> Literal('a', datatype=XSD.string).eq('a') # fine - str compatible with xsd:string
True
>>> Literal('a').eq(1) # not fine, int incompatible with plain-lit
NotImplemented
Greater-than/less-than ordering comparisons are also done in value
space, when compatible datatypes are used. Incompatible datatypes
are ordered by DT, or by lang-tag. For other nodes the ordering
is None < BNode < URIRef < Literal
Any comparison with non-rdflib Node are "NotImplemented"
In PY3 this is an error.
>>> from rdflib import Literal, XSD
>>> lit2006 = Literal('2006-01-01',datatype=XSD.date)
>>> lit2006.toPython()
datetime.date(2006, 1, 1)
>>> lit2006 < Literal('2007-01-01',datatype=XSD.date)
True
>>> Literal(datetime.utcnow()).datatype
rdflib.term.URIRef(u'http://www.w3.org/2001/XMLSchema#dateTime')
>>> Literal(1) > Literal(2) # by value
False
>>> Literal(1) > Literal(2.0) # by value
False
>>> Literal('1') > Literal(1) # by DT
True
>>> Literal('1') < Literal('1') # by lexical form
False
>>> Literal('a', lang='en') > Literal('a', lang='fr') # by lang-tag
False
>>> Literal(1) > URIRef('foo') # by node-type
True
The > < operators will eat this NotImplemented and throw a TypeError (py3k):
>>> Literal(1).__gt__(2.0)
NotImplemented
"""
_value: Any
_language: Optional[str]
# NOTE: _datatype should maybe be of type URIRef, and not optional.
_datatype: Optional[URIRef]
_ill_typed: Optional[bool]
__slots__ = ("_language", "_datatype", "_value", "_ill_typed")
def __new__(
cls,
lexical_or_value: Any,
lang: Optional[str] = None,
datatype: Optional[str] = None,
normalize: Optional[bool] = None,
) -> "Literal":
if lang == "":
lang = None # no empty lang-tags in RDF
normalize = normalize if normalize is not None else rdflib.NORMALIZE_LITERALS
if lang is not None and datatype is not None:
raise TypeError(
"A Literal can only have one of lang or datatype, "
"per http://www.w3.org/TR/rdf-concepts/#section-Graph-Literal"
)
if lang is not None and not _is_valid_langtag(lang):
raise ValueError(f"'{str(lang)}' is not a valid language tag!")
if datatype is not None:
datatype = URIRef(datatype)
value = None
ill_typed: Optional[bool] = None
if isinstance(lexical_or_value, Literal):
# create from another Literal instance
lang = lang or lexical_or_value.language
if datatype is not None:
# override datatype
value = _castLexicalToPython(lexical_or_value, datatype)
else:
datatype = lexical_or_value.datatype
value = lexical_or_value.value
elif isinstance(lexical_or_value, str) or isinstance(lexical_or_value, bytes):
# passed a string
# try parsing lexical form of datatyped literal
value = _castLexicalToPython(lexical_or_value, datatype)
if datatype is not None and datatype in _toPythonMapping:
# datatype is a recognized datatype IRI:
# https://www.w3.org/TR/rdf11-concepts/#dfn-recognized-datatype-iris
dt_uri: URIRef = URIRef(datatype)
checker = _check_well_formed_types.get(dt_uri, _well_formed_by_value)
well_formed = checker(lexical_or_value, value)
ill_typed = ill_typed or (not well_formed)
if value is not None and normalize:
_value, _datatype = _castPythonToLiteral(value, datatype)
if _value is not None and _is_valid_unicode(_value):
lexical_or_value = _value
else:
# passed some python object
value = lexical_or_value
_value, _datatype = _castPythonToLiteral(lexical_or_value, datatype)
_datatype = None if _datatype is None else URIRef(_datatype)
datatype = rdflib.util._coalesce(datatype, _datatype)
if _value is not None:
lexical_or_value = _value
if datatype is not None:
lang = None
if isinstance(lexical_or_value, bytes):
lexical_or_value = lexical_or_value.decode("utf-8")
if datatype in (_XSD_NORMALISED_STRING, _XSD_TOKEN):
lexical_or_value = _normalise_XSD_STRING(lexical_or_value)
if datatype in (_XSD_TOKEN,):
lexical_or_value = _strip_and_collapse_whitespace(lexical_or_value)
try:
inst: Literal = str.__new__(cls, lexical_or_value)
except UnicodeDecodeError:
inst = str.__new__(cls, lexical_or_value, "utf-8")
inst._language = lang
inst._datatype = datatype
inst._value = value
inst._ill_typed = ill_typed
return inst
def normalize(self) -> "Literal":
"""
Returns a new literal with a normalised lexical representation
of this literal
>>> from rdflib import XSD
>>> Literal("01", datatype=XSD.integer, normalize=False).normalize()
rdflib.term.Literal(u'1', datatype=rdflib.term.URIRef(u'http://www.w3.org/2001/XMLSchema#integer'))
Illegal lexical forms for the datatype given are simply passed on
>>> Literal("a", datatype=XSD.integer, normalize=False)
rdflib.term.Literal(u'a', datatype=rdflib.term.URIRef(u'http://www.w3.org/2001/XMLSchema#integer'))
"""
if self.value is not None:
return Literal(self.value, datatype=self.datatype, lang=self.language)
else:
return self
@property
def ill_typed(self) -> Optional[bool]:
"""
For `recognized datatype IRIs
<https://www.w3.org/TR/rdf11-concepts/#dfn-recognized-datatype-iris>`_,
this value will be `True` if the literal is ill formed, otherwise it
will be `False`. `Literal.value` (i.e. the `literal value <https://www.w3.org/TR/rdf11-concepts/#dfn-literal-value>`_) should always be defined if this property is `False`, but should not be considered reliable if this property is `True`.
If the literal's datatype is `None` or not in the set of `recognized datatype IRIs
<https://www.w3.org/TR/rdf11-concepts/#dfn-recognized-datatype-iris>`_ this value will be `None`.
"""
return self._ill_typed
@property
def value(self) -> Any:
return self._value
@property
def language(self) -> Optional[str]:
return self._language
@property
def datatype(self) -> Optional[URIRef]:
return self._datatype
def __reduce__(
self,
) -> Tuple[Type["Literal"], Tuple[str, Union[str, None], Union[str, None]]]:
return (
Literal,
(str(self), self.language, self.datatype),
)
def __getstate__(self) -> Tuple[None, Dict[str, Union[str, None]]]:
return (None, dict(language=self.language, datatype=self.datatype))
def __setstate__(self, arg: Tuple[Any, Dict[str, Any]]) -> None:
_, d = arg
self._language = d["language"]
self._datatype = d["datatype"]
def __add__(self, val: Any) -> "Literal":
"""
>>> from rdflib.namespace import XSD
>>> Literal(1) + 1
rdflib.term.Literal(u'2', datatype=rdflib.term.URIRef(u'http://www.w3.org/2001/XMLSchema#integer'))
>>> Literal("1") + "1"
rdflib.term.Literal(u'11')
# Handling dateTime/date/time based operations in Literals
>>> a = Literal('2006-01-01T20:50:00', datatype=XSD.dateTime)
>>> b = Literal('P31D', datatype=XSD.duration)
>>> (a + b)
rdflib.term.Literal('2006-02-01T20:50:00', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#dateTime'))
>>> from rdflib.namespace import XSD
>>> a = Literal('2006-07-01T20:52:00', datatype=XSD.dateTime)
>>> b = Literal('P122DT15H58M', datatype=XSD.duration)
>>> (a + b)
rdflib.term.Literal('2006-11-01T12:50:00', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#dateTime'))
"""
# if no val is supplied, return this Literal
if val is None:
return self
# convert the val to a Literal, if it isn't already one
if not isinstance(val, Literal):
val = Literal(val)
# if self is datetime based and value is duration
if (
self.datatype in (_XSD_DATETIME, _XSD_DATE)
and val.datatype in _TIME_DELTA_TYPES
):
date1: Union[datetime, date] = self.toPython()
duration: Union[Duration, timedelta] = val.toPython()
difference = date1 + duration
return Literal(difference, datatype=self.datatype)
# if self is time based and value is duration
elif self.datatype == _XSD_TIME and val.datatype in _TIME_DELTA_TYPES:
selfv: time = self.toPython()
valv: Union[Duration, timedelta] = val.toPython()
sdt = datetime.combine(date(2000, 1, 1), selfv) + valv
return Literal(sdt.time(), datatype=self.datatype)
# if self is datetime based and value is not or vice versa
elif (
(
self.datatype in _ALL_DATE_AND_TIME_TYPES
and val.datatype not in _ALL_DATE_AND_TIME_TYPES
)
or (
self.datatype not in _ALL_DATE_AND_TIME_TYPES
and val.datatype in _ALL_DATE_AND_TIME_TYPES
)
or (
self.datatype in _TIME_DELTA_TYPES
and (
(val.datatype not in _TIME_DELTA_TYPES)
or (self.datatype != val.datatype)
)
)
):
raise TypeError(
f"Cannot add a Literal of datatype {str(val.datatype)} to a Literal of datatype {str(self.datatype)}"
)
# if the datatypes are the same, just add the Python values and convert back
if self.datatype == val.datatype:
return Literal(
self.toPython() + val.toPython(), self.language, datatype=self.datatype
)
# if the datatypes are not the same but are both numeric, add the Python values and strip off decimal junk
# (i.e. tiny numbers (more than 17 decimal places) and trailing zeros) and return as a decimal
elif (
self.datatype in _NUMERIC_LITERAL_TYPES
and val.datatype in _NUMERIC_LITERAL_TYPES
):
return Literal(
Decimal(
(
"%f"
% round(Decimal(self.toPython()) + Decimal(val.toPython()), 15)
)
.rstrip("0")
.rstrip(".")
),
datatype=_XSD_DECIMAL,
)
# in all other cases, perform string concatenation
else:
try:
s = str.__add__(self, val)
except TypeError:
s = str(self.value) + str(val)
# if the original datatype is string-like, use that
if self.datatype in _STRING_LITERAL_TYPES:
new_datatype = self.datatype
# if not, use string
else:
new_datatype = _XSD_STRING
return Literal(s, self.language, datatype=new_datatype)
def __sub__(self, val: Any) -> "Literal":
"""
>>> from rdflib.namespace import XSD
>>> Literal(2) - 1
rdflib.term.Literal('1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))
>>> Literal(1.1) - 1.0
rdflib.term.Literal('0.10000000000000009', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#double'))
>>> Literal(1.1) - 1
rdflib.term.Literal('0.1', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#decimal'))
>>> Literal(1.1, datatype=XSD.float) - Literal(1.0, datatype=XSD.float)
rdflib.term.Literal('0.10000000000000009', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#float'))
>>> Literal("1.1") - 1.0 # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
TypeError: Not a number; rdflib.term.Literal('1.1')
>>> Literal(1.1, datatype=XSD.integer) - Literal(1.0, datatype=XSD.integer)
rdflib.term.Literal('0.10000000000000009', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#integer'))
# Handling dateTime/date/time based operations in Literals
>>> a = Literal('2006-01-01T20:50:00', datatype=XSD.dateTime)
>>> b = Literal('2006-02-01T20:50:00', datatype=XSD.dateTime)
>>> (b - a)
rdflib.term.Literal('P31D', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#duration'))
>>> from rdflib.namespace import XSD
>>> a = Literal('2006-07-01T20:52:00', datatype=XSD.dateTime)
>>> b = Literal('2006-11-01T12:50:00', datatype=XSD.dateTime)
>>> (a - b)
rdflib.term.Literal('-P122DT15H58M', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#duration'))
>>> (b - a)
rdflib.term.Literal('P122DT15H58M', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#duration'))
"""
# if no val is supplied, return this Literal
if val is None:
return self
# convert the val to a Literal, if it isn't already one
if not isinstance(val, Literal):
val = Literal(val)
if not getattr(self, "datatype"):
raise TypeError(
"Minuend Literal must have Numeric, Date, Datetime or Time datatype."
)
elif not getattr(val, "datatype"):
raise TypeError(
"Subtrahend Literal must have Numeric, Date, Datetime or Time datatype."
)
if (
self.datatype in (_XSD_DATETIME, _XSD_DATE)
and val.datatype in _TIME_DELTA_TYPES
):
date1: Union[datetime, date] = self.toPython()
duration: Union[Duration, timedelta] = val.toPython()
difference = date1 - duration
return Literal(difference, datatype=self.datatype)
# if self is time based and value is duration
elif self.datatype == _XSD_TIME and val.datatype in _TIME_DELTA_TYPES:
selfv: time = self.toPython()
valv: Union[Duration, timedelta] = val.toPython()
sdt = datetime.combine(date(2000, 1, 1), selfv) - valv
return Literal(sdt.time(), datatype=self.datatype)
# if the datatypes are the same, just subtract the Python values and convert back
if self.datatype == val.datatype:
if self.datatype == _XSD_TIME:
sdt = datetime.combine(date.today(), self.toPython())
vdt = datetime.combine(date.today(), val.toPython())
return Literal(sdt - vdt, datatype=_XSD_DURATION)
else:
return Literal(
self.toPython() - val.toPython(),
self.language,
datatype=_XSD_DURATION
if self.datatype in (_XSD_DATETIME, _XSD_DATE, _XSD_TIME)
else self.datatype,
)
# if the datatypes are not the same but are both numeric, subtract the Python values and strip off decimal junk
# (i.e. tiny numbers (more than 17 decimal places) and trailing zeros) and return as a decimal
elif (
self.datatype in _NUMERIC_LITERAL_TYPES
and val.datatype in _NUMERIC_LITERAL_TYPES
):
return Literal(
Decimal(
(
"%f"
% round(Decimal(self.toPython()) - Decimal(val.toPython()), 15)
)
.rstrip("0")
.rstrip(".")
),
datatype=_XSD_DECIMAL,
)
# in all other cases, perform string concatenation
else:
raise TypeError(
f"Cannot subtract a Literal of datatype {str(val.datatype)} from a Literal of datatype {str(self.datatype)}"
)
def __bool__(self) -> bool:
"""
Is the Literal "True"
This is used for if statements, bool(literal), etc.
"""
if self.value is not None:
return bool(self.value)
return len(self) != 0
def __neg__(self) -> "Literal":
"""
>>> (- Literal(1))
rdflib.term.Literal(u'-1', datatype=rdflib.term.URIRef(u'http://www.w3.org/2001/XMLSchema#integer'))
>>> (- Literal(10.5))
rdflib.term.Literal(u'-10.5', datatype=rdflib.term.URIRef(u'http://www.w3.org/2001/XMLSchema#double'))
>>> from rdflib.namespace import XSD
>>> (- Literal("1", datatype=XSD.integer))
rdflib.term.Literal(u'-1', datatype=rdflib.term.URIRef(u'http://www.w3.org/2001/XMLSchema#integer'))
>>> (- Literal("1"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Not a number; rdflib.term.Literal(u'1')
>>>
"""
if isinstance(self.value, (int, long_type, float)):
return Literal(self.value.__neg__())
else:
raise TypeError("Not a number; %s" % repr(self))
def __pos__(self) -> "Literal":
"""
>>> (+ Literal(1))
rdflib.term.Literal(u'1', datatype=rdflib.term.URIRef(u'http://www.w3.org/2001/XMLSchema#integer'))
>>> (+ Literal(-1))
rdflib.term.Literal(u'-1', datatype=rdflib.term.URIRef(u'http://www.w3.org/2001/XMLSchema#integer'))
>>> from rdflib.namespace import XSD
>>> (+ Literal("-1", datatype=XSD.integer))
rdflib.term.Literal(u'-1', datatype=rdflib.term.URIRef(u'http://www.w3.org/2001/XMLSchema#integer'))
>>> (+ Literal("1"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Not a number; rdflib.term.Literal(u'1')
"""
if isinstance(self.value, (int, long_type, float)):
return Literal(self.value.__pos__())
else:
raise TypeError("Not a number; %s" % repr(self))
def __abs__(self) -> "Literal":
"""
>>> abs(Literal(-1))
rdflib.term.Literal(u'1', datatype=rdflib.term.URIRef(u'http://www.w3.org/2001/XMLSchema#integer'))
>>> from rdflib.namespace import XSD
>>> abs( Literal("-1", datatype=XSD.integer))
rdflib.term.Literal(u'1', datatype=rdflib.term.URIRef(u'http://www.w3.org/2001/XMLSchema#integer'))
>>> abs(Literal("1"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Not a number; rdflib.term.Literal(u'1')
"""
if isinstance(self.value, (int, long_type, float)):
return Literal(self.value.__abs__())
else:
raise TypeError("Not a number; %s" % repr(self))
def __invert__(self) -> "Literal":
"""
>>> ~(Literal(-1))
rdflib.term.Literal(u'0', datatype=rdflib.term.URIRef(u'http://www.w3.org/2001/XMLSchema#integer'))
>>> from rdflib.namespace import XSD
>>> ~( Literal("-1", datatype=XSD.integer))
rdflib.term.Literal(u'0', datatype=rdflib.term.URIRef(u'http://www.w3.org/2001/XMLSchema#integer'))
Not working:
>>> ~(Literal("1"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Not a number; rdflib.term.Literal(u'1')
"""
if isinstance(self.value, (int, long_type, float)):
# type error: Unsupported operand type for ~ ("float")
return Literal(self.value.__invert__()) # type: ignore[operator] # FIXME
else:
raise TypeError("Not a number; %s" % repr(self))
def __gt__(self, other: Any) -> bool:
"""
This implements ordering for Literals,
the other comparison methods delegate here
This tries to implement this:
http://www.w3.org/TR/sparql11-query/#modOrderBy
In short, Literals with compatible data-types are ordered in value
space, i.e.
>>> from rdflib import XSD
>>> Literal(1) > Literal(2) # int/int
False
>>> Literal(2.0) > Literal(1) # double/int
True
>>> from decimal import Decimal
>>> Literal(Decimal("3.3")) > Literal(2.0) # decimal/double
True
>>> Literal(Decimal("3.3")) < Literal(4.0) # decimal/double
True
>>> Literal('b') > Literal('a') # plain lit/plain lit
True
>>> Literal('b') > Literal('a', datatype=XSD.string) # plain lit/xsd:str
True
Incompatible datatype mismatches ordered by DT
>>> Literal(1) > Literal("2") # int>string
False
Langtagged literals by lang tag
>>> Literal("a", lang="en") > Literal("a", lang="fr")
False
"""
if other is None:
return True # Everything is greater than None
if isinstance(other, Literal):
if (
self.datatype in _NUMERIC_LITERAL_TYPES
and other.datatype in _NUMERIC_LITERAL_TYPES
):
return self.value > other.value
# plain-literals and xsd:string literals
# are "the same"
dtself = rdflib.util._coalesce(self.datatype, default=_XSD_STRING)
dtother = rdflib.util._coalesce(other.datatype, default=_XSD_STRING)
if dtself != dtother:
if rdflib.DAWG_LITERAL_COLLATION:
return NotImplemented
else:
return dtself > dtother
if self.language != other.language:
if not self.language:
return False
elif not other.language:
return True
else:
return self.language > other.language
if self.value is not None and other.value is not None:
if type(self.value) in _TOTAL_ORDER_CASTERS:
caster = _TOTAL_ORDER_CASTERS[type(self.value)]
return caster(self.value) > caster(other.value)
try:
return self.value > other.value
except TypeError:
pass
if str(self) != str(other):
return str(self) > str(other)
# same language, same lexical form, check real dt
# plain-literals come before xsd:string!
if self.datatype != other.datatype:
if self.datatype is None:
return False
elif other.datatype is None:
return True
else:
return self.datatype > other.datatype
return False # they are the same
elif isinstance(other, Node):
return True # Literal are the greatest!
else:
return NotImplemented # we can only compare to nodes
def __lt__(self, other: Any) -> bool:
if other is None:
return False # Nothing is less than None
if isinstance(other, Literal):
try:
return not self.__gt__(other) and not self.eq(other)
except TypeError:
return NotImplemented
if isinstance(other, Node):
return False # all nodes are less-than Literals
return NotImplemented
def __le__(self, other: Any) -> bool:
"""
>>> from rdflib.namespace import XSD
>>> Literal('2007-01-01T10:00:00', datatype=XSD.dateTime
... ) <= Literal('2007-01-01T10:00:00', datatype=XSD.dateTime)
True
"""
r = self.__lt__(other)
if r:
return True
try:
return self.eq(other)
except TypeError:
return NotImplemented
def __ge__(self, other: Any) -> bool:
r = self.__gt__(other)
if r:
return True
try:
return self.eq(other)
except TypeError:
return NotImplemented
def _comparable_to(self, other: Any) -> bool:
"""
Helper method to decide which things are meaningful to
rich-compare with this literal
"""
if isinstance(other, Literal):
if self.datatype is not None and other.datatype is not None:
# two datatyped literals
if (
self.datatype not in XSDToPython
or other.datatype not in XSDToPython
):
# non XSD DTs must match
if self.datatype != other.datatype:
return False
else:
# xsd:string may be compared with plain literals
if not (self.datatype == _XSD_STRING and not other.datatype) or (
other.datatype == _XSD_STRING and not self.datatype
):
return False
# if given lang-tag has to be case insensitive equal
if (self.language or "").lower() != (other.language or "").lower():
return False
return True
# type error: Signature of "__hash__" incompatible with supertype "Identifier"
# Superclass: def __hash__(self: str) -> int
# Subclass: def __hash__(self) -> int
# NOTE for type ignore: This can possibly be fixed by changing how __hash__ is implemented in Identifier
def __hash__(self) -> int: # type: ignore[override]
"""
>>> from rdflib.namespace import XSD
>>> a = {Literal('1', datatype=XSD.integer):'one'}
>>> Literal('1', datatype=XSD.double) in a
False
"Called for the key object for dictionary operations,
and by the built-in function hash(). Should return
a 32-bit integer usable as a hash value for
dictionary operations. The only required property
is that objects which compare equal have the same
hash value; it is advised to somehow mix together
(e.g., using exclusive or) the hash values for the
components of the object that also play a part in
comparison of objects." -- 3.4.1 Basic customization (Python)
"Two literals are equal if and only if all of the following hold:
* The strings of the two lexical forms compare equal, character by
character.
* Either both or neither have language tags.
* The language tags, if any, compare equal.
* Either both or neither have datatype URIs.
* The two datatype URIs, if any, compare equal, character by
character."
-- 6.5.1 Literal Equality (RDF: Concepts and Abstract Syntax)
"""
# don't use super()... for efficiency reasons, see Identifier.__hash__
res = str.__hash__(self)
# Directly accessing the member is faster than the property.
if self._language:
res ^= hash(self._language.lower())
if self._datatype is not None:
res ^= hash(self._datatype)
return res
def __eq__(self, other: Any) -> bool:
"""
Literals are only equal to other literals.
"Two literals are equal if and only if all of the following hold:
* The strings of the two lexical forms compare equal, character by character.
* Either both or neither have language tags.
* The language tags, if any, compare equal.
* Either both or neither have datatype URIs.
* The two datatype URIs, if any, compare equal, character by character."
-- 6.5.1 Literal Equality (RDF: Concepts and Abstract Syntax)
>>> Literal("1", datatype=URIRef("foo")) == Literal("1", datatype=URIRef("foo"))
True
>>> Literal("1", datatype=URIRef("foo")) == Literal("1", datatype=URIRef("foo2"))
False
>>> Literal("1", datatype=URIRef("foo")) == Literal("2", datatype=URIRef("foo"))
False
>>> Literal("1", datatype=URIRef("foo")) == "asdf"
False
>>> from rdflib import XSD
>>> Literal('2007-01-01', datatype=XSD.date) == Literal('2007-01-01', datatype=XSD.date)
True
>>> Literal('2007-01-01', datatype=XSD.date) == date(2007, 1, 1)
False
>>> Literal("one", lang="en") == Literal("one", lang="en")
True
>>> Literal("hast", lang='en') == Literal("hast", lang='de')
False
>>> Literal("1", datatype=XSD.integer) == Literal(1)
True
>>> Literal("1", datatype=XSD.integer) == Literal("01", datatype=XSD.integer)
True
"""
if self is other:
return True
if other is None:
return False
# Directly accessing the member is faster than the property.
if isinstance(other, Literal):
return (
self._datatype == other._datatype
and (self._language.lower() if self._language else None)
== (other._language.lower() if other._language else None)
and str.__eq__(self, other)
)
return False
def eq(self, other: Any) -> bool:
"""
Compare the value of this literal with something else
Either, with the value of another literal
comparisons are then done in literal "value space",
and according to the rules of XSD subtype-substitution/type-promotion
OR, with a python object:
basestring objects can be compared with plain-literals,
or those with datatype xsd:string
bool objects with xsd:boolean
a int, long or float with numeric xsd types
isodate date,time,datetime objects with xsd:date,xsd:time or xsd:datetime
Any other operations returns NotImplemented
"""
if isinstance(other, Literal):
if (
self.datatype in _NUMERIC_LITERAL_TYPES
and other.datatype in _NUMERIC_LITERAL_TYPES
):
if self.value is not None and other.value is not None:
return self.value == other.value
else:
if str.__eq__(self, other):
return True
raise TypeError(
"I cannot know that these two lexical forms do not map to the same value: %s and %s"
% (self, other)
)
if (self.language or "").lower() != (other.language or "").lower():
return False
dtself = rdflib.util._coalesce(self.datatype, default=_XSD_STRING)
dtother = rdflib.util._coalesce(other.datatype, default=_XSD_STRING)
if dtself == _XSD_STRING and dtother == _XSD_STRING:
# string/plain literals, compare on lexical form
return str.__eq__(self, other)
if dtself != dtother:
if rdflib.DAWG_LITERAL_COLLATION:
raise TypeError(
"I don't know how to compare literals with datatypes %s and %s"
% (self.datatype, other.datatype)
)
else:
return False
# matching non-string DTs now - do we compare values or
# lexical form first? comparing two ints is far quicker -
# maybe there are counter examples
if self.value is not None and other.value is not None:
if self.datatype in (_RDF_XMLLITERAL, _RDF_HTMLLITERAL):
return _isEqualXMLNode(self.value, other.value)
return self.value == other.value
else:
if str.__eq__(self, other):
return True
if self.datatype == _XSD_STRING:
return False # string value space=lexical space
# matching DTs, but not matching, we cannot compare!
raise TypeError(
"I cannot know that these two lexical forms do not map to the same value: %s and %s"
% (self, other)
)
elif isinstance(other, Node):
return False # no non-Literal nodes are equal to a literal
elif isinstance(other, str):
# only plain-literals can be directly compared to strings
# TODO: Is "blah"@en eq "blah" ?
if self.language is not None:
return False
if self.datatype == _XSD_STRING or self.datatype is None:
return str(self) == other
elif isinstance(other, (int, long_type, float)):
if self.datatype in _NUMERIC_LITERAL_TYPES:
return self.value == other
elif isinstance(other, (date, datetime, time)):
if self.datatype in (_XSD_DATETIME, _XSD_DATE, _XSD_TIME):
return self.value == other
elif isinstance(other, (timedelta, Duration)):
if self.datatype in (
_XSD_DURATION,
_XSD_DAYTIMEDURATION,
_XSD_YEARMONTHDURATION,
):
return self.value == other
# NOTE for type ignore: bool is a subclass of int so this won't ever run.
elif isinstance(other, bool): # type: ignore[unreachable]
if self.datatype == _XSD_BOOLEAN:
return self.value == other
return NotImplemented
def neq(self, other: Any) -> bool:
return not self.eq(other)
def n3(self, namespace_manager: Optional["NamespaceManager"] = None) -> str:
r'''
Returns a representation in the N3 format.
Examples::
>>> Literal("foo").n3()
u'"foo"'
Strings with newlines or triple-quotes::
>>> Literal("foo\nbar").n3()
u'"""foo\nbar"""'
>>> Literal("''\'").n3()
u'"\'\'\'"'
>>> Literal('"""').n3()
u'"\\"\\"\\""'
Language::
>>> Literal("hello", lang="en").n3()
u'"hello"@en'
Datatypes::
>>> Literal(1).n3()
u'"1"^^<http://www.w3.org/2001/XMLSchema#integer>'
>>> Literal(1.0).n3()
u'"1.0"^^<http://www.w3.org/2001/XMLSchema#double>'
>>> Literal(True).n3()
u'"true"^^<http://www.w3.org/2001/XMLSchema#boolean>'
Datatype and language isn't allowed (datatype takes precedence)::
>>> Literal(1, lang="en").n3()
u'"1"^^<http://www.w3.org/2001/XMLSchema#integer>'
Custom datatype::
>>> footype = URIRef("http://example.org/ns#foo")
>>> Literal("1", datatype=footype).n3()
u'"1"^^<http://example.org/ns#foo>'
Passing a namespace-manager will use it to abbreviate datatype URIs:
>>> from rdflib import Graph
>>> Literal(1).n3(Graph().namespace_manager)
u'"1"^^xsd:integer'
'''
if namespace_manager:
return self._literal_n3(qname_callback=namespace_manager.normalizeUri)
else:
return self._literal_n3()
def _literal_n3(
self,
use_plain: bool = False,
qname_callback: Optional[Callable[[str], str]] = None,
) -> str:
"""
Using plain literal (shorthand) output::
>>> from rdflib.namespace import XSD
>>> Literal(1)._literal_n3(use_plain=True)
u'1'
>>> Literal(1.0)._literal_n3(use_plain=True)
u'1e+00'
>>> Literal(1.0, datatype=XSD.decimal)._literal_n3(use_plain=True)
u'1.0'
>>> Literal(1.0, datatype=XSD.float)._literal_n3(use_plain=True)
u'"1.0"^^<http://www.w3.org/2001/XMLSchema#float>'
>>> Literal("foo", datatype=XSD.string)._literal_n3(
... use_plain=True)
u'"foo"^^<http://www.w3.org/2001/XMLSchema#string>'
>>> Literal(True)._literal_n3(use_plain=True)
u'true'
>>> Literal(False)._literal_n3(use_plain=True)
u'false'
>>> Literal(1.91)._literal_n3(use_plain=True)
u'1.91e+00'
Only limited precision available for floats:
>>> Literal(0.123456789)._literal_n3(use_plain=True)
u'1.234568e-01'
>>> Literal('0.123456789',
... datatype=XSD.decimal)._literal_n3(use_plain=True)
u'0.123456789'
Using callback for datatype QNames::
>>> Literal(1)._literal_n3(
... qname_callback=lambda uri: "xsd:integer")
u'"1"^^xsd:integer'
"""
if use_plain and self.datatype in _PLAIN_LITERAL_TYPES:
if self.value is not None:
# If self is inf or NaN, we need a datatype
# (there is no plain representation)
if self.datatype in _NUMERIC_INF_NAN_LITERAL_TYPES:
try:
v = float(self)
if math.isinf(v) or math.isnan(v):
return self._literal_n3(False, qname_callback)
except ValueError:
return self._literal_n3(False, qname_callback)
# this is a bit of a mess -
# in py >=2.6 the string.format function makes this easier
# we try to produce "pretty" output
if self.datatype == _XSD_DOUBLE:
return sub("\\.?0*e", "e", "%e" % float(self))
elif self.datatype == _XSD_DECIMAL:
s = "%s" % self
if "." not in s and "e" not in s and "E" not in s:
s += ".0"
return s
elif self.datatype == _XSD_BOOLEAN:
return ("%s" % self).lower()
else:
return "%s" % self
encoded = self._quote_encode()
datatype = self.datatype
quoted_dt = None
if datatype is not None:
if qname_callback:
quoted_dt = qname_callback(datatype)
if not quoted_dt:
quoted_dt = "<%s>" % datatype
if datatype in _NUMERIC_INF_NAN_LITERAL_TYPES:
try:
v = float(self)
if math.isinf(v):
# py string reps: float: 'inf', Decimal: 'Infinity"
# both need to become "INF" in xsd datatypes
encoded = encoded.replace("inf", "INF").replace(
"Infinity", "INF"
)
if math.isnan(v):
encoded = encoded.replace("nan", "NaN")
except ValueError:
# if we can't cast to float something is wrong, but we can
# still serialize. Warn user about it
warnings.warn("Serializing weird numerical %r" % self)
language = self.language
if language:
return "%s@%s" % (encoded, language)
elif datatype:
return "%s^^%s" % (encoded, quoted_dt)
else:
return "%s" % encoded
def _quote_encode(self) -> str:
# This simpler encoding doesn't work; a newline gets encoded as "\\n",
# which is ok in sourcecode, but we want "\n".
# encoded = self.encode('unicode-escape').replace(
# '\\', '\\\\').replace('"','\\"')
# encoded = self.replace.replace('\\', '\\\\').replace('"','\\"')
# NOTE: Could in theory chose quotes based on quotes appearing in the
# string, i.e. '"' and "'", but N3/turtle doesn't allow "'"(?).
if "\n" in self:
# Triple quote this string.
encoded = self.replace("\\", "\\\\")
if '"""' in self:
# is this ok?
encoded = encoded.replace('"""', '\\"\\"\\"')
if encoded[-1] == '"' and encoded[-2] != "\\":
encoded = encoded[:-1] + "\\" + '"'
return '"""%s"""' % encoded.replace("\r", "\\r")
else:
return '"%s"' % self.replace("\n", "\\n").replace("\\", "\\\\").replace(
'"', '\\"'
).replace("\r", "\\r")
def __repr__(self) -> str:
args = [super(Literal, self).__repr__()]
if self.language is not None:
args.append("lang=%s" % repr(self.language))
if self.datatype is not None:
args.append("datatype=%s" % repr(self.datatype))
if self.__class__ == Literal:
clsName = "rdflib.term.Literal" # noqa: N806
else:
clsName = self.__class__.__name__ # noqa: N806
return """%s(%s)""" % (clsName, ", ".join(args))
def toPython(self) -> Any: # noqa: N802
"""
Returns an appropriate python datatype derived from this RDF Literal
"""
if self.value is not None:
return self.value
return self
def _parseXML(xmlstring: str) -> xml.dom.minidom.Document: # noqa: N802
retval = xml.dom.minidom.parseString(
"<rdflibtoplevelelement>%s</rdflibtoplevelelement>" % xmlstring
)
retval.normalize()
return retval
def _parseHTML(htmltext: str) -> xml.dom.minidom.DocumentFragment: # noqa: N802
try:
import html5lib
parser = html5lib.HTMLParser(tree=html5lib.treebuilders.getTreeBuilder("dom"))
retval = parser.parseFragment(htmltext)
retval.normalize()
return retval
except ImportError:
raise ImportError(
"HTML5 parser not available. Try installing"
+ " html5lib <http://code.google.com/p/html5lib>"
)
def _writeXML( # noqa: N802
xmlnode: Union[xml.dom.minidom.Document, xml.dom.minidom.DocumentFragment]
) -> bytes:
if isinstance(xmlnode, xml.dom.minidom.DocumentFragment):
d = xml.dom.minidom.Document()
d.childNodes += xmlnode.childNodes
xmlnode = d
s = xmlnode.toxml("utf-8")
# for clean round-tripping, remove headers -- I have great and
# specific worries that this will blow up later, but this margin
# is too narrow to contain them
if s.startswith('<?xml version="1.0" encoding="utf-8"?>'.encode("latin-1")):
s = s[38:]
if s.startswith("<rdflibtoplevelelement>".encode("latin-1")):
s = s[23:-24]
if s == "<rdflibtoplevelelement/>".encode("latin-1"):
s = "".encode("latin-1")
return s
def _unhexlify(value: Union[str, bytes, Literal]) -> bytes:
# In Python 3.2, unhexlify does not support str (only bytes)
if isinstance(value, str):
value = value.encode()
return unhexlify(value)
def _parseBoolean(value: Union[str, bytes]) -> bool: # noqa: N802
"""
Boolean is a datatype with value space {true,false},
lexical space {"true", "false","1","0"} and
lexical-to-value mapping {"true"→true, "false"→false, "1"→true, "0"→false}.
"""
true_accepted_values = ["1", "true", b"1", b"true"]
false_accepted_values = ["0", "false", b"0", b"false"]
new_value = value.lower()
if new_value in true_accepted_values:
return True
if new_value not in false_accepted_values:
warnings.warn(
"Parsing weird boolean, % r does not map to True or False" % value,
category=UserWarning,
)
return False
def _well_formed_by_value(lexical: Union[str, bytes], value: Any) -> bool:
"""
This function is used as the fallback for detecting ill-typed/ill-formed
literals and operates on the asumption that if a value (i.e.
`Literal.value`) could be determined for a Literal then it is not
ill-typed/ill-formed.
This function will be called with `Literal.lexical` and `Literal.value` as arguments.
"""
return value is not None
def _well_formed_unsignedlong(lexical: Union[str, bytes], value: Any) -> bool:
"""
xsd:unsignedInteger and xsd:unsignedLong must not be negative
"""
return len(lexical) > 0 and isinstance(value, long_type) and value >= 0
def _well_formed_boolean(lexical: Union[str, bytes], value: Any) -> bool:
"""
Boolean is a datatype with value space {true,false},
lexical space {"true", "false","1","0"} and
lexical-to-value mapping {"true"→true, "false"→false, "1"→true, "0"→false}.
"""
return lexical in ("true", b"true", "false", b"false", "1", b"1", "0", b"0")
def _well_formed_int(lexical: Union[str, bytes], value: Any) -> bool:
"""
The value space of xs:int is the set of common single size integers (32 bits),
i.e., the integers between -2147483648 and 2147483647,
its lexical space allows any number of insignificant leading zeros.
"""
return (
len(lexical) > 0
and isinstance(value, int)
and (-2147483648 <= value <= 2147483647)
)
def _well_formed_unsignedint(lexical: Union[str, bytes], value: Any) -> bool:
"""
xsd:unsignedInt has a 32bit value of between 0 and 4294967295
"""
return len(lexical) > 0 and isinstance(value, int) and (0 <= value <= 4294967295)
def _well_formed_short(lexical: Union[str, bytes], value: Any) -> bool:
"""
The value space of xs:short is the set of common short integers (16 bits),
i.e., the integers between -32768 and 32767,
its lexical space allows any number of insignificant leading zeros.
"""
return len(lexical) > 0 and isinstance(value, int) and (-32768 <= value <= 32767)
def _well_formed_unsignedshort(lexical: Union[str, bytes], value: Any) -> bool:
"""
xsd:unsignedShort has a 16bit value of between 0 and 65535
"""
return len(lexical) > 0 and isinstance(value, int) and (0 <= value <= 65535)
def _well_formed_byte(lexical: Union[str, bytes], value: Any) -> bool:
"""
The value space of xs:byte is the set of common single byte integers (8 bits),
i.e., the integers between -128 and 127,
its lexical space allows any number of insignificant leading zeros.
"""
return len(lexical) > 0 and isinstance(value, int) and (-128 <= value <= 127)
def _well_formed_unsignedbyte(lexical: Union[str, bytes], value: Any) -> bool:
"""
xsd:unsignedByte has a 8bit value of between 0 and 255
"""
return len(lexical) > 0 and isinstance(value, int) and (0 <= value <= 255)
def _well_formed_non_negative_integer(lexical: Union[str, bytes], value: Any) -> bool:
return isinstance(value, int) and value >= 0
def _well_formed_positive_integer(lexical: Union[str, bytes], value: Any) -> bool:
return isinstance(value, int) and value > 0
def _well_formed_non_positive_integer(lexical: Union[str, bytes], value: Any) -> bool:
return isinstance(value, int) and value <= 0
def _well_formed_negative_integer(lexical: Union[str, bytes], value: Any) -> bool:
return isinstance(value, int) and value < 0
# Cannot import Namespace/XSD because of circular dependencies
_XSD_PFX = "http://www.w3.org/2001/XMLSchema#"
_RDF_PFX = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
_RDF_XMLLITERAL = URIRef(_RDF_PFX + "XMLLiteral")
_RDF_HTMLLITERAL = URIRef(_RDF_PFX + "HTML")
_XSD_STRING = URIRef(_XSD_PFX + "string")
_XSD_NORMALISED_STRING = URIRef(_XSD_PFX + "normalizedString")
_XSD_TOKEN = URIRef(_XSD_PFX + "token")
_XSD_FLOAT = URIRef(_XSD_PFX + "float")
_XSD_DOUBLE = URIRef(_XSD_PFX + "double")
_XSD_DECIMAL = URIRef(_XSD_PFX + "decimal")
_XSD_INTEGER = URIRef(_XSD_PFX + "integer")
_XSD_BOOLEAN = URIRef(_XSD_PFX + "boolean")
_XSD_DATETIME = URIRef(_XSD_PFX + "dateTime")
_XSD_DATE = URIRef(_XSD_PFX + "date")
_XSD_TIME = URIRef(_XSD_PFX + "time")
_XSD_DURATION = URIRef(_XSD_PFX + "duration")
_XSD_DAYTIMEDURATION = URIRef(_XSD_PFX + "dayTimeDuration")
_XSD_YEARMONTHDURATION = URIRef(_XSD_PFX + "yearMonthDuration")
_OWL_RATIONAL = URIRef("http://www.w3.org/2002/07/owl#rational")
_XSD_B64BINARY = URIRef(_XSD_PFX + "base64Binary")
_XSD_HEXBINARY = URIRef(_XSD_PFX + "hexBinary")
_XSD_GYEAR = URIRef(_XSD_PFX + "gYear")
_XSD_GYEARMONTH = URIRef(_XSD_PFX + "gYearMonth")
# TODO: gMonthDay, gDay, gMonth
_NUMERIC_LITERAL_TYPES: Tuple[URIRef, ...] = (
_XSD_INTEGER,
_XSD_DECIMAL,
_XSD_DOUBLE,
URIRef(_XSD_PFX + "float"),
URIRef(_XSD_PFX + "byte"),
URIRef(_XSD_PFX + "int"),
URIRef(_XSD_PFX + "long"),
URIRef(_XSD_PFX + "negativeInteger"),
URIRef(_XSD_PFX + "nonNegativeInteger"),
URIRef(_XSD_PFX + "nonPositiveInteger"),
URIRef(_XSD_PFX + "positiveInteger"),
URIRef(_XSD_PFX + "short"),
URIRef(_XSD_PFX + "unsignedByte"),
URIRef(_XSD_PFX + "unsignedInt"),
URIRef(_XSD_PFX + "unsignedLong"),
URIRef(_XSD_PFX + "unsignedShort"),
)
# these have "native" syntax in N3/SPARQL
_PLAIN_LITERAL_TYPES: Tuple[URIRef, ...] = (
_XSD_INTEGER,
_XSD_BOOLEAN,
_XSD_DOUBLE,
_XSD_DECIMAL,
_OWL_RATIONAL,
)
# these have special INF and NaN XSD representations
_NUMERIC_INF_NAN_LITERAL_TYPES: Tuple[URIRef, ...] = (
URIRef(_XSD_PFX + "float"),
_XSD_DOUBLE,
_XSD_DECIMAL,
)
# these need dedicated operators
_DATE_AND_TIME_TYPES: Tuple[URIRef, ...] = (
_XSD_DATETIME,
_XSD_DATE,
_XSD_TIME,
)
# These are recognized datatype IRIs
# (https://www.w3.org/TR/rdf11-concepts/#dfn-recognized-datatype-iris) that
# represents durations.
_TIME_DELTA_TYPES: Tuple[URIRef, ...] = (
_XSD_DURATION,
_XSD_DAYTIMEDURATION,
)
_ALL_DATE_AND_TIME_TYPES: Tuple[URIRef, ...] = _DATE_AND_TIME_TYPES + _TIME_DELTA_TYPES
# the following types need special treatment for reasonable sorting because
# certain instances can't be compared to each other. We treat this by
# partitioning and then sorting within those partitions.
_TOTAL_ORDER_CASTERS: Dict[Type[Any], Callable[[Any], Any]] = {
datetime: lambda value: (
# naive vs. aware
value.tzinfo is not None and value.tzinfo.utcoffset(value) is not None,
value,
),
time: lambda value: (
# naive vs. aware
value.tzinfo is not None and value.tzinfo.utcoffset(None) is not None,
value,
),
xml.dom.minidom.Document: lambda value: value.toxml(),
}
_STRING_LITERAL_TYPES: Tuple[URIRef, ...] = (
_XSD_STRING,
_RDF_XMLLITERAL,
_RDF_HTMLLITERAL,
URIRef(_XSD_PFX + "normalizedString"),
URIRef(_XSD_PFX + "token"),
)
_StrT = TypeVar("_StrT", bound=str)
def _py2literal(
obj: Any,
pType: Any, # noqa: N803
castFunc: Optional[Callable[[Any], Any]],
dType: Optional[_StrT],
) -> Tuple[Any, Optional[_StrT]]:
if castFunc is not None:
return castFunc(obj), dType
elif dType is not None:
return obj, dType
else:
return obj, None
def _castPythonToLiteral( # noqa: N802
obj: Any, datatype: Optional[str]
) -> Tuple[Any, Optional[str]]:
"""
Casts a tuple of a python type and a special datatype URI to a tuple of the lexical value and a
datatype URI (or None)
"""
castFunc: Optional[Callable[[Any], Union[str, bytes]]] # noqa: N806
dType: Optional[str] # noqa: N806
for (pType, dType), castFunc in _SpecificPythonToXSDRules: # noqa: N806
if isinstance(obj, pType) and dType == datatype:
return _py2literal(obj, pType, castFunc, dType)
for pType, (castFunc, dType) in _GenericPythonToXSDRules: # noqa: N806
if isinstance(obj, pType):
return _py2literal(obj, pType, castFunc, dType)
return obj, None # TODO: is this right for the fall through case?
# Mappings from Python types to XSD datatypes and back (borrowed from sparta)
# datetime instances are also instances of date... so we need to order these.
# SPARQL/Turtle/N3 has shortcuts for integer, double, decimal
# python has only float - to be in tune with sparql/n3/turtle
# we default to XSD.double for float literals
# python ints are promoted to longs when overflowing
# python longs have no limit
# both map to the abstract integer type,
# rather than some concrete bit-limited datatype
_GenericPythonToXSDRules: List[
Tuple[Type[Any], Tuple[Optional[Callable[[Any], Union[str, bytes]]], Optional[str]]]
] = [
(str, (None, None)),
(float, (None, _XSD_DOUBLE)),
(bool, (lambda i: str(i).lower(), _XSD_BOOLEAN)),
(int, (None, _XSD_INTEGER)),
(long_type, (None, _XSD_INTEGER)),
(Decimal, (lambda i: f"{i:f}", _XSD_DECIMAL)),
(datetime, (lambda i: i.isoformat(), _XSD_DATETIME)),
(date, (lambda i: i.isoformat(), _XSD_DATE)),
(time, (lambda i: i.isoformat(), _XSD_TIME)),
(Duration, (lambda i: duration_isoformat(i), _XSD_DURATION)),
(timedelta, (lambda i: duration_isoformat(i), _XSD_DAYTIMEDURATION)),
(xml.dom.minidom.Document, (_writeXML, _RDF_XMLLITERAL)),
# this is a bit dirty - by accident the html5lib parser produces
# DocumentFragments, and the xml parser Documents, letting this
# decide what datatype to use makes roundtripping easier, but it a
# bit random
(xml.dom.minidom.DocumentFragment, (_writeXML, _RDF_HTMLLITERAL)),
(Fraction, (None, _OWL_RATIONAL)),
]
_OriginalGenericPythonToXSDRules = list(_GenericPythonToXSDRules)
_SpecificPythonToXSDRules: List[
Tuple[Tuple[Type[Any], str], Optional[Callable[[Any], Union[str, bytes]]]]
] = [
((date, _XSD_GYEAR), lambda val: val.strftime("%Y").zfill(4)),
((date, _XSD_GYEARMONTH), lambda val: val.strftime("%Y-%m").zfill(7)),
((str, _XSD_HEXBINARY), hexlify),
((bytes, _XSD_HEXBINARY), hexlify),
((str, _XSD_B64BINARY), b64encode),
((bytes, _XSD_B64BINARY), b64encode),
]
_OriginalSpecificPythonToXSDRules = list(_SpecificPythonToXSDRules)
XSDToPython: Dict[Optional[str], Optional[Callable[[str], Any]]] = {
None: None, # plain literals map directly to value space
URIRef(_XSD_PFX + "time"): parse_time,
URIRef(_XSD_PFX + "date"): parse_date,
URIRef(_XSD_PFX + "gYear"): parse_date,
URIRef(_XSD_PFX + "gYearMonth"): parse_date,
URIRef(_XSD_PFX + "dateTime"): parse_datetime,
URIRef(_XSD_PFX + "duration"): parse_duration,
URIRef(_XSD_PFX + "dayTimeDuration"): parse_duration,
URIRef(_XSD_PFX + "yearMonthDuration"): parse_duration,
URIRef(_XSD_PFX + "hexBinary"): _unhexlify,
URIRef(_XSD_PFX + "string"): None,
URIRef(_XSD_PFX + "normalizedString"): None,
URIRef(_XSD_PFX + "token"): None,
URIRef(_XSD_PFX + "language"): None,
URIRef(_XSD_PFX + "boolean"): _parseBoolean,
URIRef(_XSD_PFX + "decimal"): Decimal,
URIRef(_XSD_PFX + "integer"): long_type,
URIRef(_XSD_PFX + "nonPositiveInteger"): long_type,
URIRef(_XSD_PFX + "long"): long_type,
URIRef(_XSD_PFX + "nonNegativeInteger"): long_type,
URIRef(_XSD_PFX + "negativeInteger"): long_type,
URIRef(_XSD_PFX + "int"): int,
URIRef(_XSD_PFX + "unsignedLong"): long_type,
URIRef(_XSD_PFX + "positiveInteger"): long_type,
URIRef(_XSD_PFX + "short"): int,
URIRef(_XSD_PFX + "unsignedInt"): int,
URIRef(_XSD_PFX + "byte"): int,
URIRef(_XSD_PFX + "unsignedShort"): int,
URIRef(_XSD_PFX + "unsignedByte"): int,
URIRef(_XSD_PFX + "float"): float,
URIRef(_XSD_PFX + "double"): float,
URIRef(_XSD_PFX + "base64Binary"): b64decode,
URIRef(_XSD_PFX + "anyURI"): None,
_RDF_XMLLITERAL: _parseXML,
_RDF_HTMLLITERAL: _parseHTML,
}
_check_well_formed_types: Dict[URIRef, Callable[[Union[str, bytes], Any], bool]] = {
URIRef(_XSD_PFX + "boolean"): _well_formed_boolean,
URIRef(_XSD_PFX + "nonPositiveInteger"): _well_formed_non_positive_integer,
URIRef(_XSD_PFX + "nonNegativeInteger"): _well_formed_non_negative_integer,
URIRef(_XSD_PFX + "negativeInteger"): _well_formed_negative_integer,
URIRef(_XSD_PFX + "positiveInteger"): _well_formed_positive_integer,
URIRef(_XSD_PFX + "int"): _well_formed_int,
URIRef(_XSD_PFX + "short"): _well_formed_short,
URIRef(_XSD_PFX + "byte"): _well_formed_byte,
URIRef(_XSD_PFX + "unsignedInt"): _well_formed_unsignedint,
URIRef(_XSD_PFX + "unsignedLong"): _well_formed_unsignedlong,
URIRef(_XSD_PFX + "unsignedShort"): _well_formed_unsignedshort,
URIRef(_XSD_PFX + "unsignedByte"): _well_formed_unsignedbyte,
}
_toPythonMapping: Dict[Optional[str], Optional[Callable[[str], Any]]] = {} # noqa: N816
_toPythonMapping.update(XSDToPython)
def _reset_bindings() -> None:
"""
Reset lexical<->value space binding for `Literal`
"""
_toPythonMapping.clear()
_toPythonMapping.update(XSDToPython)
_GenericPythonToXSDRules.clear()
_GenericPythonToXSDRules.extend(_OriginalGenericPythonToXSDRules)
_SpecificPythonToXSDRules.clear()
_SpecificPythonToXSDRules.extend(_OriginalSpecificPythonToXSDRules)
def _castLexicalToPython( # noqa: N802
lexical: Union[str, bytes], datatype: Optional[URIRef]
) -> Any:
"""
Map a lexical form to the value-space for the given datatype
:returns: a python object for the value or ``None``
"""
try:
conv_func = _toPythonMapping[datatype]
except KeyError:
# no conv_func -> unknown data-type
return None
if conv_func is not None:
try:
# type error: Argument 1 has incompatible type "Union[str, bytes]"; expected "str"
# NOTE for type ignore: various functions in _toPythonMapping will
# only work for str, so there is some inconsistency here, the right
# approach may be to change lexical to be of str type but this will
# require runtime changes.
return conv_func(lexical) # type: ignore[arg-type]
except Exception:
logger.warning(
"Failed to convert Literal lexical form to value. Datatype=%s, "
"Converter=%s",
datatype,
conv_func,
exc_info=True,
)
# not a valid lexical representation for this dt
return None
else:
# no conv func means 1-1 lexical<->value-space mapping
try:
return str(lexical)
except UnicodeDecodeError:
# type error: Argument 1 to "str" has incompatible type "Union[str, bytes]"; expected "bytes"
# NOTE for type ignore: code assumes that lexical is of type bytes
# at this point.
return str(lexical, "utf-8") # type: ignore[arg-type]
_AnyT = TypeVar("_AnyT", bound=Any)
def _normalise_XSD_STRING(lexical_or_value: _AnyT) -> _AnyT: # noqa: N802
"""
Replaces \t, \n, \r (#x9 (tab), #xA (linefeed), and #xD (carriage return)) with space without any whitespace collapsing
"""
if isinstance(lexical_or_value, str):
# type error: Incompatible return value type (got "str", expected "_AnyT") [return-value]
# NOTE for type ignore: this is an issue with mypy: https://github.com/python/mypy/issues/10003
return lexical_or_value.replace("\t", " ").replace("\n", " ").replace("\r", " ") # type: ignore[return-value]
return lexical_or_value
def _strip_and_collapse_whitespace(lexical_or_value: _AnyT) -> _AnyT:
if isinstance(lexical_or_value, str):
# Use regex to substitute contiguous whitespace into a single whitespace. Strip trailing whitespace.
# type error: Incompatible return value type (got "str", expected "_AnyT") [return-value]
# NOTE for type ignore: this is an issue with mypy: https://github.com/python/mypy/issues/10003
return re.sub(" +", " ", lexical_or_value.strip()) # type: ignore[return-value]
return lexical_or_value
def bind(
datatype: str,
pythontype: Type[Any],
constructor: Optional[Callable[[str], Any]] = None,
lexicalizer: Optional[Callable[[Any], Union[str, bytes]]] = None,
datatype_specific: bool = False,
) -> None:
"""
register a new datatype<->pythontype binding
:param constructor: an optional function for converting lexical forms
into a Python instances, if not given the pythontype
is used directly
:param lexicalizer: an optional function for converting python objects to
lexical form, if not given object.__str__ is used
:param datatype_specific: makes the lexicalizer function be accessible
from the pair (pythontype, datatype) if set to True
or from the pythontype otherwise. False by default
"""
if datatype_specific and datatype is None:
raise Exception("No datatype given for a datatype-specific binding")
if datatype in _toPythonMapping:
logger.warning("datatype '%s' was already bound. Rebinding." % datatype)
if constructor is None:
constructor = pythontype
_toPythonMapping[datatype] = constructor
if datatype_specific:
_SpecificPythonToXSDRules.append(((pythontype, datatype), lexicalizer))
else:
_GenericPythonToXSDRules.append((pythontype, (lexicalizer, datatype)))
class Variable(Identifier):
"""
A Variable - this is used for querying, or in Formula aware
graphs, where Variables can be stored
"""
__slots__ = ()
def __new__(cls, value: str) -> "Variable":
if len(value) == 0:
raise Exception("Attempted to create variable with empty string as name!")
if value[0] == "?":
value = value[1:]
return str.__new__(cls, value)
def __repr__(self) -> str:
if self.__class__ is Variable:
clsName = "rdflib.term.Variable" # noqa: N806
else:
clsName = self.__class__.__name__ # noqa: N806
return """%s(%s)""" % (clsName, super(Variable, self).__repr__())
def toPython(self) -> str: # noqa: N802
return "?%s" % self
def n3(self, namespace_manager: Optional["NamespaceManager"] = None) -> str:
return "?%s" % self
def __reduce__(self) -> Tuple[Type["Variable"], Tuple[str]]:
return (Variable, (str(self),))
# Nodes are ordered like this
# See http://www.w3.org/TR/sparql11-query/#modOrderBy
# we leave "space" for more subclasses of Node elsewhere
# default-dict to grazefully fail for new subclasses
_ORDERING: Dict[Type[Node], int] = defaultdict(int)
_ORDERING.update({BNode: 10, Variable: 20, URIRef: 30, Literal: 40})
def _isEqualXMLNode( # noqa: N802
node: Union[
None,
xml.dom.minidom.Attr,
xml.dom.minidom.Comment,
xml.dom.minidom.Document,
xml.dom.minidom.DocumentFragment,
xml.dom.minidom.DocumentType,
xml.dom.minidom.Element,
xml.dom.minidom.Entity,
xml.dom.minidom.Notation,
xml.dom.minidom.ProcessingInstruction,
xml.dom.minidom.Text,
],
other: Union[
None,
xml.dom.minidom.Attr,
xml.dom.minidom.Comment,
xml.dom.minidom.Document,
xml.dom.minidom.DocumentFragment,
xml.dom.minidom.DocumentType,
xml.dom.minidom.Element,
xml.dom.minidom.Entity,
xml.dom.minidom.Notation,
xml.dom.minidom.ProcessingInstruction,
xml.dom.minidom.Text,
],
) -> bool:
# importing xml.dom.minidom.Node as XMLNode to avoid confusion with
# rdflib.term.Node
from xml.dom.minidom import Node as XMLNode
def recurse():
# Recursion through the children
# In Python2, the semantics of 'map' is such that the check on
# length would be unnecessary. In Python 3,
# the semantics of map has changed (why, oh why???) and the check
# for the length becomes necessary...
if len(node.childNodes) != len(other.childNodes):
return False
for nc, oc in map(lambda x, y: (x, y), node.childNodes, other.childNodes):
if not _isEqualXMLNode(nc, oc):
return False
# if we got here then everything is fine:
return True
if node is None or other is None:
return False
if node.nodeType != other.nodeType:
return False
if node.nodeType in [XMLNode.DOCUMENT_NODE, XMLNode.DOCUMENT_FRAGMENT_NODE]:
return recurse()
elif node.nodeType == XMLNode.ELEMENT_NODE:
if TYPE_CHECKING:
assert isinstance(node, xml.dom.minidom.Element)
assert isinstance(other, xml.dom.minidom.Element)
# Get the basics right
if not (
node.tagName == other.tagName and node.namespaceURI == other.namespaceURI
):
return False
# Handle the (namespaced) attributes; the namespace setting key
# should be ignored, though
# Note that the minidom orders the keys already, so we do not have
# to worry about that, which is a bonus...
n_keys = [
k
for k in node.attributes.keysNS()
if k[0] != "http://www.w3.org/2000/xmlns/"
]
o_keys = [
k
for k in other.attributes.keysNS()
if k[0] != "http://www.w3.org/2000/xmlns/"
]
if len(n_keys) != len(o_keys):
return False
for k in n_keys:
if not (
k in o_keys
and node.getAttributeNS(k[0], k[1]) == other.getAttributeNS(k[0], k[1])
):
return False
# if we got here, the attributes are all right, we can go down
# the tree recursively
return recurse()
elif node.nodeType in [
XMLNode.TEXT_NODE,
XMLNode.COMMENT_NODE,
XMLNode.CDATA_SECTION_NODE,
XMLNode.NOTATION_NODE,
]:
if TYPE_CHECKING:
assert isinstance(
node,
(
xml.dom.minidom.Text,
xml.dom.minidom.Comment,
xml.dom.minidom.CDATASection,
xml.dom.minidom.Notation,
),
)
assert isinstance(
other,
(
xml.dom.minidom.Text,
xml.dom.minidom.Comment,
xml.dom.minidom.CDATASection,
xml.dom.minidom.Notation,
),
)
# type error: Item "Notation" of "Union[Comment, Document, Notation, Text]" has no attribute "data"
return node.data == other.data # type: ignore[union-attr] # FIXME
elif node.nodeType == XMLNode.PROCESSING_INSTRUCTION_NODE:
if TYPE_CHECKING:
assert isinstance(node, xml.dom.minidom.ProcessingInstruction)
assert isinstance(other, xml.dom.minidom.ProcessingInstruction)
return node.data == other.data and node.target == other.target
elif node.nodeType == XMLNode.ENTITY_NODE:
return node.nodeValue == other.nodeValue
elif node.nodeType == XMLNode.DOCUMENT_TYPE_NODE:
if TYPE_CHECKING:
assert isinstance(node, xml.dom.minidom.DocumentType)
assert isinstance(other, xml.dom.minidom.DocumentType)
return node.publicId == other.publicId and node.systemId == other.systemId
else:
# should not happen, in fact
raise Exception("I dont know how to compare XML Node type: %s" % node.nodeType)
|