code_context.py 718 B

123456789101112131415161718192021222324252627282930
  1. # mypy: allow-untyped-defs
  2. import types
  3. from .utils import ExactWeakKeyDictionary
  4. class CodeContextDict:
  5. def __init__(self):
  6. self.code_context = ExactWeakKeyDictionary()
  7. def has_context(self, code: types.CodeType):
  8. return code in self.code_context
  9. def get_context(self, code: types.CodeType):
  10. ctx = self.code_context.get(code)
  11. if ctx is None:
  12. ctx = {}
  13. self.code_context[code] = ctx
  14. return ctx
  15. def pop_context(self, code: types.CodeType):
  16. ctx = self.get_context(code)
  17. self.code_context._remove_id(id(code))
  18. return ctx
  19. def clear(self):
  20. self.code_context.clear()
  21. code_context = CodeContextDict()