environment.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import os
  2. from distutils.dist import Distribution
  3. __metaclass__ = type
  4. class EnvironmentConfig:
  5. def __init__(self, distutils_section='ALL', **kw):
  6. self._distutils_section = distutils_section
  7. self._conf_keys = kw
  8. self._conf = None
  9. self._hook_handler = None
  10. def dump_variable(self, name):
  11. conf_desc = self._conf_keys[name]
  12. hook, envvar, confvar, convert, append = conf_desc
  13. if not convert:
  14. convert = lambda x : x
  15. print('%s.%s:' % (self._distutils_section, name))
  16. v = self._hook_handler(name, hook)
  17. print(' hook : %s' % (convert(v),))
  18. if envvar:
  19. v = os.environ.get(envvar, None)
  20. print(' environ: %s' % (convert(v),))
  21. if confvar and self._conf:
  22. v = self._conf.get(confvar, (None, None))[1]
  23. print(' config : %s' % (convert(v),))
  24. def dump_variables(self):
  25. for name in self._conf_keys:
  26. self.dump_variable(name)
  27. def __getattr__(self, name):
  28. try:
  29. conf_desc = self._conf_keys[name]
  30. except KeyError:
  31. raise AttributeError(
  32. f"'EnvironmentConfig' object has no attribute '{name}'"
  33. ) from None
  34. return self._get_var(name, conf_desc)
  35. def get(self, name, default=None):
  36. try:
  37. conf_desc = self._conf_keys[name]
  38. except KeyError:
  39. return default
  40. var = self._get_var(name, conf_desc)
  41. if var is None:
  42. var = default
  43. return var
  44. def _get_var(self, name, conf_desc):
  45. hook, envvar, confvar, convert, append = conf_desc
  46. if convert is None:
  47. convert = lambda x: x
  48. var = self._hook_handler(name, hook)
  49. if envvar is not None:
  50. envvar_contents = os.environ.get(envvar)
  51. if envvar_contents is not None:
  52. envvar_contents = convert(envvar_contents)
  53. if var and append:
  54. if os.environ.get('NPY_DISTUTILS_APPEND_FLAGS', '1') == '1':
  55. var.extend(envvar_contents)
  56. else:
  57. # NPY_DISTUTILS_APPEND_FLAGS was explicitly set to 0
  58. # to keep old (overwrite flags rather than append to
  59. # them) behavior
  60. var = envvar_contents
  61. else:
  62. var = envvar_contents
  63. if confvar is not None and self._conf:
  64. if confvar in self._conf:
  65. source, confvar_contents = self._conf[confvar]
  66. var = convert(confvar_contents)
  67. return var
  68. def clone(self, hook_handler):
  69. ec = self.__class__(distutils_section=self._distutils_section,
  70. **self._conf_keys)
  71. ec._hook_handler = hook_handler
  72. return ec
  73. def use_distribution(self, dist):
  74. if isinstance(dist, Distribution):
  75. self._conf = dist.get_option_dict(self._distutils_section)
  76. else:
  77. self._conf = dist