Skip to content

Instantly share code, notes, and snippets.

@Ry4an

Ry4an/session.py

Created Oct 13, 2015
Embed
What would you like to do?
default dict is your friend
from collections import defaultdict, namedtuple
class Session:
def __init__(self):
self.seconds = 0
self.session_id = None
self.events_by_type = defaultdict(int)
def add_event(self, event):
if self.session_id and event.session_id != self.session_id:
raise Exception("Argh mixing sessions!")
self.session_id = event.session_id
self.seconds += event.seconds
self.events_by_type[event.type_name] += 1
Event = namedtuple('Event', 'session_id type_name seconds')
sessions = defaultdict(Session)
events = (
Event('session_1', 'watched', 20),
Event('session_1', 'paused', 20),
Event('session_2', 'watched', 20),
Event('session_2', 'paused', 20),
Event('session_1', 'watched', 20),
)
# creating Sessions and added events
for event in events:
sessions[event.session_id].add_event(event)
# result
for session in sessions.itervalues():
print vars(session)
# OUTPUT
# {'seconds': 60, 'events_by_type': defaultdict(<type 'int'>, {'paused': 1, 'watched': 2}), 'session_id': 'session_1'}
# {'seconds': 40, 'events_by_type': defaultdict(<type 'int'>, {'paused': 1, 'watched': 1}), 'session_id': 'session_2'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment