Skip to content

Instantly share code, notes, and snippets.

@dansondergaard
Created October 21, 2019 19:58
Show Gist options
  • Save dansondergaard/64059f9659d51cd8f6a01a7c1a77f5e2 to your computer and use it in GitHub Desktop.
Save dansondergaard/64059f9659d51cd8f6a01a7c1a77f5e2 to your computer and use it in GitHub Desktop.
from datetime import datetime
from functools import singledispatch
class State:
def __init__(self, meta):
self.meta = meta
def has_failed(self):
return isinstance(self, Failed)
def has_completed(self):
return isinstance(self, Completed)
class RuntimeMixin:
def runtime(self):
return self.meta["ended_at"] - self.meta["started_at"]
class Initial(State):
pass
class Submitted(State):
pass
class Running(State):
pass
class Completed(State, RuntimeMixin):
pass
class Failed(State, RuntimeMixin):
pass
@singledispatch
def move_to(from_state):
raise Exception("Cannot move out of state {}.".format(from_state.__class__.__name__))
@move_to.register(Initial)
def _(from_state):
return Submitted(meta=dict(from_state.meta, submitted_at=datetime.now()))
@move_to.register(Submitted)
def _(from_state):
return Running(meta=dict(from_state.meta, started_at=datetime.now()))
@move_to.register(Running)
def _(from_state, return_code):
if return_code == 0:
return Completed(meta=dict(from_state.meta, ended_at=datetime.now()))
return Failed(meta=dict(from_state.meta, ended_at=datetime.now()))
s = Initial(meta=dict(name="foo"))
print(type(s), s.meta)
s = move_to(s)
print(type(s), s.meta)
s = move_to(s)
print(type(s), s.meta)
s = move_to(s, return_code=0)
print(type(s), s.meta)
print(s.runtime())
# s = move_to(s)
# print(type(s), s.meta)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment