current_scope_id.py 637 B

123456789101112131415161718192021222324
  1. # mypy: allow-untyped-defs
  2. import contextlib
  3. import threading
  4. # Global variable to identify which SubgraphTracer we are in.
  5. # It is sometimes difficult to find an InstructionTranslator to use.
  6. _current_scope_id = threading.local()
  7. def current_scope_id():
  8. global _current_scope_id
  9. if not hasattr(_current_scope_id, "value"):
  10. _current_scope_id.value = 1
  11. return _current_scope_id.value
  12. @contextlib.contextmanager
  13. def enter_new_scope():
  14. global _current_scope_id
  15. try:
  16. _current_scope_id.value = current_scope_id() + 1
  17. yield
  18. finally:
  19. _current_scope_id.value = current_scope_id() - 1