Skip to content

Commit c870678

Browse files
committed
Remove Python 2 workarounds
1 parent c703c15 commit c870678

8 files changed

Lines changed: 49 additions & 164 deletions

File tree

curtsies/events.py

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,8 @@
77

88
from typing import Text, Optional, List, Union
99

10-
PY3 = sys.version_info[0] >= 3
11-
12-
if PY3:
13-
raw_input = input
14-
unicode = str
15-
chr_byte = lambda i: chr(i).encode("latin-1")
16-
chr_uni = chr
17-
else:
18-
chr_byte = chr
19-
chr_uni = lambda i: chr(i).decode("latin-1")
10+
chr_byte = lambda i: chr(i).encode("latin-1")
11+
chr_uni = chr
2012

2113

2214
CURTSIES_NAMES = {}
@@ -345,7 +337,7 @@ def ask_what_they_pressed(seq, Normal):
345337
print("Unidentified character sequence!")
346338
with Normal:
347339
while True:
348-
r = raw_input("type 'ok' to prove you're not pounding keys ")
340+
r = input("type 'ok' to prove you're not pounding keys ")
349341
if r.lower().strip() == "ok":
350342
break
351343
while True:
@@ -355,7 +347,7 @@ def ask_what_they_pressed(seq, Normal):
355347
break
356348
print("nope, that wasn't it")
357349
with Normal:
358-
name = raw_input("Describe in English what key you pressed: ")
350+
name = input("Describe in English what key you pressed: ")
359351
f = open("keylog.txt", "a")
360352
f.write(f"{seq!r} is called {name}\n")
361353
f.close()

curtsies/formatstring.py

Lines changed: 19 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,6 @@
3333
RESET_ALL, RESET_BG, RESET_FG,
3434
seq)
3535

36-
PY3 = sys.version_info[0] >= 3
37-
38-
if PY3:
39-
unicode = str
4036

4137
one_arg_xforms = {
4238
'bold' : lambda s: seq(STYLES['bold']) +s+seq(RESET_ALL),
@@ -97,7 +93,7 @@ def __init__(self, string, atts=None):
9793
# type: (Text, Mapping[str, Union[int, bool]]) -> None
9894
if atts is None:
9995
atts = {}
100-
if not isinstance(string, unicode):
96+
if not isinstance(string, str):
10197
raise ValueError("unicode string required, got %r" % string)
10298
self._s = string # type: Text
10399
self._atts = FrozenDict(atts)
@@ -144,11 +140,11 @@ def color_str(self):
144140
s = two_arg_xforms[k](s, v)
145141
return s
146142

147-
def __unicode__(self):
143+
def __str__(self):
148144
# type: () -> Text
149145
value = self.color_str
150146
if isinstance(value, bytes):
151-
return value.decode('utf8', 'replace')
147+
return value.decode("utf8", "replace")
152148
return value
153149

154150
def __eq__(self, other):
@@ -161,12 +157,6 @@ def __hash__(self):
161157
# type: () -> int
162158
return hash(self.s, self.atts)
163159

164-
if PY3:
165-
__str__ = __unicode__
166-
else:
167-
def __str__(self):
168-
return unicode(self).encode('utf8')
169-
170160
def __repr__(self):
171161
# type: () -> str
172162
return 'Chunk({s}{sep}{atts})'.format(
@@ -268,7 +258,6 @@ def __init__(self, *components):
268258
self.chunks = list(components)
269259

270260
# caching these leads to a significant speedup
271-
self._str = None
272261
self._unicode = None # type: Optional[Text]
273262
self._len = None # type: Optional[int]
274263
self._s = None # type: Optional[Text]
@@ -300,7 +289,7 @@ def from_str(cls, s):
300289
for x in tokens_and_strings:
301290
if isinstance(x, dict):
302291
cur_fmt.update(x)
303-
elif isinstance(x, unicode):
292+
elif isinstance(x, str):
304293
atts = parse_args((), {k: v
305294
for k, v in cur_fmt.items()
306295
if v is not None})
@@ -407,6 +396,8 @@ def join(self, iterable):
407396
before = self.chunks
408397
if isinstance(s, FmtStr):
409398
chunks.extend(s.chunks)
399+
elif isinstance(s, (bytes, str)):
400+
chunks.extend(fmtstr(s).chunks) # TODO just make a chunk directly
410401
elif isinstance(s, (bytes, unicode)):
411402
chunks.extend(fmtstr(s).chunks) #TODO just make a chunk directly
412403
else:
@@ -474,22 +465,13 @@ def rjust(self, width, fillchar=None):
474465
uniform = self.new_with_atts_removed('bg')
475466
return fmtstr(to_add, **self.shared_atts) + uniform if to_add else uniform
476467

477-
def __unicode__(self):
468+
def __str__(self):
478469
# type: () -> Text
479470
if self._unicode is not None:
480471
return self._unicode
481-
self._unicode = ''.join(unicode(fs) for fs in self.chunks)
472+
self._unicode = "".join(str(fs) for fs in self.chunks)
482473
return self._unicode
483474

484-
if PY3:
485-
__str__ = __unicode__
486-
else:
487-
def __str__(self):
488-
if self._str is not None:
489-
return self._str
490-
self._str = ''.join(str(fs) for fs in self.chunks)
491-
return self._str
492-
493475
def __len__(self):
494476
# type: () -> int
495477
if self._len is not None:
@@ -523,7 +505,7 @@ def __repr__(self):
523505

524506
def __eq__(self, other):
525507
# type: (Any) -> bool
526-
if isinstance(other, (unicode, bytes, FmtStr)):
508+
if isinstance(other, (str, bytes, FmtStr)):
527509
return str(self) == str(other)
528510
return False
529511

@@ -535,7 +517,7 @@ def __add__(self, other):
535517
# type: (Union[FmtStr, Text]) -> FmtStr
536518
if isinstance(other, FmtStr):
537519
return FmtStr(*(self.chunks + other.chunks))
538-
elif isinstance(other, (bytes, unicode)):
520+
elif isinstance(other, (bytes, str)):
539521
return FmtStr(*(self.chunks + [Chunk(other)]))
540522
else:
541523
raise TypeError(f'Can\'t add {self!r} and {other!r}')
@@ -544,7 +526,7 @@ def __radd__(self, other):
544526
# type: (Union[FmtStr, Text]) -> FmtStr
545527
if isinstance(other, FmtStr):
546528
return FmtStr(*(x for x in (other.chunks + self.chunks)))
547-
elif isinstance(other, (bytes, unicode)):
529+
elif isinstance(other, (bytes, str)):
548530
return FmtStr(*(x for x in ([Chunk(other)] + self.chunks)))
549531
else:
550532
raise TypeError('Can\'t add those')
@@ -581,15 +563,17 @@ def __getattr__(self, att):
581563
# thanks to @aerenchyma/@jczett
582564
if not hasattr(self.s, att):
583565
raise AttributeError(f"No attribute {att!r}")
566+
584567
@no_type_check
585568
def func_help(*args, **kwargs):
586569
result = getattr(self.s, att)(*args, **kwargs)
587-
if isinstance(result, (bytes, unicode)):
570+
if isinstance(result, (bytes, str)):
588571
return fmtstr(result, **self.shared_atts)
589572
elif isinstance(result, list):
590573
return [fmtstr(x, **self.shared_atts) for x in result]
591574
else:
592-
return result
575+
return result
576+
593577
return func_help
594578

595579
@property
@@ -806,15 +790,14 @@ def normalize_slice(length, index):
806790
return index
807791

808792
def parse_args(args, kwargs):
809-
# type: (Tuple[Union[bytes, unicode], ...], MutableMapping[str, Union[int, bool, str]]) -> Mapping[str, Union[int, bool]]
793+
# type: (Tuple[Union[bytes, str], ...], MutableMapping[str, Union[int, bool, str]]) -> Mapping[str, Union[int, bool]]
810794
"""Returns a kwargs dictionary by turning args into kwargs"""
811795
if 'style' in kwargs:
812796
args += (cast(str, kwargs['style']),)
813797
del kwargs['style']
814798
for arg in args:
815-
if PY3:
816-
arg = cast(str, arg)
817-
if not isinstance(arg, (bytes, unicode)):
799+
arg = cast(str, arg)
800+
if not isinstance(arg, (bytes, str)):
818801
raise ValueError("args must be strings:" + repr(args))
819802
if arg.lower() in FG_COLORS:
820803
if 'fg' in kwargs: raise ValueError("fg specified twice")
@@ -854,7 +837,7 @@ def fmtstr(string, *args, **kwargs):
854837
atts = parse_args(args, kwargs)
855838
if isinstance(string, FmtStr):
856839
pass
857-
elif isinstance(string, (bytes, unicode)):
840+
elif isinstance(string, (bytes, str)):
858841
string = FmtStr.from_str(string)
859842
else:
860843
raise ValueError("Bad Args: {!r} (of type {}), {!r}, {!r}".format(string, type(string), args, kwargs))

curtsies/formatstringarray.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -41,13 +41,7 @@
4141
no_type_check,
4242
)
4343

44-
PY3 = sys.version_info[0] >= 3
45-
46-
if PY3:
47-
unicode = str
48-
49-
actualize = str if PY3 else unicode
50-
44+
actualize = str
5145
logger = logging.getLogger(__name__)
5246

5347
# TODO check that strings used in arrays don't have tabs or spaces in them!
@@ -165,7 +159,7 @@ def __setitem__(self, slicetuple, value):
165159
logger.debug("slice: %r", slicetuple)
166160
if isinstance(slicetuple, slice):
167161
rowslice, colslice = slicetuple, slice(None)
168-
if isinstance(value, (bytes, unicode)):
162+
if isinstance(value, (bytes, str)):
169163
raise ValueError(
170164
"if slice is 2D, value must be 2D as in of list type []"
171165
)

curtsies/input.py

Lines changed: 9 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,6 @@
1919
from typing import Callable, Type, TextIO, Optional, List, Union, Text, cast, Tuple, Any
2020
from types import TracebackType, FrameType
2121

22-
PY3 = sys.version_info[0] >= 3
23-
2422
READ_SIZE = 1024
2523
assert READ_SIZE >= events.MAX_KEYPRESS_SIZE
2624
# if a keypress could require more bytes than we read to be identified,
@@ -137,12 +135,10 @@ def __iter__(self):
137135
# type: () -> Input
138136
return self
139137

140-
def next(self):
138+
def __next__(self):
141139
# type: () -> Union[None, Text, events.Event]
142140
return self.send(None)
143141

144-
__next__ = next
145-
146142
def unget_bytes(self, string):
147143
# type: (bytes) -> None
148144
"""Adds bytes to be internal buffer to be read
@@ -291,26 +287,15 @@ def _nonblocking_read(self):
291287
# type: () -> int
292288
"""Returns the number of characters read and adds them to self.unprocessed_bytes"""
293289
with Nonblocking(self.in_stream):
294-
if PY3:
295-
try:
296-
data = os.read(self.in_stream.fileno(), READ_SIZE)
297-
except BlockingIOError:
298-
return 0
299-
if data:
300-
self.unprocessed_bytes.extend(
301-
data[i : i + 1] for i in range(len(data))
302-
)
303-
return len(data)
304-
else:
305-
return 0
290+
try:
291+
data = os.read(self.in_stream.fileno(), READ_SIZE)
292+
except BlockingIOError:
293+
return 0
294+
if data:
295+
self.unprocessed_bytes.extend(data[i : i + 1] for i in range(len(data)))
296+
return len(data)
306297
else:
307-
try:
308-
data = os.read(self.in_stream.fileno(), READ_SIZE)
309-
except OSError:
310-
return 0
311-
else:
312-
self.unprocessed_bytes.extend(data)
313-
return len(data)
298+
return 0
314299

315300
def event_trigger(self, event_type):
316301
# type: (Type[events.Event]) -> Callable

tests/test_fmtstr.py

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -22,16 +22,7 @@
2222
from curtsies.termformatconstants import FG_COLORS
2323
from curtsies.formatstringarray import fsarray, FSArray, FormatStringTest
2424

25-
try:
26-
from unittest import skip
27-
except ImportError:
28-
29-
def skip(f):
30-
return lambda self: None
31-
32-
33-
PY2 = sys.version_info[0] == 2
34-
25+
from unittest import skip
3526

3627

3728
def repr_without_leading_u(s):
@@ -514,10 +505,7 @@ def test_char_width_aware_slice(self):
514505
class TestChunk(unittest.TestCase):
515506
def test_repr(self):
516507
c = Chunk("a", {"fg": 32})
517-
if PY2:
518-
self.assertEqual(repr(c), """Chunk(u'a', {'fg': 32})""")
519-
else:
520-
self.assertEqual(repr(c), """Chunk('a', {'fg': 32})""")
508+
self.assertEqual(repr(c), """Chunk('a', {'fg': 32})""")
521509

522510

523511
class TestChunkSplitter(unittest.TestCase):

tests/test_input.py

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,7 @@
55
import time
66
import unittest
77
from unittest.mock import Mock
8-
9-
try:
10-
from unittest import skip, skipUnless
11-
except ImportError:
12-
13-
def skip(f):
14-
return lambda self: None
15-
16-
def skipUnless(condition, reason):
17-
if condition:
18-
return lambda x: x
19-
else:
20-
return lambda x: None
21-
8+
from unittest import skip, skipUnless
229

2310
from curtsies import events
2411
from curtsies.input import Input

0 commit comments

Comments
 (0)