dynamicvariables.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. # coding=utf-8
  2. #
  3. # This file is part of Hypothesis, which may be found at
  4. # https://github.com/HypothesisWorks/hypothesis-python
  5. #
  6. # Most of this work is copyright (C) 2013-2018 David R. MacIver
  7. # (david@drmaciver.com), but it contains contributions by others. See
  8. # CONTRIBUTING.rst for a full list of people who may hold copyright, and
  9. # consult the git log if you need to determine who owns an individual
  10. # contribution.
  11. #
  12. # This Source Code Form is subject to the terms of the Mozilla Public License,
  13. # v. 2.0. If a copy of the MPL was not distributed with this file, You can
  14. # obtain one at http://mozilla.org/MPL/2.0/.
  15. #
  16. # END HEADER
  17. from __future__ import division, print_function, absolute_import
  18. import threading
  19. from contextlib import contextmanager
  20. class DynamicVariable(object):
  21. def __init__(self, default):
  22. self.default = default
  23. self.data = threading.local()
  24. @property
  25. def value(self):
  26. return getattr(self.data, 'value', self.default)
  27. @value.setter
  28. def value(self, value):
  29. setattr(self.data, 'value', value)
  30. @contextmanager
  31. def with_value(self, value):
  32. old_value = self.value
  33. try:
  34. self.data.value = value
  35. yield
  36. finally:
  37. self.data.value = old_value