Last active
August 29, 2015 14:27
-
-
Save aaronchall/24959e0bb5a5a752b4b5 to your computer and use it in GitHub Desktop.
typed lists
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 datetime import datetime, date | |
from decimal import Decimal | |
class TypedList(list): | |
'''assumes subclassed with attribute _type constructor''' | |
@classmethod | |
def gen_type(cls, iterable): | |
return (cls._type(i) for i in iterable) | |
def __init__(self, iterable=()): | |
super(TypedList, self).__init__(self.gen_type(iterable)) | |
def insert(self, index, object): | |
super(TypedList, self).insert(index, self._type(object)) | |
def extend(self, iterable): | |
super(TypedList, self).extend(self.gen_type(iterable)) | |
def __iadd__(self, other): | |
return super(TypedList, self).__iadd__(self.gen_type(other)) | |
def append(self, object): | |
super(TypedList, self).append(self._type(object)) | |
def __setslice__(self, i, j, sequence): | |
super(TypedList, self).__setitem__(self, i, j, self.gen_type(sequence)) | |
def __setitem__(self, key, value): | |
super(TypedList, self).__setitem__(key, self._type(value)) | |
# 'string[]' | |
class StrList(TypedList): | |
_type = str | |
# 'float[]' | |
class FloatList(TypedList): | |
_type = float | |
# 'int[]' | |
class IntList(TypedList): | |
_type = int | |
# 'decimal[]' # ??? | |
class DecimalList(TypedList): | |
'''must convert floats to strings before giving to list''' | |
_type = Decimal | |
# 'date[]' | |
class DateList(TypedList): | |
'''can convert from date 3-tuple''' | |
@staticmethod | |
def _type(obj): | |
if isinstance(obj, date): | |
return obj | |
if isinstance(obj, datetime): | |
return obj.date | |
return date(*obj) | |
# 'time[]' | |
class TimeList(TypedList): | |
'''can convert from timetuple, i.e. 3+tuple''' | |
@staticmethod | |
def _type(obj): | |
if isinstance(obj, datetime): | |
return obj | |
if isinstance(obj, date): | |
return datetime(*obj.timetuple()[:6]) | |
if isinstance(obj, (int, long)): | |
return datetime.fromtimestamp(obj) | |
return datetime(*obj) | |
sl = StrList('0123') | |
print(sl) | |
il = IntList(sl) | |
print(il) | |
fl = FloatList(il) | |
print(fl) | |
dl = DecimalList(sl) | |
dl += il | |
print(dl) | |
datel = DateList() | |
datel.append(date.today()) | |
datel.extend(((1,1,1),(2,2,2))) | |
print(datel) | |
timel = TimeList(datel) | |
timel.append(datetime.now()) | |
print(timel) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment