/
term.py
2308 lines (1902 loc) · 82.5 KB
/
term.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
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
"""
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
from rdflib.compat import long_type
if TYPE_CHECKING:
from .namespace import NamespaceManager
from .paths import AlternativePath, InvPath, NegatedPath, Path, SequencePath
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(object):
"""
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
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 = "http://rdlib.net/"
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[str]
_ill_formed: Optional[bool]
__slots__ = ("_language", "_datatype", "_value", "_ill_formed")
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:
datatype = URIRef(datatype)
value = None
ill_formed: Optional[bool] = None
if isinstance(lexical_or_value, Literal):
# create from another Literal instance
lang = lang or lexical_or_value.language
if datatype:
# 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 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_formed = ill_formed 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 = datatype or _datatype
if _value is not None:
lexical_or_value = _value
if datatype:
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_formed = ill_formed
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_formed(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_formed
@property
def value(self) -> Any:
return self._value
@property
def language(self) -> Optional[str]:
return self._language
@property
def datatype(self) -> Optional[str]:
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, str]]) -> 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'))