Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

components.py 14KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. # -*- test-case-name: twisted.python.test.test_components -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Component architecture for Twisted, based on Zope3 components.
  6. Using the Zope3 API directly is strongly recommended. Everything
  7. you need is in the top-level of the zope.interface package, e.g.::
  8. from zope.interface import Interface, implementer
  9. class IFoo(Interface):
  10. pass
  11. @implementer(IFoo)
  12. class Foo:
  13. pass
  14. print(IFoo.implementedBy(Foo)) # True
  15. print(IFoo.providedBy(Foo())) # True
  16. L{twisted.python.components.registerAdapter} from this module may be used to
  17. add to Twisted's global adapter registry.
  18. L{twisted.python.components.proxyForInterface} is a factory for classes
  19. which allow access to only the parts of another class defined by a specified
  20. interface.
  21. """
  22. from io import StringIO
  23. from typing import Dict
  24. # zope3 imports
  25. from zope.interface import declarations, interface
  26. from zope.interface.adapter import AdapterRegistry
  27. # twisted imports
  28. from twisted.python import reflect
  29. # Twisted's global adapter registry
  30. globalRegistry = AdapterRegistry()
  31. # Attribute that registerAdapter looks at. Is this supposed to be public?
  32. ALLOW_DUPLICATES = 0
  33. def registerAdapter(adapterFactory, origInterface, *interfaceClasses):
  34. """Register an adapter class.
  35. An adapter class is expected to implement the given interface, by
  36. adapting instances implementing 'origInterface'. An adapter class's
  37. __init__ method should accept one parameter, an instance implementing
  38. 'origInterface'.
  39. """
  40. self = globalRegistry
  41. assert interfaceClasses, "You need to pass an Interface"
  42. global ALLOW_DUPLICATES
  43. # deal with class->interface adapters:
  44. if not isinstance(origInterface, interface.InterfaceClass):
  45. origInterface = declarations.implementedBy(origInterface)
  46. for interfaceClass in interfaceClasses:
  47. factory = self.registered([origInterface], interfaceClass)
  48. if factory is not None and not ALLOW_DUPLICATES:
  49. raise ValueError(f"an adapter ({factory}) was already registered.")
  50. for interfaceClass in interfaceClasses:
  51. self.register([origInterface], interfaceClass, "", adapterFactory)
  52. def getAdapterFactory(fromInterface, toInterface, default):
  53. """Return registered adapter for a given class and interface.
  54. Note that is tied to the *Twisted* global registry, and will
  55. thus not find adapters registered elsewhere.
  56. """
  57. self = globalRegistry
  58. if not isinstance(fromInterface, interface.InterfaceClass):
  59. fromInterface = declarations.implementedBy(fromInterface)
  60. factory = self.lookup1(fromInterface, toInterface) # type: ignore[attr-defined]
  61. if factory is None:
  62. factory = default
  63. return factory
  64. def _addHook(registry):
  65. """
  66. Add an adapter hook which will attempt to look up adapters in the given
  67. registry.
  68. @type registry: L{zope.interface.adapter.AdapterRegistry}
  69. @return: The hook which was added, for later use with L{_removeHook}.
  70. """
  71. lookup = registry.lookup1
  72. def _hook(iface, ob):
  73. factory = lookup(declarations.providedBy(ob), iface)
  74. if factory is None:
  75. return None
  76. else:
  77. return factory(ob)
  78. interface.adapter_hooks.append(_hook)
  79. return _hook
  80. def _removeHook(hook):
  81. """
  82. Remove a previously added adapter hook.
  83. @param hook: An object previously returned by a call to L{_addHook}. This
  84. will be removed from the list of adapter hooks.
  85. """
  86. interface.adapter_hooks.remove(hook)
  87. # add global adapter lookup hook for our newly created registry
  88. _addHook(globalRegistry)
  89. def getRegistry():
  90. """Returns the Twisted global
  91. C{zope.interface.adapter.AdapterRegistry} instance.
  92. """
  93. return globalRegistry
  94. # FIXME: deprecate attribute somehow?
  95. CannotAdapt = TypeError
  96. class Adapter:
  97. """I am the default implementation of an Adapter for some interface.
  98. This docstring contains a limerick, by popular demand::
  99. Subclassing made Zope and TR
  100. much harder to work with by far.
  101. So before you inherit,
  102. be sure to declare it
  103. Adapter, not PyObject*
  104. @cvar temporaryAdapter: If this is True, the adapter will not be
  105. persisted on the Componentized.
  106. @cvar multiComponent: If this adapter is persistent, should it be
  107. automatically registered for all appropriate interfaces.
  108. """
  109. # These attributes are used with Componentized.
  110. temporaryAdapter = 0
  111. multiComponent = 1
  112. def __init__(self, original):
  113. """Set my 'original' attribute to be the object I am adapting."""
  114. self.original = original
  115. def __conform__(self, interface):
  116. """
  117. I forward __conform__ to self.original if it has it, otherwise I
  118. simply return None.
  119. """
  120. if hasattr(self.original, "__conform__"):
  121. return self.original.__conform__(interface)
  122. return None
  123. def isuper(self, iface, adapter):
  124. """
  125. Forward isuper to self.original
  126. """
  127. return self.original.isuper(iface, adapter)
  128. class Componentized:
  129. """I am a mixin to allow you to be adapted in various ways persistently.
  130. I define a list of persistent adapters. This is to allow adapter classes
  131. to store system-specific state, and initialized on demand. The
  132. getComponent method implements this. You must also register adapters for
  133. this class for the interfaces that you wish to pass to getComponent.
  134. Many other classes and utilities listed here are present in Zope3; this one
  135. is specific to Twisted.
  136. """
  137. persistenceVersion = 1
  138. def __init__(self):
  139. self._adapterCache = {}
  140. def locateAdapterClass(self, klass, interfaceClass, default):
  141. return getAdapterFactory(klass, interfaceClass, default)
  142. def setAdapter(self, interfaceClass, adapterClass):
  143. """
  144. Cache a provider for the given interface, by adapting C{self} using
  145. the given adapter class.
  146. """
  147. self.setComponent(interfaceClass, adapterClass(self))
  148. def addAdapter(self, adapterClass, ignoreClass=0):
  149. """Utility method that calls addComponent. I take an adapter class and
  150. instantiate it with myself as the first argument.
  151. @return: The adapter instantiated.
  152. """
  153. adapt = adapterClass(self)
  154. self.addComponent(adapt, ignoreClass)
  155. return adapt
  156. def setComponent(self, interfaceClass, component):
  157. """
  158. Cache a provider of the given interface.
  159. """
  160. self._adapterCache[reflect.qual(interfaceClass)] = component
  161. def addComponent(self, component, ignoreClass=0):
  162. """
  163. Add a component to me, for all appropriate interfaces.
  164. In order to determine which interfaces are appropriate, the component's
  165. provided interfaces will be scanned.
  166. If the argument 'ignoreClass' is True, then all interfaces are
  167. considered appropriate.
  168. Otherwise, an 'appropriate' interface is one for which its class has
  169. been registered as an adapter for my class according to the rules of
  170. getComponent.
  171. """
  172. for iface in declarations.providedBy(component):
  173. if ignoreClass or (
  174. self.locateAdapterClass(self.__class__, iface, None)
  175. == component.__class__
  176. ):
  177. self._adapterCache[reflect.qual(iface)] = component
  178. def unsetComponent(self, interfaceClass):
  179. """Remove my component specified by the given interface class."""
  180. del self._adapterCache[reflect.qual(interfaceClass)]
  181. def removeComponent(self, component):
  182. """
  183. Remove the given component from me entirely, for all interfaces for which
  184. it has been registered.
  185. @return: a list of the interfaces that were removed.
  186. """
  187. l = []
  188. for k, v in list(self._adapterCache.items()):
  189. if v is component:
  190. del self._adapterCache[k]
  191. l.append(reflect.namedObject(k))
  192. return l
  193. def getComponent(self, interface, default=None):
  194. """Create or retrieve an adapter for the given interface.
  195. If such an adapter has already been created, retrieve it from the cache
  196. that this instance keeps of all its adapters. Adapters created through
  197. this mechanism may safely store system-specific state.
  198. If you want to register an adapter that will be created through
  199. getComponent, but you don't require (or don't want) your adapter to be
  200. cached and kept alive for the lifetime of this Componentized object,
  201. set the attribute 'temporaryAdapter' to True on your adapter class.
  202. If you want to automatically register an adapter for all appropriate
  203. interfaces (with addComponent), set the attribute 'multiComponent' to
  204. True on your adapter class.
  205. """
  206. k = reflect.qual(interface)
  207. if k in self._adapterCache:
  208. return self._adapterCache[k]
  209. else:
  210. adapter = interface.__adapt__(self)
  211. if adapter is not None and not (
  212. hasattr(adapter, "temporaryAdapter") and adapter.temporaryAdapter
  213. ):
  214. self._adapterCache[k] = adapter
  215. if hasattr(adapter, "multiComponent") and adapter.multiComponent:
  216. self.addComponent(adapter)
  217. if adapter is None:
  218. return default
  219. return adapter
  220. def __conform__(self, interface):
  221. return self.getComponent(interface)
  222. class ReprableComponentized(Componentized):
  223. def __init__(self):
  224. Componentized.__init__(self)
  225. def __repr__(self) -> str:
  226. from pprint import pprint
  227. sio = StringIO()
  228. pprint(self._adapterCache, sio)
  229. return sio.getvalue()
  230. def proxyForInterface(iface, originalAttribute="original"):
  231. """
  232. Create a class which proxies all method calls which adhere to an interface
  233. to another provider of that interface.
  234. This function is intended for creating specialized proxies. The typical way
  235. to use it is by subclassing the result::
  236. class MySpecializedProxy(proxyForInterface(IFoo)):
  237. def someInterfaceMethod(self, arg):
  238. if arg == 3:
  239. return 3
  240. return self.original.someInterfaceMethod(arg)
  241. @param iface: The Interface to which the resulting object will conform, and
  242. which the wrapped object must provide.
  243. @param originalAttribute: name of the attribute used to save the original
  244. object in the resulting class. Default to C{original}.
  245. @type originalAttribute: C{str}
  246. @return: A class whose constructor takes the original object as its only
  247. argument. Constructing the class creates the proxy.
  248. """
  249. def __init__(self, original):
  250. setattr(self, originalAttribute, original)
  251. contents: Dict[str, object] = {"__init__": __init__}
  252. for name in iface:
  253. contents[name] = _ProxyDescriptor(name, originalAttribute)
  254. proxy = type(f"(Proxy for {reflect.qual(iface)})", (object,), contents)
  255. # mypy-zope declarations.classImplements only works when passing
  256. # a concrete class type
  257. declarations.classImplements(proxy, iface) # type: ignore[misc]
  258. return proxy
  259. class _ProxiedClassMethod:
  260. """
  261. A proxied class method.
  262. @ivar methodName: the name of the method which this should invoke when
  263. called.
  264. @type methodName: L{str}
  265. @ivar __name__: The name of the method being proxied (the same as
  266. C{methodName}).
  267. @type __name__: L{str}
  268. @ivar originalAttribute: name of the attribute of the proxy where the
  269. original object is stored.
  270. @type originalAttribute: L{str}
  271. """
  272. def __init__(self, methodName, originalAttribute):
  273. self.methodName = self.__name__ = methodName
  274. self.originalAttribute = originalAttribute
  275. def __call__(self, oself, *args, **kw):
  276. """
  277. Invoke the specified L{methodName} method of the C{original} attribute
  278. for proxyForInterface.
  279. @param oself: an instance of a L{proxyForInterface} object.
  280. @return: the result of the underlying method.
  281. """
  282. original = getattr(oself, self.originalAttribute)
  283. actualMethod = getattr(original, self.methodName)
  284. return actualMethod(*args, **kw)
  285. class _ProxyDescriptor:
  286. """
  287. A descriptor which will proxy attribute access, mutation, and
  288. deletion to the L{_ProxyDescriptor.originalAttribute} of the
  289. object it is being accessed from.
  290. @ivar attributeName: the name of the attribute which this descriptor will
  291. retrieve from instances' C{original} attribute.
  292. @type attributeName: C{str}
  293. @ivar originalAttribute: name of the attribute of the proxy where the
  294. original object is stored.
  295. @type originalAttribute: C{str}
  296. """
  297. def __init__(self, attributeName, originalAttribute):
  298. self.attributeName = attributeName
  299. self.originalAttribute = originalAttribute
  300. def __get__(self, oself, type=None):
  301. """
  302. Retrieve the C{self.attributeName} property from I{oself}.
  303. """
  304. if oself is None:
  305. return _ProxiedClassMethod(self.attributeName, self.originalAttribute)
  306. original = getattr(oself, self.originalAttribute)
  307. return getattr(original, self.attributeName)
  308. def __set__(self, oself, value):
  309. """
  310. Set the C{self.attributeName} property of I{oself}.
  311. """
  312. original = getattr(oself, self.originalAttribute)
  313. setattr(original, self.attributeName, value)
  314. def __delete__(self, oself):
  315. """
  316. Delete the C{self.attributeName} property of I{oself}.
  317. """
  318. original = getattr(oself, self.originalAttribute)
  319. delattr(original, self.attributeName)
  320. __all__ = [
  321. "registerAdapter",
  322. "getAdapterFactory",
  323. "Adapter",
  324. "Componentized",
  325. "ReprableComponentized",
  326. "getRegistry",
  327. "proxyForInterface",
  328. ]