A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
3.4 KiB

  1. # Copyright (C) 2009-2024 Ben Kurtovic <ben.kurtovic@gmail.com>
  2. #
  3. # Permission is hereby granted, free of charge, to any person obtaining a copy
  4. # of this software and associated documentation files (the "Software"), to deal
  5. # in the Software without restriction, including without limitation the rights
  6. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. # copies of the Software, and to permit persons to whom the Software is
  8. # furnished to do so, subject to the following conditions:
  9. #
  10. # The above copyright notice and this permission notice shall be included in
  11. # all copies or substantial portions of the Software.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. # SOFTWARE.
  20. """
  21. Implements a hierarchy of importing classes as defined in `PEP 302
  22. <https://www.python.org/dev/peps/pep-0302/>`_ to load modules in a safe yet lazy
  23. manner, so that they can be referred to by name but are not actually loaded
  24. until they are used (i.e. their attributes are read or modified).
  25. """
  26. import importlib
  27. import sys
  28. from threading import RLock
  29. from types import ModuleType
  30. __all__ = ["LazyImporter"]
  31. _real_get = ModuleType.__getattribute__
  32. _lazy_init_lock = RLock()
  33. def _create_failing_get(exc):
  34. def _fail(self, attr):
  35. raise exc
  36. return _fail
  37. def _mock_get(self, attr):
  38. with _real_get(self, "_lock"):
  39. if _real_get(self, "_unloaded"):
  40. type(self)._unloaded = False
  41. try:
  42. importlib.reload(self)
  43. except ImportError as exc:
  44. type(self).__getattribute__ = _create_failing_get(exc)
  45. del type(self)._lock
  46. raise
  47. type(self).__getattribute__ = _real_get
  48. del type(self)._lock
  49. return _real_get(self, attr)
  50. class _LazyModule(type):
  51. def __new__(cls, name):
  52. with _lazy_init_lock:
  53. if name not in sys.modules:
  54. attributes = {
  55. "__name__": name,
  56. "__getattribute__": _mock_get,
  57. "_unloaded": True,
  58. "_lock": RLock(),
  59. }
  60. parents = (ModuleType,)
  61. klass = type.__new__(cls, "module", parents, attributes)
  62. sys.modules[name] = klass(name)
  63. if "." in name: # Also ensure the parent exists
  64. _LazyModule(name.rsplit(".", 1)[0])
  65. return sys.modules[name]
  66. class LazyImporter:
  67. """An importer for modules that are loaded lazily.
  68. This inserts itself into :py:data:`sys.meta_path`, storing a dictionary of
  69. :py:class:`_LazyModule`\ s (which is added to with :py:meth:`new`).
  70. """
  71. def __init__(self):
  72. self._modules = {}
  73. sys.meta_path.append(self)
  74. def new(self, name):
  75. module = _LazyModule(name)
  76. self._modules[name] = module
  77. return module
  78. def find_module(self, fullname, path=None):
  79. if fullname in self._modules and fullname not in sys.modules:
  80. return self
  81. def load_module(self, fullname):
  82. return self._modules.pop(fullname)