Skip to content

Instantly share code, notes, and snippets.

@MostAwesomeDude
Created March 9, 2017 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MostAwesomeDude/5943b245d288f0b6dcdc2409745d994d to your computer and use it in GitHub Desktop.
Save MostAwesomeDude/5943b245d288f0b6dcdc2409745d994d to your computer and use it in GitHub Desktop.
#!/usr/bin/env nix-shell
#! nix-shell -i python -p pythonPackages.attrs pythonPackages.pyyaml
import attr
import yaml
@attr.s(frozen=True, slots=True)
class Subject(object):
name = attr.ib()
observations = attr.ib()
def glue(self, other):
name = self.name
if name != other.name:
name += " AKA " + other.name
observations = self.observations.copy()
for k, theirs in other.observations.iteritems():
if k in observations:
ours = observations[k]
if ours != theirs:
raise Exception("ours != theirs")
else:
observations[k] = theirs
return Subject(name=name, observations=observations)
@attr.s(frozen=True, slots=True)
class Story(object):
names = attr.ib()
subjects = attr.ib()
@classmethod
def from_dict(cls, **kwargs):
names = [kwargs.pop("name")]
subjects = kwargs.pop("subjects")
subjects = {s["name"]: Subject(**s) for s in subjects}
return cls(names=names, subjects=subjects, **kwargs)
def glue(self, other):
names = self.names + other.names
subjects = {}
keys = set(self.subjects.keys() + other.subjects.keys())
for key in keys:
ours = self.subjects.get(key)
theirs = other.subjects.get(key)
if ours is None:
subjects[key] = theirs
elif theirs is None:
subjects[key] = ours
else:
subjects[key] = ours.glue(theirs)
return Story(names=names, subjects=subjects)
def find_global_section(stories):
story = Story(names=["The Null Story"], subjects={})
for s in stories.itervalues():
story = story.glue(s)
return story
with open("sw.yaml") as handle:
stories = yaml.safe_load(handle.read())
stories = {s["name"]: Story.from_dict(**s) for s in stories}
print find_global_section(stories)
- name: A New Hope
subjects:
- name: Death Star
observations:
destroyed: 0
- name: Obi-Wan Kenobi
observations:
died: 0
- name: Luke Skywalker
observations:
rogue: 0
- name: Return of the Jedi
subjects:
- name: Obi-Wan Kenobi
observations:
ghost: 4
- name: Luke Skywalker
observations:
jedi_knight: 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment