Skip to content

Instantly share code, notes, and snippets.

@safhac
Created October 29, 2021 21:03
Show Gist options
  • Save safhac/b20ee73f367afe06e500560ba1f44bb5 to your computer and use it in GitHub Desktop.
Save safhac/b20ee73f367afe06e500560ba1f44bb5 to your computer and use it in GitHub Desktop.
from contextlib import ExitStack
from dataclasses import dataclass
import json
@dataclass
class Node:
n_id: int
n_type: str
n_text: str
points_to: int | list[int] | None
def __enter__(self, *args, **kwargs):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
return True if self.n_type == 'end' else False
chart = []
with open('resources/nodes.json', 'r') as file:
data = file.read()
nodes = json.loads(data)['nodes']
with ExitStack() as stack:
chart = [stack.enter_context(Node(*tuple(n.values()))) for n in nodes]
print(chart)
# resources/nodes.json
"""
{
"nodes": [
{
"id": 1 ,
"type": "start" ,
"text": "" ,
"points_to": 2
} ,
{
"id": 2 ,
"type": "input" ,
"text": "get input" ,
"points_to": 3
} ,
{
"id": 3 ,
"type": "process" ,
"text": "do work" ,
"points_to": 4
} ,
{
"id": 4 ,
"type": "question" ,
"text": "yes/no" ,
"points_to": [
5 ,
6
]
} ,
{
"id": 5 ,
"type": "process" ,
"text": "do more work" ,
"points_to": 7
} ,
{
"id": 6 ,
"type": "input" ,
"text": "get more input" ,
"points_to": 7
} ,
{
"id": 7 ,
"type": "question" ,
"text": "yes/no" ,
"points_to": [
3 ,
8
]
} ,
{
"id": 8 ,
"type": "input" ,
"text": "get more input" ,
"points_to": 9
} ,
{
"id": 9 ,
"type": "question" ,
"text": "yes/no" ,
"points_to": [
10 ,
11
]
} ,
{
"id": 10 ,
"type": "process" ,
"text": "do more work" ,
"points_to": 12
} ,
{
"id": 11 ,
"type": "end" ,
"text": "finished 1" ,
"points_to": null
} ,
{
"id": 12 ,
"type": "end" ,
"text": "finished 2" ,
"points_to": null
}
]
}
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment