You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

max_recursion_limit.py 2.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # -*- coding: utf-8 -*-
  2. import platform
  3. import sys
  4. import threading
  5. # Windows do not imp resource package
  6. if platform.system() != "Windows":
  7. import resource
  8. class AlternativeRecursionLimit:
  9. r"""A reentrant context manager for setting global recursion limits."""
  10. def __init__(self, new_py_limit):
  11. self.new_py_limit = new_py_limit
  12. self.count = 0
  13. self.lock = threading.Lock()
  14. self.orig_py_limit = 0
  15. self.orig_rlim_stack_soft = 0
  16. self.orig_rlim_stack_hard = 0
  17. def __enter__(self):
  18. with self.lock:
  19. if self.count == 0:
  20. self.orig_py_limit = sys.getrecursionlimit()
  21. if platform.system() != "Windows":
  22. (
  23. self.orig_rlim_stack_soft,
  24. self.orig_rlim_stack_hard,
  25. ) = resource.getrlimit(resource.RLIMIT_STACK)
  26. # FIXME: https://bugs.python.org/issue34602, python3 release version
  27. # on Macos always have this issue, not all user install python3 from src
  28. try:
  29. resource.setrlimit(
  30. resource.RLIMIT_STACK,
  31. (self.orig_rlim_stack_hard, self.orig_rlim_stack_hard),
  32. )
  33. except ValueError as exc:
  34. if platform.system() != "Darwin":
  35. raise exc
  36. # increase recursion limit
  37. sys.setrecursionlimit(self.new_py_limit)
  38. self.count += 1
  39. def __exit__(self, type, value, traceback):
  40. with self.lock:
  41. self.count -= 1
  42. if self.count == 0:
  43. sys.setrecursionlimit(self.orig_py_limit)
  44. if platform.system() != "Windows":
  45. try:
  46. resource.setrlimit(
  47. resource.RLIMIT_STACK,
  48. (self.orig_rlim_stack_soft, self.orig_rlim_stack_hard),
  49. )
  50. except ValueError as exc:
  51. if platform.system() != "Darwin":
  52. raise exc
  53. _max_recursion_limit_context_manager = AlternativeRecursionLimit(2 ** 31 - 1)
  54. def max_recursion_limit():
  55. r"""Sets recursion limit to the max possible value."""
  56. return _max_recursion_limit_context_manager