Source code

Download source archive ↓

src/rdflib/compat.py

1"""
2Utility functions and objects to ease Python 2/3 compatibility,
3and different versions of support libraries.
4"""
5
6from __future__ import annotations
7
8import codecs
9import re
10import warnings
11from typing import Match
12
13
14def cast_bytes(s, enc="utf-8"):
15    if isinstance(s, str):
16        return s.encode(enc)
17    return s
18
19
20def ascii(stream):
21    return codecs.getreader("ascii")(stream)
22
23
24def bopen(*args, **kwargs):
25    # type error: No overload variant of "open" matches argument types "Tuple[Any, ...]", "str", "Dict[str, Any]"
26    return open(*args, mode="rb", **kwargs)  # type: ignore[call-overload]
27
28
29long_type = int
30
31
32def sign(n):
33    if n < 0:
34        return -1
35    if n > 0:
36        return 1
37    return 0
38
39
40r_unicodeEscape = re.compile(r"(\\u[0-9A-Fa-f]{4}|\\U[0-9A-Fa-f]{8})")  # noqa: N816
41
42
43def _unicodeExpand(s):  # noqa: N802
44    return r_unicodeEscape.sub(lambda m: chr(int(m.group(0)[2:], 16)), s)
45
46
47def decodeStringEscape(s):  # noqa: N802
48    warnings.warn(
49        DeprecationWarning(
50            "rdflib.compat.decodeStringEscape() is deprecated, "
51            "it will be removed in rdflib 7.0.0. "
52            "This function is not used anywhere in rdflib anymore "
53            "and the utility that it does provide is not implemented correctly."
54        )
55    )
56    r"""
57    s is byte-string - replace \ escapes in string
58    """
59
60    s = s.replace("\\t", "\t")
61    s = s.replace("\\n", "\n")
62    s = s.replace("\\r", "\r")
63    s = s.replace("\\b", "\b")
64    s = s.replace("\\f", "\f")
65    s = s.replace('\\"', '"')
66    s = s.replace("\\'", "'")
67    s = s.replace("\\\\", "\\")
68
69    return s
70    # return _unicodeExpand(s) # hmm - string escape doesn't do unicode escaping
71
72
73_string_escape_map = {
74    "t": "\t",
75    "b": "\b",
76    "n": "\n",
77    "r": "\r",
78    "f": "\f",
79    '"': '"',
80    "'": "'",
81    "\\": "\\",
82}
83
84
85def _turtle_escape_subber(match: Match[str]) -> str:
86    smatch, umatch = match.groups()
87    if smatch is not None:
88        return _string_escape_map[smatch]
89    else:
90        return chr(int(umatch[1:], 16))
91
92
93_turtle_escape_pattern = re.compile(
94    r"""\\(?:([tbnrf"'\\])|(u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8}))""",
95)
96
97
98def decodeUnicodeEscape(escaped: str) -> str:  # noqa: N802
99    if "\\" not in escaped:
100        # Most of times, there are no backslashes in strings.
101        return escaped
102    return _turtle_escape_pattern.sub(_turtle_escape_subber, escaped)