-
Notifications
You must be signed in to change notification settings - Fork 543
/
term.py
1853 lines (1493 loc) · 60 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",
"Node",
"Identifier",
"URIRef",
"BNode",
"Literal",
"Variable",
"Statement",
]
import logging
import warnings
import math
import xml.dom.minidom
from datetime import date, time, datetime, timedelta
from re import sub, compile
from collections import defaultdict
from isodate import (
parse_time,
parse_date,
parse_datetime,
Duration,
parse_duration,
duration_isoformat,
)
from base64 import b64decode, b64encode
from binascii import hexlify, unhexlify
import rdflib
from rdflib.compat import long_type
from urllib.parse import urldefrag
from urllib.parse import urljoin
from urllib.parse import urlparse
from decimal import Decimal
from typing import TYPE_CHECKING, Dict, Callable, Optional, Union, Type
if TYPE_CHECKING:
from .paths import AlternativePath, InvPath, NegatedPath, SequencePath, Path
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):
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):
return bool(_lang_tag_regex.match(tag))
def _is_valid_unicode(value):
"""
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):
return str.__new__(cls, value)
def eq(self, other):
"""A "semantic"/interpreted equality function,
by default, same as __eq__"""
return self.__eq__(other)
def neq(self, other):
"""A "semantic"/interpreted not equal function,
by default, same as __ne__"""
return self.__ne__(other)
def __ne__(self, other):
return not self.__eq__(other)
def __eq__(self, other):
"""
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):
"""
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):
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):
r = self.__lt__(other)
if r:
return True
return self == other
def __ge__(self, other):
r = self.__gt__(other)
if r:
return True
return self == other
def startswith(self, prefix, start=..., end=...) -> bool:
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 URIRef(Identifier):
"""
RDF URI Reference: http://www.w3.org/TR/rdf-concepts/#section-Graph-URIref
"""
__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):
if base is not None:
ends_in_hash = value.endswith("#")
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:
rt = str.__new__(cls, value, "utf-8") # type: ignore[call-overload]
return rt
def toPython(self):
return str(self)
def n3(self, namespace_manager=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):
if "#" in self:
url, frag = urldefrag(self)
return URIRef(url)
else:
return self
def __reduce__(self):
return (URIRef, (str(self),))
def __getnewargs__(self):
return (str(self),)
def __repr__(self):
if self.__class__ is URIRef:
clsName = "rdflib.term.URIRef"
else:
clsName = self.__class__.__name__
return """%s(%s)""" % (clsName, super(URIRef, self).__repr__())
def __add__(self, other):
return self.__class__(str(self) + other)
def __radd__(self, other):
return self.__class__(other + str(self))
def __mod__(self, other):
return self.__class__(str(self) % other)
def de_skolemize(self):
"""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):
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):
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():
# 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():
"""
Generates UUID4-based but ncname-compliant identifiers.
"""
from uuid import uuid4
def _generator():
return uuid4().hex
return _generator
class BNode(Identifier):
"""
Blank Node: http://www.w3.org/TR/rdf-concepts/#section-blank-nodes
"""
__slots__ = ()
def __new__(
cls, value=None, _sn_gen=_serial_number_generator(), _prefix=_unique_id()
):
"""
# 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
return Identifier.__new__(cls, value)
def toPython(self):
return str(self)
def n3(self, namespace_manager=None):
return "_:%s" % self
def __getnewargs__(self):
return (str(self),)
def __reduce__(self):
return (BNode, (str(self),))
def __repr__(self):
if self.__class__ is BNode:
clsName = "rdflib.term.BNode"
else:
clsName = self.__class__.__name__
return """%s('%s')""" % (clsName, str(self))
def skolemize(self, authority=None, basepath=None):
"""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 Literal: http://www.w3.org/TR/rdf-concepts/#section-Graph-Literal
The lexical value of the literal is the unicode object.
The interpreted, datatyped value is available from .value
Language tags must be valid according to :rfc:5646
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
"""
__slots__ = ("_language", "_datatype", "_value")
def __new__(cls, lexical_or_value, lang=None, datatype=None, normalize=None):
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 and not _is_valid_langtag(lang):
raise Exception("'%s' is not a valid language tag!" % lang)
if datatype:
datatype = URIRef(datatype)
value = 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 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 = 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
return inst
def normalize(self):
"""
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 value(self):
return self._value
@property
def language(self):
return self._language
@property
def datatype(self):
return self._datatype
def __reduce__(self):
return (
Literal,
(str(self), self.language, self.datatype),
)
def __getstate__(self):
return (None, dict(language=self.language, datatype=self.datatype))
def __setstate__(self, arg):
_, d = arg
self._language = d["language"]
self._datatype = d["datatype"]
def __add__(self, val):
"""
>>> 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')
"""
# 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 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 __bool__(self):
"""
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(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(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):
"""
>>> 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(-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)):
return Literal(self.value.__invert__())
else:
raise TypeError("Not a number; %s" % repr(self))
def __gt__(self, other):
"""
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 = self.datatype or _XSD_STRING
dtother = other.datatype or _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 not self.datatype:
return False
elif not other.datatype:
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):
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):
"""
>>> 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):
r = self.__gt__(other)
if r:
return True
try:
return self.eq(other)
except TypeError:
return NotImplemented
def _comparable_to(self, other):
"""
Helper method to decide which things are meaningful to
rich-compare with this literal
"""
if isinstance(other, Literal):
if self.datatype and other.datatype:
# 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
def __hash__(self):
"""
>>> 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:
res ^= hash(self._datatype)
return res
def __eq__(self, other):
"""