Debian Codegraph @

clevercsv/escape.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 """
4 Common functions for dealing with escape characters.
5
6 Author: Gertjan van den Burg
7 Date: 2018-11-06
8 """
9
10 import codecs
11 import sys
12 import unicodedata
13
14 from typing import Iterable
15 from typing import Optional
16 from typing import Set
17
18 #: Set of default characters to *never* consider as escape character
19 DEFAULT_BLOCK_CHARS: Set[str] = set(
20 [
21 "!",
22 "?",
23 '"',
24 "'",
25 ".",
26 ",",
27 ";",
28 ":",
29 "%",
30 "*",
31 "&",
32 "#",
33 ]
34 )
35
36 #: Set of characters in the Unicode "Po" category
37 UNICODE_PO_CHARS: Set[str] = set(
38 [
39 c
40 for c in map(chr, range(sys.maxunicode + 1))
41 if unicodedata.category(c) == "Po"
42 ]
43 )
44
45
46 def is_potential_escapechar(
47 char: str, encoding: str, block_char: Optional[Iterable[str]] = None
48 ) -> bool:
49 """Check if a character is a potential escape character.
50
51 A character is considered a potential escape character if it is in the
52 "Punctuation, Other" Unicode category and not in the list of blocked
53 characters.
54
55 Parameters
56 ----------
57 char: str
58 The character to check
59
60 encoding : str
61 The encoding of the character
62
63 block_char : Optional[Iterable[str]]
64 Characters that are in the Punctuation Other category but that should
65 not be considered as escape character. If None, the default set is
66 used, which is defined in :py:data:`DEFAULT_BLOCK_CHARS`.
67
68 Returns
69 -------
70 is_escape : bool
71 Whether the character is considered a potential escape or not.
72
73 """
74 if encoding.lower() in set(["utf-8", "ascii"]):
75 uchar = char
76 else:
77 uchar = codecs.decode(bytes(char, encoding), encoding=encoding)
78
79 block_chars = (
80 DEFAULT_BLOCK_CHARS if block_char is None else set(block_char)
81 )
82 if uchar in UNICODE_PO_CHARS and uchar not in block_chars:
83 return True
84 return False