• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

zopefoundation / zope.component / 3829079989

pending completion
3829079989

push

github

Jens Vagelpohl
- prepare release 5.1.0

467 of 489 branches covered (95.5%)

Branch coverage included in aggregate %.

4620 of 4625 relevant lines covered (99.89%)

1.0 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.55
/src/zope/component/interfaces.py
1
############################################################################
2
#
3
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
4
# All Rights Reserved.
5
#
6
# This software is subject to the provisions of the Zope Public License,
7
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
8
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
9
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
10
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
11
# FOR A PARTICULAR PURPOSE.
12
#
13
############################################################################
14
"""
1✔
15
Component and Component Architecture Interfaces
16

17
The `IComponentArchitecture` and `IComponentRegistrationConvenience` interfaces
18
are provided by `zope.component` directly.
19
"""
20
from zope.interface import Attribute
1✔
21
from zope.interface import Interface
1✔
22

23
# pylint:disable=inherit-non-class,no-self-argument,no-method-argument
24

25
class IComponentArchitecture(Interface):
1✔
26
    """The Component Architecture is defined by two key components: Adapters
27
    and Utiltities. Both are managed by site managers. All other components
28
    build on top of them.
29
    """
30
    # Site Manager API
31

32
    def getGlobalSiteManager():
1✔
33
        """Return the global site manager.
34

35
        This function should never fail and always return an object that
36
        provides `zope.interface.interfaces.IComponents`.
37
        """
38

39
    def getSiteManager(context=None):
1✔
40
        """Get the nearest site manager in the given context.
41

42
        If *context* is `None`, return the global site manager.
43

44
        If the *context* is not `None`, it is expected that an adapter
45
        from the *context* to
46
        :mod:`zope.interface.interfaces.IComponentLookup` can be
47
        found. If no adapter is found, a
48
        `~zope.interface.interfaces.ComponentLookupError` is raised.
49
        """
50

51
    # Utility API
52

53
    def getUtility(interface, name='', context=None):
1✔
54
        """Get the utility that provides interface
55

56
        Returns the nearest utility to the context that implements the
57
        specified interface. If one is not found, raises
58
        `~zope.interface.interfaces.ComponentLookupError`.
59
        """
60

61
    def queryUtility(interface, name='', default=None, context=None):
1✔
62
        """Look for the utility that provides *interface*
63

64
        Returns the nearest utility to the *context* that implements the
65
        specified interface. If one is not found, returns *default*.
66
        """
67

68
    def queryNextUtility(context, interface, name='', default=None):
1✔
69
        """Query for the next available utility.
70

71
        Find the next available utility providing *interface* and having the
72
        specified name. If no utility was found, return the specified *default*
73
        value.
74
        """
75

76
    def getNextUtility(context, interface, name=''):
1✔
77
        """Get the next available utility.
78

79
        If no utility was found, a `~zope.interface.interfaces.ComponentLookupError` is raised.
80
        """
81

82
    def getUtilitiesFor(interface, context=None):
1✔
83
        """Return the utilities that provide an interface
84

85
        An iterable of utility name-value pairs is returned.
86
        """
87

88
    def getAllUtilitiesRegisteredFor(interface, context=None):
1✔
89
        """Return all registered utilities for an interface
90

91
        This includes overridden utilities.
92

93
        An iterable of utility instances is returned.  No names are
94
        returned.
95
        """
96

97
    # Adapter API
98

99
    def getAdapter(object,
1✔
100
                   interface=Interface, name=u'',
101
                   context=None):
102
        """Get a named adapter to an interface for an object
103

104
        Returns an adapter that can adapt object to interface.  If a matching
105
        adapter cannot be found, raises `~zope.interface.interfaces.ComponentLookupError`.
106
        """
107

108
    def getAdapterInContext(object, interface, context):
1✔
109
        """Get a special adapter to an interface for an object
110

111
        .. note::
112
            This method should only be used if a custom context
113
            needs to be provided to provide custom component
114
            lookup. Otherwise, call the interface, as in::
115

116
               interface(object)
117

118
        Returns an adapter that can adapt object to interface. If a
119
        matching adapter cannot be found, raises
120
        `~zope.interface.interfaces.ComponentLookupError`.
121

122
        If the object has a ``__conform__`` method, this method will be
123
        called with the requested interface. If the method returns a
124
        non-None value, that value will be returned. Otherwise, if the
125
        object already implements the interface, the object will be
126
        returned.
127
        """
128

129
    def getMultiAdapter(objects,
1✔
130
                        interface=Interface, name='',
131
                        context=None):
132
        """Look for a multi-adapter to an *interface* for an *objects*
133

134
        Returns a multi-adapter that can adapt *objects* to *interface*.
135
        If a matching adapter cannot be found, raises
136
        `~zope.interface.interfaces.ComponentLookupError`.
137

138
        The name consisting of an empty string is reserved for unnamed
139
        adapters. The unnamed adapter methods will often call the
140
        named adapter methods with an empty string for a name.
141
        """
142

143
    def queryAdapter(object, interface=Interface, name=u'',
1✔
144
                     default=None, context=None):
145
        """Look for a named adapter to an interface for an object
146

147
        Returns an adapter that can adapt object to interface. If a
148
        matching adapter cannot be found, returns the default.
149
        """
150

151
    def queryAdapterInContext(object, interface, context, default=None):
1✔
152
        """
153
        Look for a special adapter to an interface for an object
154

155
        .. note::
156

157
            This method should only be used if a custom context
158
            needs to be provided to provide custom component lookup.
159
            Otherwise, call the interface, as in::
160

161
                interface(object, default)
162

163
        Returns an adapter that can adapt object to interface. If a
164
        matching adapter cannot be found, returns the default.
165

166
        If the object has a ``__conform__`` method, this method will be
167
        called with the requested interface. If the method returns a
168
        non-None value, that value will be returned. Otherwise, if the
169
        object already implements the interface, the object will be
170
        returned.
171
        """
172

173
    def queryMultiAdapter(objects,
1✔
174
                          interface=Interface, name=u'',
175
                          default=None,
176
                          context=None):
177
        """Look for a multi-adapter to an interface for objects
178

179
        Returns a multi-adapter that can adapt objects to interface.  If a
180
        matching adapter cannot be found, returns the default.
181

182
        The name consisting of an empty string is reserved for unnamed
183
        adapters. The unnamed adapter methods will often call the
184
        named adapter methods with an empty string for a name.
185
        """
186

187
    def getAdapters(objects, provided, context=None):
1✔
188
        """
189
        Look for all matching adapters to a provided interface for
190
        objects
191

192
        Return a list of adapters that match. If an adapter is named,
193
        only the most specific adapter of a given name is returned.
194
        """
195

196
    def subscribers(required, provided, context=None):
1✔
197
        """Get subscribers
198

199
        Subscribers are returned that provide the provided interface
200
        and that depend on and are computed from the sequence of
201
        required objects.
202
        """
203

204
    def handle(*objects):
1✔
205
        """Call all of the handlers for the given objects
206

207
        Handlers are subscription adapter factories that don't produce
208
        anything. They do all of their work when called. Handlers are
209
        typically used to handle events.
210
        """
211

212
    def adapts(*interfaces):
1✔
213
        """
214
        Declare that a class adapts the given interfaces.
215

216
        This function can only be used in a class definition.
217

218
        (TODO, allow classes to be passed as well as interfaces.)
219
        """
220

221
    # Factory service
222

223
    def createObject(factory_name, *args, **kwargs):
1✔
224
        """Create an object using a factory
225

226
        Finds the named factory in the current site and calls it with
227
        the given arguments. If a matching factory cannot be found
228
        raises `~zope.interface.interfaces.ComponentLookupError`.
229
        Returns the created object.
230

231
        A context keyword argument can be provided to cause the
232
        factory to be looked up in a location other than the current
233
        site. (Of course, this means that it is impossible to pass a
234
        keyword argument named "context" to the factory.
235
        """
236

237
    def getFactoryInterfaces(name, context=None):
1✔
238
        """Get interfaces implemented by a factory
239

240
        Finds the factory of the given name that is nearest to the
241
        context, and returns the interface or interface tuple that
242
        object instances created by the named factory will implement.
243
        """
244

245
    def getFactoriesFor(interface, context=None):
1✔
246
        """Return a tuple (name, factory) of registered factories that
247
        create objects which implement the given interface.
248
        """
249

250

251
class IRegistry(Interface):
1✔
252
    """Object that supports component registry
253
    """
254

255
    def registrations():
1✔
256
        """Return an iterable of component registrations
257
        """
258

259
class IComponentRegistrationConvenience(Interface):
1✔
260
    """API for registering components.
261

262
    .. caution::
263
        This API should only be used from test or
264
        application-setup code. This api shouldn't be used by regular
265
        library modules, as component registration is a configuration
266
        activity.
267
    """
268

269
    def provideUtility(component, provides=None, name=u''):
1✔
270
        """Register a utility globally
271

272
        A utility is registered to provide an interface with a
273
        name. If a component provides only one interface, then the
274
        provides argument can be omitted and the provided interface
275
        will be used. (In this case, provides argument can still be
276
        provided to provide a less specific interface.)
277
        """
278

279
    def provideAdapter(factory, adapts=None, provides=None, name=u''):
1✔
280
        """Register an adapter globally
281

282
        An adapter is registered to provide an interface with a name
283
        for some number of object types. If a factory implements only
284
        one interface, then the provides argument can be omitted and
285
        the provided interface will be used. (In this case, a provides
286
        argument can still be provided to provide a less specific
287
        interface.)
288

289
        If the factory has an adapts declaration, then the adapts
290
        argument can be omitted and the declaration will be used.  (An
291
        adapts argument can be provided to override the declaration.)
292
        """
293

294
    def provideSubscriptionAdapter(factory, adapts=None, provides=None):
1✔
295
        """Register a subscription adapter
296

297
        A subscription adapter is registered to provide an interface
298
        for some number of object types. If a factory implements only
299
        one interface, then the provides argument can be omitted and
300
        the provided interface will be used. (In this case, a provides
301
        argument can still be provided to provide a less specific
302
        interface.)
303

304
        If the factory has an adapts declaration, then the adapts
305
        argument can be omitted and the declaration will be used.  (An
306
        adapts argument can be provided to override the declaration.)
307
        """
308

309
    def provideHandler(handler, adapts=None):
1✔
310
        """Register a handler
311

312
        Handlers are subscription adapter factories that don't produce
313
        anything.  They do all of their work when called.  Handlers
314
        are typically used to handle events.
315

316
        If the handler has an adapts declaration, then the adapts
317
        argument can be omitted and the declaration will be used.  (An
318
        adapts argument can be provided to override the declaration.)
319
        """
320

321

322
class IPossibleSite(Interface):
1✔
323
    """An object that could be a site.
324
    """
325

326
    def setSiteManager(sitemanager):
1✔
327
        """Sets the site manager for this object.
328
        """
329

330
    def getSiteManager():
1✔
331
        """Returns the site manager contained in this object.
332

333
        If there isn't a site manager, raise a component lookup.
334
        """
335

336
class ISite(IPossibleSite):
1✔
337
    """Marker interface to indicate that we have a site"""
338

339
class Misused(Exception):
1✔
340
    """A component is being used (registered) for the wrong interface."""
341

342

343
class IFactory(Interface):
1✔
344
    """A factory is responsible for creating other components."""
345

346
    title = Attribute("The factory title.")
1✔
347

348
    description = Attribute("A brief description of the factory.")
1✔
349

350
    def __call__(*args, **kw):
1✔
351
        """Return an instance of the objects we're a factory for."""
352

353

354
    def getInterfaces():
1✔
355
        """Get the interfaces implemented by the factory
356

357
        Return the interface(s), as an instance of Implements, that objects
358
        created by this factory will implement. If the callable's Implements
359
        instance cannot be created, an empty Implements instance is returned.
360
        """
361

362

363
# Internal helpers
364

365
def _inherits_docs(func, iface):
1✔
366
    doc = iface[func.__name__].__doc__
1✔
367

368
    # doc can be None if the interpreter drops all docstrings when the
369
    # environment variable PYTHONOPTIMIZE is set 2.
370
    if not doc:
1!
371
        return func
×
372

373
    # By adding the ..seealso:: we get a link from our overview page
374
    # to the specific narrative place where the function is described, because
375
    # our overview page uses :noindex:
376
    doc += "\n        .. seealso::"
1✔
377
    doc += "\n           Function `~zope.component.%s` for notes, and " % (func.__name__,)
1✔
378
    doc += "\n           `~zope.component.interfaces.%s` for the defining interface." % (iface.__name__,)
1✔
379
    doc += "\n"
1✔
380
    func.__doc__ = doc
1✔
381
    return func
1✔
382

383
def inherits_arch_docs(func):
1✔
384
    return _inherits_docs(func, IComponentArchitecture)
1✔
385

386
def inherits_reg_docs(func):
1✔
387
    return _inherits_docs(func, IComponentRegistrationConvenience)
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc