Skip to content

Commit 106ebfa

Browse files
committed
Cleaned up code
1 parent 0eef213 commit 106ebfa

14 files changed

Lines changed: 50 additions & 86 deletions

File tree

codext/base/_base.py

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,10 @@ def _generate_charset(n):
3838

3939
def _get_charset(charset, p=""):
4040
"""
41-
Charaters set selection function. It allows to define charsets in many
42-
different ways.
41+
Characters set selection function. It allows to define charsets in many different ways.
4342
44-
:param charset: charset object, can be a string (the charset itself), a
45-
function (that chooses the right charset depending on the
46-
input parameter) or a dictionary (either by exact key or by
47-
pattern matching)
43+
:param charset: charset object, can be a string (the charset itself), a function (that chooses the right charset
44+
depending on the input parameter) or a dictionary (either by exact key or by pattern matching)
4845
:param p: the parameter for choosing the charset
4946
"""
5047
# case 1: charset is a function, so return its result
@@ -53,12 +50,11 @@ def _get_charset(charset, p=""):
5350
# case 2: charset is a string, so return it
5451
elif isinstance(charset, string_types):
5552
return charset
56-
# case 3: charset is a dict with keys '' and 'inv', typically for a charset
57-
# using lowercase and uppercase characters that can be inverted
53+
# case 3: charset is a dict with keys '' and 'inv', typically for a charset using lowercase and uppercase characters
54+
# that can be inverted
5855
elif isinstance(charset, dict) and list(charset.keys()) == ["", "inv"]:
5956
return charset["inv" if re.match(r"[-_]inv(erted)?$", p) else ""]
60-
# case 4: charset is a dict, but not with the specific keys '' and 'inv', so
61-
# consider it as pattern-charset pairs
57+
# case 4: charset is a dict, but not with the specific keys '' and 'inv', so consider it as pattern-charset pairs
6258
elif isinstance(charset, dict):
6359
# try to handle [p]arameter as a simple key
6460
try:
@@ -74,8 +70,7 @@ def _get_charset(charset, p=""):
7470
continue
7571
if re.match(pattern, p):
7672
return cset
77-
# special case: the given [p]arameter can be the charset itself if
78-
# it has the right length
73+
# special case: the given [p]arameter can be the charset itself if it has the right length
7974
p = re.sub(r"^[-_]+", "", p)
8075
if len(p) == n:
8176
return p
@@ -119,23 +114,21 @@ def base_decode(input, charset, errors="strict", exc=BaseEncodeError):
119114
i = i * n + charset.index(c)
120115
except ValueError:
121116
if errors == "strict":
122-
raise exc("'base' codec can't decode character '{}' in position"
123-
" {}".format(c, k))
117+
raise exc("'base' codec can't decode character '{}' in position {}".format(c, k))
124118
elif errors in ["ignore", "replace"]:
125119
continue
126120
else:
127121
raise ValueError("Unsupported error handling {}".format(errors))
128122
return base_encode(i, [chr(j) for j in range(256)], errors, exc)
129123

130124

131-
def base(charset, pattern=None, pow2=False,
132-
encode_template=base_encode, decode_template=base_decode):
125+
def base(charset, pattern=None, pow2=False, encode_template=base_encode, decode_template=base_decode):
133126
"""
134127
Base-N codec factory.
135128
136129
:param charset: charset selection function
137-
:param pattern: matching pattern for the codec name (first capturing group
138-
is used as the parameter for selecting the charset)
130+
:param pattern: matching pattern for the codec name (first capturing group is used as the parameter for selecting
131+
the charset)
139132
:param pow2: whether the base codec's N is a power of 2
140133
"""
141134
is_n = isinstance(charset, int)

codext/base/_base2n.py

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ def base2n(charset, pattern=None):
2626
Base-N codec factory for N a power of 2.
2727
2828
:param charset: charset selection function
29-
:param pattern: matching pattern for the codec name (first capturing group
30-
is used as the parameter for selecting the charset)
29+
:param pattern: matching pattern for the codec name (first capturing group is used as the parameter for selecting
30+
the charset)
3131
"""
3232
base(charset, pattern, True, base2n_encode, base2n_decode)
3333

@@ -83,12 +83,10 @@ def base2n_decode(string, charset, errors="strict", exc=Base2NDecodeError):
8383
elif any(c in string for c in "ABCDEF"):
8484
charset = charset.upper()
8585
string = re.sub(r"\s", "", string)
86-
# find the number of bits for the given character set and the number of
87-
# padding characters
86+
# find the number of bits for the given character set and the number of padding characters
8887
nb_in = int(log(n, 2))
8988
n_pad = len(string) - len(string.rstrip("="))
90-
# iterate over the characters, mapping them to the character set and
91-
# converting the resulting bits to 8-bits characters
89+
# iterate over the characters, mapping them to the character set and converting the resulting bits to 8-bits chars
9290
for i, c in enumerate(string):
9391
if c == "=":
9492
bs += "0" * nb_in
@@ -97,20 +95,17 @@ def base2n_decode(string, charset, errors="strict", exc=Base2NDecodeError):
9795
bs += ("{:0>%d}" % nb_in).format(bin(charset.index(c))[2:])
9896
except ValueError:
9997
if errors == "strict":
100-
raise exc("'base' codec can't decode character '{}' in "
101-
"position {}".format(c, i))
98+
raise exc("'base' codec can't decode character '{}' in position {}".format(c, i))
10299
elif errors == "replace":
103100
bs += "0" * nb_in
104101
elif errors == "ignore":
105102
continue
106103
else:
107-
raise ValueError("Unsupported error handling {}"
108-
.format(errors))
104+
raise ValueError("Unsupported error handling {}".format(errors))
109105
if len(bs) > 8:
110106
r += chr(int(bs[:8], 2))
111107
bs = bs[8:]
112-
# if the number of bits is not multiple of 8 bits, it could mean a bad
113-
# padding
108+
# if the number of bits is not multiple of 8 bits, it could mean a bad padding
114109
if len(bs) != 8:
115110
if errors == "strict":
116111
raise Base2NDecodeError("Incorrect padding")

codext/base/base100.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
# -*- coding: UTF-8 -*-
22
"""Base100 Codec - base100 content encoding.
33
4-
Note: only works in Python3 ; strongly inspired from
5-
https://github.com/MasterGroosha/pybase100
4+
Note: only works in Python3 ; strongly inspired from https://github.com/MasterGroosha/pybase100
65
76
This codec:
87
- en/decodes strings from str to str
@@ -33,10 +32,8 @@ def base100_encode(input, errors='strict'):
3332

3433
def base100_decode(input, errors='strict'):
3534
input = b(input)
36-
print(input)
3735
if len(input) % 4 != 0:
38-
raise Base100DecodeError("Bad input (length should be multiple of"
39-
" 4)")
36+
raise Base100DecodeError("Bad input (length should be multiple of 4)")
4037
r = [None] * (len(input) // 4)
4138
for i, c in enumerate(input):
4239
if i % 4 == 2:
@@ -46,5 +43,4 @@ def base100_decode(input, errors='strict'):
4643
return bytes(r), len(input)
4744

4845

49-
add("base100", base100_encode, base100_decode,
50-
r"(?i)^(?:base[-_]?100|emoji)$")
46+
add("base100", base100_encode, base100_decode, r"(?i)^(?:base[-_]?100|emoji)$")

codext/base/baseN.py

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -35,13 +35,12 @@
3535

3636

3737
B32 = {
38-
r'': upper + "234567",
39-
r'[-_]inv(erted)?$': "234567" + upper,
38+
r'': upper + "234567",
39+
r'[-_]inv(erted)?$': "234567" + upper,
4040
r'(?:[-_]ext(?:ended)?)?[-_]hex$': digits + upper[:22],
41-
r'[-_]geohash': digits + "bcdefghjkmnpqrstuvwxyz",
41+
r'[-_]geohash': digits + "bcdefghjkmnpqrstuvwxyz",
4242
}
43-
base2n(B32, r"(?i)^base[-_]?32(|[-_]inv(?:erted)?|"
44-
r"(?:[-_]ext(?:ended)?)?[-_]hex|[-_]geohash)$")
43+
base2n(B32, r"(?i)^base[-_]?32(|[-_]inv(?:erted)?|(?:[-_]ext(?:ended)?)?[-_]hex|[-_]geohash)$")
4544
ZB32 = {'': "ybndrfg8ejkmcpqxot1uwisza345h769"}
4645
base2n(ZB32, r"(?i)^z[-_]?base[-_]?32$")
4746

@@ -51,41 +50,36 @@
5150

5251

5352
B58 = {
54-
r'(|[-_](bc|bitcoin))$': "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopq"
55-
"rstuvwxyz",
56-
r'[-_](rp|ripple)$': "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tu"
57-
"vAxyz",
58-
r'[-_](fl|flickr|short[-]?url|url)$': "123456789abcdefghijkmnopqrstuvwxyzAB"
59-
"CDEFGHJKLMNPQRSTUVWXYZ"
53+
r'(|[-_](bc|bitcoin))$': "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",
54+
r'[-_](rp|ripple)$': "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz",
55+
r'[-_](fl|flickr|short[-]?url|url)$': "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ",
6056
}
61-
base(B58, r"(?i)^base[-_]?58(|[-_](bc|bitcoin|rp|ripple|fl|flickr|"
62-
r"short[-]?url|url))$")
57+
base(B58, r"(?i)^base[-_]?58(|[-_](bc|bitcoin|rp|ripple|fl|flickr|short[-]?url|url))$")
6358

6459

6560
B62 = {'': digits + upper + lower, 'inv': digits + lower + upper}
6661
base(B62, r"(?i)^base[-_]?62(|[-_]inv(?:erted)?)$")
6762

6863

6964
B64 = {
70-
r'': upper + lower + digits + "+/",
71-
r'[-_]inv(erted)?$': lower + upper + digits + "+/",
65+
r'': upper + lower + digits + "+/",
66+
r'[-_]inv(erted)?$': lower + upper + digits + "+/",
7267
r'[-_](file|url)(safe)?$': upper + lower + digits + "-_",
7368
}
7469
base2n(B64, r"(?i)^base[-_]?64(|[-_]inv(?:erted)?|[-_](?:file|url)(?:safe)?)$")
7570

7671

7772
#FIXME
7873
#B85 = {
79-
# r'': "!\"#$%&'()*+,-./" + digits + ":;<=>?@" + upper + "[\\]^_`" + \
80-
# lower[:21],
74+
# r'': "!\"#$%&'()*+,-./" + digits + ":;<=>?@" + upper + "[\\]^_`" + lower[:21],
8175
# r'[-_]z(eromq)?$': digits + upper + lower + ".-:+=^!/*?&<>()[]{}@%$#",
82-
# r'[-_]rfc1924$': digits + upper + lower + "!#$%&()*+-;<=>?@^_`{|}~",
76+
# r'[-_]rfc1924$': digits + upper + lower + "!#$%&()*+-;<=>?@^_`{|}~",
8377
#}
8478
#base(B85, r"(?i)^(?:ascii|base)[-_]?85(|[-_](?:z(?:eromq)?|rfc1924))$")
8579

8680

8781
B91 = {
88-
'': upper + lower + digits + "!#$%&()*+,./:;<=>?@[]^_`{|}~\"",
82+
'': upper + lower + digits + "!#$%&()*+,./:;<=>?@[]^_`{|}~\"",
8983
'inv': lower + upper + digits + "!#$%&()*+,./:;<=>?@[]^_`{|}~\"",
9084
}
9185
base(B91, r"(?i)^base[-_]?91(|[-_]inv(?:erted)?)$")

codext/crypto/rotn.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,6 @@
88
- encodes file content from str to bytes (write)
99
"""
1010
from string import ascii_lowercase as LC, ascii_uppercase as UC
11-
try: # Python 2
12-
from string import maketrans
13-
except ImportError: # Python 3
14-
maketrans = str.maketrans
1511

1612
from ..__common__ import *
1713

@@ -36,6 +32,5 @@ def decode(text, errors="strict"):
3632
return decode
3733

3834

39-
# note: the integer behind "rot" is captured for sending to the parametrizable
40-
# encode and decode functions "rotn_**code"
35+
# note: the integer behind "rot" is captured for sending to the parametrizable encode and decode functions "rotn_**code"
4136
add("rotN", rot_encode, rot_decode, r"(?i)rot[-_]?([1-9]|1[0-9]|2[0-5])$")

codext/crypto/xor_byte.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ def encode(text, errors="strict"):
2121
return encode
2222

2323

24-
# note: the integer behind "xor" is captured for sending to the parametrizable
25-
# encode and decode functions "xor_byte_**code"
26-
add("xorN", xor_byte_encode, xor_byte_encode,
27-
r"(?i)xor[-_]?([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$")
24+
# note: the integer (belongs to ]0,256[) behind "xor" is captured for sending to the parametrizable encode and decode
25+
# functions "xor_byte_**code"
26+
add("xorN", xor_byte_encode, xor_byte_encode, r"(?i)xor[-_]?([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$")

codext/others/markdown.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ def markdown_encode(mdtext, errors="strict"):
1515
return markdown(mdtext), len(mdtext)
1616

1717

18-
# note: the group is NOT captured so that the pattern is only used to match the
19-
# name of the codec and not to dynamically bind to a parametrizable
20-
# encode function
18+
# note: the group is NOT captured so that the pattern is only used to match the name of the codec and not to dynamically
19+
# bind to a parametrizable encode function
2120
add("markdown", markdown_encode, pattern=r"^(?:markdown|Markdown|md)$")

tests/test_barbie.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@
1111
class TestCodecBarbie(TestCase):
1212
def test_codec_barbie(self):
1313
STR = "this is a test"
14-
BRB = ["hstf tf i hafh", "sfhp hp t sips", "fpsu su h ftuf",
15-
"pufq fq s phqp"]
14+
BRB = ["hstf tf i hafh", "sfhp hp t sips", "fpsu su h ftuf", "pufq fq s phqp"]
1615
self.assertRaises(LookupError, codecs.encode, STR, "barbie")
1716
for i in range(4):
1817
self.assertEqual(codecs.encode(STR, "barbie{}".format(i+1)), BRB[i])

tests/test_base.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -133,8 +133,7 @@ def test_codec_base32(self):
133133
self.assertEqual(codecs.decode(B32, "z_base_32"), STR)
134134
self.assertEqual(codecs.decode(b(B32), "zbase32"), b(STR))
135135
self.assertRaises(ValueError, codecs.decode, B32.rstrip("="), "zbase32")
136-
self.assertRaises(ValueError, codecs.decode, B32.rstrip("="), "zbase32",
137-
"BAD")
136+
self.assertRaises(ValueError, codecs.decode, B32.rstrip("="), "zbase32", "BAD")
138137

139138
def test_codec_base36(self):
140139
B36 = "4WMHTK6UZL044O91NKCEB8"
@@ -205,9 +204,8 @@ def test_codec_base91(self):
205204

206205
def test_codec_base100(self):
207206
if PY3:
208-
B100 = "\U0001f46b\U0001f45f\U0001f460\U0001f46a\U0001f417" \
209-
"\U0001f460\U0001f46a\U0001f417\U0001f458\U0001f417" \
210-
"\U0001f46b\U0001f45c\U0001f46a\U0001f46b"
207+
B100 = "\U0001f46b\U0001f45f\U0001f460\U0001f46a\U0001f417\U0001f460\U0001f46a\U0001f417\U0001f458" \
208+
"\U0001f417\U0001f46b\U0001f45c\U0001f46a\U0001f46b"
211209
self.assertEqual(codecs.encode(STR, "base100"), B100)
212210
self.assertEqual(codecs.encode(b(STR), "base100"), b(B100))
213211
self.assertEqual(codecs.decode(B100, "base100"), STR)

tests/test_dna.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ def test_codec_dna(self):
2828
self.assertEqual(codecs.decode(DNA[i], enc), STR)
2929
self.assertEqual(codecs.decode(b(DNA[i]), enc), b(STR))
3030
self.assertRaises(ValueError, codecs.decode, "ABC", enc)
31-
self.assertEqual(codecs.decode("ABC", "dna-2", errors="replace"),
32-
"[00??01]")
31+
self.assertEqual(codecs.decode("ABC", "dna-2", errors="replace"), "[00??01]")
3332
self.assertEqual(codecs.decode("ABC", "dna-1", errors="ignore"), "\x02")
3433
self.assertRaises(ValueError, codecs.decode, "B", "dna-8", errors="BAD")
34+
self.assertRaises(LookupError, codecs.decode, "B", "dna-123")

0 commit comments

Comments
 (0)