Created
March 25, 2018 19:11
-
-
Save LewisGaul/e82758acdde014bf1e713242d18aef8c to your computer and use it in GitHub Desktop.
Mutable string array with most string methods treating it as a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import wraps | |
def use_str(method, self): | |
@wraps(method) | |
def new_method(*args, **kwargs): | |
return getattr(self.__str__(), method.__name__)(*args, **kwargs) | |
return new_method | |
class Buffer(bytearray): | |
def __init__(self, s=''): | |
if isinstance(s, str): | |
s = s.encode() | |
super().__init__(s) | |
# First convert most string methods to use strings directly. | |
for method in ['capitalize', 'center', 'count', 'endswith', | |
'expandtabs', 'find', 'index', 'join', 'ljust', 'lower', | |
'lstrip', 'partition', 'replace', 'rfind', 'rindex', | |
'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', | |
'splitlines', 'startswith', 'strip', 'swapcase', 'title', | |
'translate', 'upper', 'zfill']: | |
setattr(self, method, use_str(getattr(str, method), self)) | |
def __repr__(self): | |
return "Buffer({})".format(self.__str__()) | |
def __str__(self): | |
return bytes(b).__str__()[2:-1] | |
# Methods which alter self. | |
def __iadd__(self, s): | |
""" | |
Allow adding of strings or iterables of integers, using the extend | |
method. Also print the added string in the correct position. | |
""" | |
if ((hasattr(s, '__iter__') and | |
not all([isinstance(c, int) for c in s])) and | |
not isinstance(s, str)): | |
raise TypeError("a string or iterable of integers is required") | |
if isinstance(s, str): | |
self.extend(s.encode()) | |
else: | |
self.extend(s) | |
return self | |
def append(self, s): | |
if isinstance(s, (str, bytes)) and len(s) == 1: | |
s = ord(s) | |
super().append(s) | |
def extend(self, s): | |
if isinstance(s, str): | |
s = s.encode() | |
super().extend(s) | |
def pop(self, index=-1): | |
return chr(super().pop(index)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment