Utility Registration APIs

zope.component.provideUtility(component, provides=None, name=u'')[source]

Register a utility globally

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

See also

Function provideUtility for notes, and IComponentRegistrationConvenience for the defining interface.

zope.component.getUtility(interface, name='', context=None)[source]

Get the utility that provides interface

Returns the nearest utility to the context that implements the specified interface. If one is not found, raises ComponentLookupError.

See also

Function getUtility for notes, and IComponentArchitecture for the defining interface.

zope.component.queryUtility(interface, name='', default=None, context=None)[source]

Look for the utility that provides interface

Returns the nearest utility to the context that implements the specified interface. If one is not found, returns default.

See also

Function queryUtility for notes, and IComponentArchitecture for the defining interface.

Utilities are components that simply provide an interface. They are instantiated at the time or before they are registered. Here we test the simple query interface.

Before we register any utility, there is no utility available, of course. The pure instatiation of an object does not make it a utility. If you do not specify a default, you get a ComponentLookupError.

>>> from zope.component import getUtility
>>> from zope.component import queryUtility
>>> from zope.component.tests.examples import I1
>>> getUtility(I1) 
Traceback (most recent call last):
ComponentLookupError: \
(<InterfaceClass zope.component.tests.examples.I1>, '')

Otherwise, you get the default:

>>> queryUtility(I1, default='<default>')

Now we declare ob to be the utility providing I1:

>>> ob = object()
>>> from zope.component import getGlobalSiteManager
>>> getGlobalSiteManager().registerUtility(ob, I1)

Now the component is available:

>>> getUtility(I1) is ob
>>> queryUtility(I1) is ob

Named Utilities

Registering a utility without a name does not mean that it is available when looking for the utility with a name:

>>> getUtility(I1, name='foo')
Traceback (most recent call last):
(<InterfaceClass zope.component.tests.examples.I1>, 'foo')

>>> queryUtility(I1, name='foo', default='<default>')

Registering the utility under the correct name makes it available:

>>> ob2 = object()
>>> getGlobalSiteManager().registerUtility(ob2, I1, name='foo')
>>> getUtility(I1, 'foo') is ob2
>>> queryUtility(I1, 'foo') is ob2

Querying Multiple Utilities

zope.component.getUtilitiesFor(interface, context=None)[source]

Return the utilities that provide an interface

An iterable of utility name-value pairs is returned.

See also

Function getUtilitiesFor for notes, and IComponentArchitecture for the defining interface.

zope.component.getAllUtilitiesRegisteredFor(interface, context=None)[source]

Return all registered utilities for an interface

This includes overridden utilities.

An iterable of utility instances is returned. No names are returned.

See also

Function getAllUtilitiesRegisteredFor for notes, and IComponentArchitecture for the defining interface.

Sometimes it may be useful to query all utilities, both anonymous and named for a given interface. The getUtilitiesFor() API returns a sequence of (name, utility) tuples, where name is the empty string for the anonymous utility:

>>> from zope.component import getUtilitiesFor
>>> tuples = list(getUtilitiesFor(I1))
>>> len(tuples)
>>> ('', ob) in tuples
>>> ('foo', ob2) in tuples

The getAllUtilitiesRegisteredFor() API returns utilities that have been registered for a particular interface. Utilities providing a derived interface are also listed.

>>> from zope.interface import implementer
>>> from zope.component.tests.examples import Comp
>>> from zope.component.tests.examples import I2
>>> from zope.component.tests.examples import Ob
>>> class I11(I1):
...     pass

>>> @implementer(I11)
... class Ob11(Ob):
...     pass

>>> ob11 = Ob11()
>>> ob_bob = Ob()

Now we register the new utilities:

>>> from zope.component import getGlobalSiteManager
>>> gsm = getGlobalSiteManager()
>>> gsm.registerUtility(ob, I1)
>>> gsm.registerUtility(ob11, I11)
>>> gsm.registerUtility(ob_bob, I1, name='bob')
>>> gsm.registerUtility(Comp(2), I2)

We can now get all the utilities that provide interface I1:

>>> from zope.component import getAllUtilitiesRegisteredFor
>>> uts = list(getAllUtilitiesRegisteredFor(I1))
>>> len(uts)
>>> ob in uts
>>> ob2 in uts
>>> ob_bob in uts
>>> ob11 in uts

Note that getAllUtilitiesRegisteredFor() does not return the names of the utilities.

Delegated Utility Lookup

zope.component.getNextUtility(context, interface, name='')[source]

Get the next available utility.

If no utility was found, a ComponentLookupError is raised.

See also

Function getNextUtility for notes, and IComponentArchitecture for the defining interface.

zope.component.queryNextUtility(context, interface, name='', default=None)[source]

Query for the next available utility.

Find the next available utility providing interface and having the specified name. If no utility was found, return the specified default value.

See also

Function queryNextUtility for notes, and IComponentArchitecture for the defining interface.

It is common for a utility to delegate its answer to a utility providing the same interface in one of the component registry’s bases. Let’s first create a global utility:

>>> from zope.interface import Interface
>>> from zope.interface import implementer
>>> class IMyUtility(Interface):
...     pass

>>> from zope.component.tests.examples import ConformsToIComponentLookup
>>> @implementer(IMyUtility)
... class MyUtility(ConformsToIComponentLookup):
...     def __init__(self, id, sm):
...         self.id = id
...         self.sitemanager = sm
...     def __repr__(self):
...         return "%s('%s')" % (self.__class__.__name__, self.id)

>>> gutil = MyUtility('global', gsm)
>>> gsm.registerUtility(gutil, IMyUtility, 'myutil')

Now, let’s create two registries and set up the bases hierarchy:

>>> from zope.interface.registry import Components
>>> sm1 = Components('sm1', bases=(gsm, ))
>>> sm1_1 = Components('sm1_1', bases=(sm1, ))

Now we create two utilities and insert them in our folder hierarchy:

>>> from zope.interface.interfaces import IComponentLookup
>>> util1 = MyUtility('one', sm1)
>>> sm1.registerUtility(util1, IMyUtility, 'myutil')
>>> IComponentLookup(util1) is sm1

>>> util1_1 = MyUtility('one-one', sm1_1)
>>> sm1_1.registerUtility(util1_1, IMyUtility, 'myutil')
>>> IComponentLookup(util1_1) is sm1_1

Now, if we ask util1_1 for its next available utility we get the one utility:

>>> from zope.component import getNextUtility
>>> getNextUtility(util1_1, IMyUtility, 'myutil')

Next we ask util1 for its next utility and we should get the global version:

>>> getNextUtility(util1, IMyUtility, 'myutil')

However, if we ask the global utility for the next one, an error is raised

>>> getNextUtility(gutil, IMyUtility,
...                     'myutil') 
Traceback (most recent call last):
No more utilities for <InterfaceClass zope.component.tests.examples.IMyUtility>,
'myutil' have been found.

You can also use queryNextUtility and specify a default:

>>> from zope.component import queryNextUtility
>>> queryNextUtility(gutil, IMyUtility, 'myutil', 'default')

Let’s now ensure that the function also works with multiple registries. First we create another base registry:

>>> myregistry = Components()

We now set up another utility into that registry:

>>> custom_util = MyUtility('my_custom_util', myregistry)
>>> myregistry.registerUtility(custom_util, IMyUtility, 'my_custom_util')

We add it as a base to the local site manager:

>>> sm1.__bases__ = (myregistry,) + sm1.__bases__

Both the myregistry and global utilities should be available:

>>> queryNextUtility(sm1, IMyUtility, 'my_custom_util')
>>> queryNextUtility(sm1, IMyUtility, 'myutil')

Note, if the context cannot be converted to a site manager, the default is retruned:

>>> queryNextUtility(object(), IMyUtility, 'myutil', 'default')