summaryrefslogtreecommitdiff
path: root/rdflib/term.py
blob: 35fcf839f581dc3de87a0bb2597112c95bda58b1 (plain)
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
"""
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:

* Blank Nodes
* URI References
* Literals (which consist of a literal value,datatype and language tag)

Those that extend the RDF model into N3:

* Formulae
* Universal Quantifications (Variables)

And those that are primarily for matching against 'Nodes' in the
underlying Graph:

* REGEX Expressions
* Date Ranges
* Numerical Ranges

"""

__all__ = [
    'bind',

    'Node',
    'Identifier',

    'URIRef',
    'BNode',
    'Literal',

    'Variable',
    'Statement',
]

import logging
import warnings

_LOGGER = logging.getLogger(__name__)

import base64

from urlparse import urlparse, urljoin, urldefrag
from datetime import date, time, datetime
from isodate import parse_time, parse_date, parse_datetime
from re import sub


try:
    from hashlib import md5
    assert md5
except ImportError:
    from md5 import md5


from rdflib import NORMALIZE_LITERALS
from . import py3compat

b = py3compat.b


class Node(object):
    """
    A Node in the Graph.
    """

    __slots__ = ()


class Identifier(Node, unicode):  # 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 unicode.__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)


class URIRef(Identifier):
    """
    RDF URI Reference: http://www.w3.org/TR/rdf-concepts/#section-Graph-URIref
    """

    __slots__ = ()

    def __new__(cls, value, base=None):
        if base is not None:
            ends_in_hash = value.endswith("#")
            value = urljoin(base, value, allow_fragments=1)
            if ends_in_hash:
                if not value.endswith("#"):
                    value += "#"
        # if normalize and value and value != normalize("NFC", value):
        #    raise Error("value must be in NFC normalized form.")
        try:
            rt = unicode.__new__(cls, value)
        except UnicodeDecodeError:
            rt = unicode.__new__(cls, value, 'utf-8')
        return rt

    def toPython(self):
        return unicode(self)

    def n3(self):
        return "<%s>" % self

    def concrete(self):
        warnings.warn("URIRef.concrete is deprecated.",
                      category=DeprecationWarning, stacklevel=2)
        if "#" in self:
            return URIRef("/".join(self.rsplit("#", 1)))
        else:
            return self

    def abstract(self):
        warnings.warn("URIRef.abstract is deprecated.",
                      category=DeprecationWarning, stacklevel=2)
        if "#" not in self:
            scheme, netloc, path, params, query, fragment = urlparse(self)
            if path:
                return URIRef("#".join(self.rsplit("/", 1)))
            else:
                if not self.endswith("#"):
                    return URIRef("%s#" % self)
                else:
                    return self
        else:
            return self

    def defrag(self):
        if "#" in self:
            url, frag = urldefrag(self)
            return URIRef(url)
        else:
            return self

    def __reduce__(self):
        return (URIRef, (unicode(self),))

    def __getnewargs__(self):
        return (unicode(self), )

    def __ne__(self, other):
        return not self.__eq__(other)

    def __eq__(self, other):
        if isinstance(other, URIRef):
            return unicode(self) == unicode(other)
        else:
            return False

    def __hash__(self):
        return hash(URIRef) ^ hash(unicode(self))

    if not py3compat.PY3:
        def __str__(self):
            return self.encode()

    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 md5_term_hash(self):
        """a string of hex that will be the same for two URIRefs that
        are the same. It is not a suitable unique id.

        Supported for backwards compatibility; new code should
        probably just use __hash__
        """
        d = md5(self.encode())
        d.update(b("U"))
        return d.hexdigest()


def _unique_id():
    # Used to read: """Create a (hopefully) unique prefix"""
    # now retained merely to leave interal 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


# Adapted from http://icodesnip.com/snippet/python/
# simple-universally-unique-id-uuid-or-guid
def bnode_uuid():
    """
    Generates a uuid on behalf of Python 2.4
    """
    import os
    import random
    import socket
    from time import time
    from binascii import hexlify

    pid = [None]

    try:
        ip = socket.gethostbyname(socket.gethostname())
        ip = long(ip.replace('.', '999').replace(':', '999'))
    except:
        # if we can't get a network address, just imagine one
        ip = long(random.random() * 100000000000000000L)

    def _generator():
        if os.getpid() != pid[0]:
            # Process might have been forked (issue 200), must reseed random:
            try:
                preseed = long(hexlify(os.urandom(16)), 16)
            except NotImplementedError:
                preseed = 0
            seed = long(str(preseed) + str(os.getpid())
                        + str(long(time() * 1000000)) + str(ip))
            random.seed(seed)
            pid[0] = os.getpid()

        t = long(time() * 1000.0)
        r = long(random.random() * 100000000000000000L)
        data = str(t) + ' ' + str(r) + ' ' + str(ip)
        return md5(data).hexdigest()

    return _generator


def uuid4_ncname():
    """
    Generates UUID4-based but ncname-compliant identifiers.
    """
    from uuid import uuid4

    def _generator():
        return uuid4().hex

    return _generator


def _serial_number_generator():
    import sys
    if sys.version_info[:2] < (2, 5):
        return bnode_uuid()
    else:
        return uuid4_ncname()


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(unicode(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 unicode(self)

    def n3(self):
        return "_:%s" % self

    def __getnewargs__(self):
        return (unicode(self), )

    def __reduce__(self):
        return (BNode, (unicode(self),))

    def __ne__(self, other):
        return not self.__eq__(other)

    def __eq__(self, other):
        """
        >>> BNode("foo")==None
        False
        >>> BNode("foo")==URIRef("foo")
        False
        >>> URIRef("foo")==BNode("foo")
        False
        >>> BNode("foo")!=URIRef("foo")
        True
        >>> URIRef("foo")!=BNode("foo")
        True
        """
        if isinstance(other, BNode):
            return unicode(self) == unicode(other)
        else:
            return False

    def __hash__(self):
        return hash(BNode) ^ hash(unicode(self))

    if not py3compat.PY3:
        def __str__(self):
            return self.encode()

    def __repr__(self):
        if self.__class__ is BNode:
            clsName = "rdflib.term.BNode"
        else:
            clsName = self.__class__.__name__
        return """%s('%s')""" % (clsName, str(self))

    def md5_term_hash(self):
        """a string of hex that will be the same for two BNodes that
        are the same. It is not a suitable unique id.

        Supported for backwards compatibility; new code should
        probably just use __hash__
        """
        d = md5(self.encode())
        d.update(b("B"))
        return d.hexdigest()


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

    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

    GT/LT Comparisons are done by language, then by datatype, and finally 
    by lexical representations. Comparisons with non-literals is done by type

    >>> from rdflib import Literal, XSD
    >>> Literal(1).toPython()
    1
    >>> Literal("adsf") > 1
    True
    >>> 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)s'http://www.w3.org/2001/XMLSchema#dateTime')
    >>> oneInt     = Literal(1)
    >>> twoInt     = Literal(2)
    >>> twoInt < oneInt
    False
    >>> Literal('1') < Literal(1)
    True
    >>> Literal('1') < Literal('1')
    False
    >>> Literal(1) < Literal('1')
    False
    >>> Literal(1) > Literal('1')
    True
    >>> Literal(1) > Literal(2.0)
    True
    >>> Literal(1) < URIRef('foo')
    False
    >>> Literal(1) < 2.0
    False
    >>> Literal(1) < object
    False
    >>> lit2006 < "2007"
    False
    >>> "2005" < lit2006
    True
    >>> x = Literal("2", datatype=XSD.integer)
    >>> x.n3()
    %(u)s'"2"^^<http://www.w3.org/2001/XMLSchema#integer>'
    >>> Literal(x) == x
    True
    >>> x = Literal("cake", lang="en")
    >>> x
    rdflib.term.Literal(%(u)s'cake', lang='en')
    >>> Literal(x) == x
    True
    """
    __doc__ = py3compat.format_doctest_out(doc)

    if not py3compat.PY3:
        __slots__ = ("language", "datatype", "value", "_language", "_datatype", "_value")
    else:
        __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 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 datatype: datatype = URIRef(datatype)

        value=None
        if isinstance(lexical_or_value, Literal): # create from another Literal instance
            datatype=datatype or lexical_or_value.datatype
            lang=lang or lexical_or_value.language
            value=lexical_or_value.value
        elif isinstance(lexical_or_value, basestring):
            
            if datatype: 
                convFunc = _toPythonMapping.get(datatype, None)
                if convFunc:
                    try: 
                        value=convFunc(lexical_or_value)
                    except: 
                        pass # not a valid lexical representation for this dt
        
                if value is not None and normalize:
                    _value, _datatype = _castPythonToLiteral(value)
                    if _value is not None:
                        lexical_or_value = _value


        else:
            value=lexical_or_value
            _value, _datatype = _castPythonToLiteral(lexical_or_value)
            datatype=datatype or _datatype
            if _value is not None: 
                lexical_or_value = _value
            if datatype: lang=None

        if py3compat.PY3 and isinstance(lexical_or_value, bytes):
            lexical_or_value = lexical_or_value.decode('utf-8')
                
        try:
            inst = unicode.__new__(cls, lexical_or_value)
        except UnicodeDecodeError:
            inst = unicode.__new__(cls, lexical_or_value, 'utf-8')

        inst._language = lang
        inst._datatype = datatype
        inst._value = value
        return inst

    @py3compat.format_doctest_out
    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()
        rdflib.term.Literal(%(u)s'1', datatype=rdflib.term.URIRef(%(u)s'http://www.w3.org/2001/XMLSchema#integer'))
        """

        return Literal(self.value,datatype=self.datatype, lang=self.language)

    @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, (unicode(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"]

    @py3compat.format_doctest_out
    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)s'11')
        """

        py = self.toPython()
        if isinstance(py, Literal):
            s = super(Literal, self).__add__(val)
            return Literal(s, self.language, self.datatype)
        else:
            return Literal(py + val)

    def __nonzero__(self): 
        """
        Is the Literal "True"
        This is used for if statements, bool(literal), etc. 
        """
        if self.value: return bool(self.value)
        return len(self)!=0 


    @py3compat.format_doctest_out
    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, float)): 
            return Literal(self.value.__neg__())
        else: 
            raise TypeError("Not a number; %s" % repr(self))


    @py3compat.format_doctest_out
    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, float)): 
            return Literal(self.value.__pos__())
        else: 
            raise TypeError("Not a number; %s" % repr(self))

    @py3compat.format_doctest_out
    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, float)): 
            return Literal(self.value.__abs__())
        else: 
            raise TypeError("Not a number; %s" % repr(self))


    @py3compat.format_doctest_out
    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, float)): 
            return Literal(self.value.__invert__())
        else: 
            raise TypeError("Not a number; %s" % repr(self))


    @py3compat.format_doctest_out
    def __lt__(self, other):
        """
        >>> from rdflib.namespace import XSD
        >>> Literal("YXNkZg==", datatype=XSD.base64Binary) < "foo"
        False
        >>> u"\xfe" < Literal(u"foo")
        True
        >>> Literal(base64.encodestring(u"\xfe".encode("utf-8")), datatype=XSD.base64Binary) < u"foo"
        False
        """

        if other is None:
            return False # Nothing is less than None
        if isinstance(other, Literal):
            r=cmp(self.language, other.language)
            if r: return r<0
            r=cmp(self.datatype, other.datatype)
            if r: return r<0

            return unicode.__lt__(self, other)
        else: 
            return Literal<type(other)

    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
        """
        if other is None:
            return False
        if self == other:
            return True
        else:
            return self < other

    def __gt__(self, other):
        """
        Literals compare by value if datatype and lang match
        >>> Literal(1)>Literal(2)
        False
        >>> Literal(1)>Literal("2")
        True
        >>> Literal(1)>2
        True
        >>> 2>Literal(1)
        False
        >>> Literal(1)<2
        False
        >>> 2<Literal(1)
        True
        
        >>> Literal(1.2)>Literal(1.1)
        True
        >>> Literal("a")<Literal("b")
        True
        >>> Literal("a", lang="en")<Literal("b")
        False
        """
        if other is None:
            return True # Everything is greater than None
        if isinstance(other, Literal):
            r=cmp(self.language, other.language)
            if r: return r>0
            r=cmp(self.datatype, other.datatype)
            if r: return r>0
            
            return self.value>other.value
        else: 
            return Literal>type(other)

    def __ge__(self, other):
        if other is None:
            return False
        if self == other:
            return True
        else:
            return self > other

    def __ne__(self, other):
        """
        Overriden to ensure property result for comparisons with None via !=.
        Routes all other such != and <> comparisons to __eq__

        >>> Literal('') != None
        True
        >>> Literal('2') != Literal('2')
        False

        """
        return not self.__eq__(other)

    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 not self.datatype in XSDToPython or not other.datatype 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)

        """
        
        return Identifier.__hash__(self) ^ hash(self.language.lower() if self.language else None) ^ hash(self.datatype)

    @py3compat.format_doctest_out
    def __eq__(self, other):
        """
        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
        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 unicode.__eq__(self, other)

        return False


    def eq(self, other): 
        """
        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):
            # TODO XSD typePromotion!

            if self.datatype in _NUMERIC_LITERAL_TYPES  \
                    and other.datatype in _NUMERIC_LITERAL_TYPES:
                return self.value==other.value

            if not ((self.datatype==_XSD_STRING and other.datatype==None) or (other.datatype==_XSD_STRING and self.datatype==None)):                
                if self.datatype!=other.datatype: return False

            if (self.language or "").lower() != (other.language or "").lower(): return False
            
            if self.value!=None and other.value!=None: 
                return self.value == other.value
            else: 
                if unicode.__eq__(self,other): return True
                return NotImplemented # not valid values, not equal lexical
                

        elif isinstance(other, basestring):
            # 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 unicode(self) == other

        elif isinstance(other, (int, long, 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, bool): 
            if self.datatype == _XSD_BOOLEAN: 
                return self.value==other

        return NotImplemented


    def neq(self, other): 
        """
        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):
            # TODO XSD typePromotion!

            if self.datatype in _NUMERIC_LITERAL_TYPES  \
                    and other.datatype in _NUMERIC_LITERAL_TYPES:
                return self.value!=other.value

            if self.datatype!=other.datatype \
                or (self.language or "").lower() != (other.language or "").lower(): return True
            
            if self.value!=None and other.value!=None: 
                return self.value != other.value
            else: 
                if unicode.__eq__(self,other): return False
                return NotImplemented # not valid values, not equal lexical

        elif isinstance(other, basestring):
            # only plain-literals can be directly compared to strings

            # TODO: Is "blah"@en eq "blah" ? 
            if self.language is not None: return True

            if (self.datatype == _XSD_STRING or self.datatype is None): 
                return unicode(self) != other

        elif isinstance(other, (int, long, 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, bool): 
            if self.datatype == _XSD_BOOLEAN: 
                return self.value!=other

        return NotImplemented


    @py3compat.format_doctest_out
    def n3(self):
        r'''
        Returns a representation in the N3 format.

        Examples::

            >>> Literal("foo").n3()
            %(u)s'"foo"'

        Strings with newlines or triple-quotes::

            >>> Literal("foo\nbar").n3()
            %(u)s'"""foo\nbar"""'

            >>> Literal("''\'").n3()
            %(u)s'"\'\'\'"'

            >>> Literal('"""').n3()
            %(u)s'"\\"\\"\\""'

        Language::

            >>> Literal("hello", lang="en").n3()
            %(u)s'"hello"@en'

        Datatypes::

            >>> Literal(1).n3()
            %(u)s'"1"^^<http://www.w3.org/2001/XMLSchema#integer>'

            >>> Literal(1, lang="en").n3()
            %(u)s'"1"^^<http://www.w3.org/2001/XMLSchema#integer>'

            >>> Literal(1.0).n3()
            %(u)s'"1.0"^^<http://www.w3.org/2001/XMLSchema#double>'

        Datatype and language isn't allowed (datatype takes precedence)::

            >>> Literal(True).n3()
            %(u)s'"true"^^<http://www.w3.org/2001/XMLSchema#boolean>'

        Custom datatype::

            >>> footype = URIRef("http://example.org/ns#foo")
            >>> Literal("1", datatype=footype).n3()
            %(u)s'"1"^^<http://example.org/ns#foo>'

        '''
        return self._literal_n3()

    @py3compat.format_doctest_out
    def _literal_n3(self, use_plain=False, qname_callback=None):
        '''
        Using plain literal (shorthand) output::
            >>> from rdflib.namespace import XSD

            >>> Literal(1)._literal_n3(use_plain=True)
            %(u)s'1'

            >>> Literal(1.0)._literal_n3(use_plain=True)
            %(u)s'1e+00'

            >>> Literal(1.0, datatype=XSD.decimal)._literal_n3(use_plain=True)
            %(u)s'1.0'

            >>> Literal(1.0, datatype=XSD.float)._literal_n3(use_plain=True)
            %(u)s'"1.0"^^<http://www.w3.org/2001/XMLSchema#float>'

            >>> Literal("foo", datatype=XSD.string)._literal_n3(
            ...         use_plain=True)
            %(u)s'"foo"^^<http://www.w3.org/2001/XMLSchema#string>'

            >>> Literal(True)._literal_n3(use_plain=True)
            %(u)s'true'

            >>> Literal(False)._literal_n3(use_plain=True)
            %(u)s'false'

            >>> Literal(1.91)._literal_n3(use_plain=True)
            %(u)s'1.91e+00'

            Only limited precision available for floats:
            >>> Literal(0.123456789)._literal_n3(use_plain=True)
            %(u)s'1.234568e-01'

            >>> Literal('0.123456789',
            ...     datatype=XSD.decimal)._literal_n3(use_plain=True)
            %(u)s'0.123456789'

        Using callback for datatype QNames::

            >>> Literal(1)._literal_n3(
            ...         qname_callback=lambda uri: "xsd:integer")
            %(u)s'"1"^^xsd:integer'

        '''
        if use_plain and self.datatype in _PLAIN_LITERAL_TYPES:
            if self.value is not None:

                # 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", u'%e' % float(self))
                elif self.datatype == _XSD_DECIMAL:
                    s='%s'%self
                    if '.' not in s: s+='.0'
                    return s
                        
                elif self.datatype == _XSD_BOOLEAN: 
                    return (u'%s'%self).lower()
                else:
                    return u'%s' % self

        encoded = self._quote_encode()

        datatype = self.datatype
        quoted_dt = None
        if datatype:
            if qname_callback:
                quoted_dt = qname_callback(datatype)
            if not quoted_dt:
                quoted_dt = "<%s>" % datatype

        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):
        # 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')

    if not py3compat.PY3:
        def __str__(self):
            return self.encode()

    def __repr__(self):
        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"
        else:
            clsName = self.__class__.__name__
        return """%s(%s)""" % (clsName, ", ".join(args))

    def toPython(self):
        """
        Returns an appropriate python datatype derived from this RDF Literal
        """

        if self.value is not None: return self.value 
        return self

    def md5_term_hash(self):
        """a string of hex that will be the same for two Literals that
        are the same. It is not a suitable unique id.

        Supported for backwards compatibility; new code should
        probably just use __hash__
        """
        d = md5(self.encode())
        d.update(b("L"))
        return d.hexdigest()




# Cannot import Namespace/XSD because of circular dependencies

_XSD_PFX = 'http://www.w3.org/2001/XMLSchema#'

_XSD_STRING = URIRef(_XSD_PFX+'string')

_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')

# TODO: duration, gYearMonth, gYear, gMonthDay, gDay, gMonth

_NUMERIC_LITERAL_TYPES= (
    _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 = (
    _XSD_INTEGER, 
    _XSD_BOOLEAN,
    _XSD_DOUBLE,
    _XSD_DECIMAL,
)


def _castPythonToLiteral(obj):
    """
    Casts a python datatype to a tuple of the lexical value and a
    datatype URI (or None)
    """
    for pType, (castFunc, dType) in _PythonToXSD:
        if isinstance(obj, pType):
            if castFunc:
                return castFunc(obj), dType
            elif dType:
                return obj, dType
            else:
                return obj, None
    return obj, None  # TODO: is this right for the fall through case?

from decimal import Decimal

# 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

_PythonToXSD = [
    (basestring, (None, None)),
    (float     , (None, _XSD_DOUBLE)),
    (bool      , (lambda i:str(i).lower(), _XSD_BOOLEAN)),
    (int       , (None, _XSD_INTEGER)), 
    (long      , (None, _XSD_INTEGER)),
    (Decimal   , (None, _XSD_DECIMAL)),
    (datetime  , (lambda i:i.isoformat(), _XSD_DATETIME)),
    (date      , (lambda i:i.isoformat(), _XSD_DATE)),
    (time      , (lambda i:i.isoformat(), _XSD_TIME)),
]

XSDToPython = {
    URIRef(_XSD_PFX + 'time'): parse_time,
    URIRef(_XSD_PFX + 'date'): parse_date,
    URIRef(_XSD_PFX + 'dateTime'): parse_datetime,
    URIRef(_XSD_PFX + 'string'): None,
    URIRef(_XSD_PFX + 'normalizedString'): None,
    URIRef(_XSD_PFX + 'token'): None,
    URIRef(_XSD_PFX + 'language'): None,
    URIRef(_XSD_PFX + 'boolean'): lambda i: i.lower() in ['1', 'true'],
    URIRef(_XSD_PFX + 'decimal'): Decimal,
    URIRef(_XSD_PFX + 'integer'): long,
    URIRef(_XSD_PFX + 'nonPositiveInteger'): int,
    URIRef(_XSD_PFX + 'long'): long,
    URIRef(_XSD_PFX + 'nonNegativeInteger'): int,
    URIRef(_XSD_PFX + 'negativeInteger'): int,
    URIRef(_XSD_PFX + 'int'): long,
    URIRef(_XSD_PFX + 'unsignedLong'): long,
    URIRef(_XSD_PFX + 'positiveInteger'): int,
    URIRef(_XSD_PFX + 'short'): int,
    URIRef(_XSD_PFX + 'unsignedInt'): long,
    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'): lambda s: base64.b64decode(py3compat.b(s)),
    URIRef(_XSD_PFX + 'anyURI'): None,
}

_toPythonMapping = {}
_toPythonMapping.update(XSDToPython)


def bind(datatype, conversion_function):
    """
    bind a datatype to a function for converting it into a Python
    instance.
    """
    if datatype in _toPythonMapping:
        _LOGGER.warning("datatype '%s' was already bound. Rebinding." %
                        datatype)
    _toPythonMapping[datatype] = conversion_function


class Variable(Identifier):
    """
    """
    __slots__ = ()

    def __new__(cls, value):
        if len(value) == 0:
            raise Exception(
                "Attempted to create variable with empty string as name!")
        if value[0] == '?':
            value = value[1:]
        return unicode.__new__(cls, value)

    def __repr__(self):
        return self.n3()

    def toPython(self):
        return "?%s" % self

    def n3(self):
        return "?%s" % self

    def __reduce__(self):
        return (Variable, (unicode(self),))

    def md5_term_hash(self):
        """a string of hex that will be the same for two Variables that
        are the same. It is not a suitable unique id.

        Supported for backwards compatibility; new code should
        probably just use __hash__
        """
        d = md5(self.encode())
        d.update(b("V"))
        return d.hexdigest()


class Statement(Node, tuple):

    def __new__(cls, (subject, predicate, object), context):
        warnings.warn(
            "Class Statement is deprecated, and will be removed in " +
            "the future. If you use this please let rdflib-dev know!",
            category=DeprecationWarning, stacklevel=2)
        return tuple.__new__(cls, ((subject, predicate, object), context))

    def __reduce__(self):
        return (Statement, (self[0], self[1]))

    def toPython(self):
        return (self[0], self[1])


if __name__ == '__main__':
    import doctest
    doctest.testmod()