Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simpler version of PyMC3's questionable idea
import sys
from typing import ClassVar, Dict, List, Type
class Model:
_ctx: 'ClassVar[List[Model]]' = list()
def __init__(self):
self.nodes: 'Dict[Node]' = dict()
def __enter__(self):
Model._ctx.append(self)
return self
def __exit__(self, typ, value, traceback):
Model._ctx.pop()
@classmethod
def context(cls: 'Type[Model]'):
if not cls._ctx:
raise ValueError('empty context stack')
return cls._ctx[-1]
class Node:
def __init__(self, name: str):
self.name = name
Model.context().nodes[self.name] = self
def main(argv: List[str]) -> int:
with Model() as mdl:
x = Node('x')
y = Node('y')
z = Node('z')
print(mdl.nodes)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.