Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Commit 201c48c

Browse files
authored
Remove a Python 2-ism and improve type hints. (#11699)
On Python 2, indexing a byte-string gives back a byte-string, while on Python 3 it gives back the ASCII equivalent as an int.
1 parent 70ce9ae commit 201c48c

File tree

2 files changed

+8
-12
lines changed

2 files changed

+8
-12
lines changed

changelog.d/11699.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Remove fallback code for Python 2.

synapse/types.py

+7-12
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
ClassVar,
2222
Dict,
2323
Mapping,
24+
Match,
2425
MutableMapping,
2526
Optional,
2627
Tuple,
@@ -380,37 +381,31 @@ def map_username_to_mxid_localpart(
380381
onto different mxids
381382
382383
Returns:
383-
unicode: string suitable for a mxid localpart
384+
string suitable for a mxid localpart
384385
"""
385386
if not isinstance(username, bytes):
386387
username = username.encode("utf-8")
387388

388389
# first we sort out upper-case characters
389390
if case_sensitive:
390391

391-
def f1(m):
392+
def f1(m: Match[bytes]) -> bytes:
392393
return b"_" + m.group().lower()
393394

394395
username = UPPER_CASE_PATTERN.sub(f1, username)
395396
else:
396397
username = username.lower()
397398

398-
# then we sort out non-ascii characters
399-
def f2(m):
400-
g = m.group()[0]
401-
if isinstance(g, str):
402-
# on python 2, we need to do a ord(). On python 3, the
403-
# byte itself will do.
404-
g = ord(g)
405-
return b"=%02x" % (g,)
399+
# then we sort out non-ascii characters by converting to the hex equivalent.
400+
def f2(m: Match[bytes]) -> bytes:
401+
return b"=%02x" % (m.group()[0],)
406402

407403
username = NON_MXID_CHARACTER_PATTERN.sub(f2, username)
408404

409405
# we also do the =-escaping to mxids starting with an underscore.
410406
username = re.sub(b"^_", b"=5f", username)
411407

412-
# we should now only have ascii bytes left, so can decode back to a
413-
# unicode.
408+
# we should now only have ascii bytes left, so can decode back to a string.
414409
return username.decode("ascii")
415410

416411

0 commit comments

Comments
 (0)