Created
October 4, 2018 04:53
-
-
Save theY4Kman/b19be9ce20f8e4dc372823608a03d6ed to your computer and use it in GitHub Desktop.
This file contains hidden or 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 typing import Union | |
def resolve(d: dict) -> dict: | |
"""Helper which resolves references marked with ref(id) | |
>>> resolve({'frames': {'0': 'test'}, 'paths': {'0': [ref('0')]}}) | |
{'frames': {'0': 'test'}, 'paths': {'0': ['test']}} | |
""" | |
frame_refs = d['frames'] | |
cmp_refs = { | |
k: v | |
for frame in frame_refs.values() | |
for k, v in frame['comparisons'].items() | |
} | |
refs = { | |
**frame_refs, | |
**cmp_refs, | |
} | |
def resolve_refs(o: Union[dict, list, tuple, set]): | |
if isinstance(o, dict): | |
return { | |
k: resolve_refs(v) | |
for k, v in o.items() | |
} | |
elif isinstance(o, (list, tuple, set)): | |
t = type(o) | |
return t(resolve_refs(v) for v in o) | |
elif isinstance(o, Reference): | |
return refs.get(o, o) | |
else: | |
return o | |
return resolve_refs(d) | |
class Reference(str): | |
"""Marks a reference to a frame or comparison | |
Do not use this directly. Instead, use ref(id). | |
This will only work when used within a dict passed to parsed(). | |
""" | |
def ref(id: str) -> Reference: | |
return Reference(id) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment