Skip to content

Commit

Permalink
Move get() and find() functions into utils.py
Browse files Browse the repository at this point in the history
  • Loading branch information
mathsman5133 committed Apr 21, 2019
1 parent 1c542df commit 5f31c78
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 23 deletions.
26 changes: 3 additions & 23 deletions coc/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,35 +29,15 @@
from operator import attrgetter
from itertools import chain

from .utils import get, from_timestamp


def try_enum(_class, data):
if data is None:
return None
return _class(data=data)


def find(predicate, seq):
for element in seq:
if predicate(element):
return element
return None


def get(iterable, **attrs):
def predicate(elem):
for attr, val in attrs.items():
nested = attr.split('__')
obj = elem
for attribute in nested:
obj = getattr(obj, attribute)

if obj != val:
return False
return True

return find(predicate, iterable)


class Clan:
"""Represents the most stripped down version of clan info.
All other clan classes inherit this.
Expand Down Expand Up @@ -1112,7 +1092,7 @@ def __init__(self, *, data):
@property
def utc_timestamp(self):
""":class:`datetime`: The timestamp as a UTC datetime object"""
return datetime.strptime(self.time, '%Y%m%dT%H%M%S.000Z')
return from_timestamp(self.time)

@property
def now(self):
Expand Down
27 changes: 27 additions & 0 deletions coc/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import json

from datetime import datetime


def to_json(model):
dct = {}
Expand Down Expand Up @@ -32,4 +34,29 @@ def to_json(model):
return json.loads(dct, separators=(',', ':'), ensure_ascii=True)


def find(predicate, seq):
for element in seq:
if predicate(element):
return element
return None


def get(iterable, **attrs):
def predicate(elem):
for attr, val in attrs.items():
nested = attr.split('__')
obj = elem
for attribute in nested:
obj = getattr(obj, attribute)

if obj != val:
return False
return True

return find(predicate, iterable)


def from_timestamp(timestamp):
return datetime.strptime(timestamp, '%Y%m%dT%H%M%S.000Z')


0 comments on commit 5f31c78

Please sign in to comment.