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.

102 lines
3.5 KiB

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