Skip to content

Instantly share code, notes, and snippets.

@derrickturk
Created September 12, 2020 19:14
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 derrickturk/d686307f83ad5b53f026fa5fce7ab87d to your computer and use it in GitHub Desktop.
Save derrickturk/d686307f83ad5b53f026fa5fce7ab87d to your computer and use it in GitHub Desktop.
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