File: narr.rst

package info (click to toggle)
zope.component 4.3.0-3
  • links: PTS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 780 kB
  • sloc: python: 5,600; makefile: 130
file content (449 lines) | stat: -rw-r--r-- 12,647 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
Zope Component Architecture
===========================

This package, together with `zope.interface`, provides facilities for
defining, registering and looking up components.  There are two basic
kinds of components: adapters and utilities.

Utilities
---------

Utilities are just components that provide an interface and that are
looked up by an interface and a name.  Let's look at a trivial utility
definition:

.. doctest::

   >>> from zope import interface

   >>> class IGreeter(interface.Interface):
   ...     def greet():
   ...         "say hello"

   >>> class Greeter:
   ...     interface.implements(IGreeter)
   ...
   ...     def __init__(self, other="world"):
   ...         self.other = other
   ...
   ...     def greet(self):
   ...         print "Hello", self.other

We can register an instance this class using `provideUtility` [1]_:

.. doctest::

   >>> from zope import component
   >>> greet = Greeter('bob')
   >>> component.provideUtility(greet, IGreeter, 'robert')

In this example we registered the utility as providing the `IGreeter`
interface with a name of 'bob'. We can look the interface up with
either `queryUtility` or `getUtility`:

.. doctest::

   >>> component.queryUtility(IGreeter, 'robert').greet()
   Hello bob

   >>> component.getUtility(IGreeter, 'robert').greet()
   Hello bob

`queryUtility` and `getUtility` differ in how failed lookups are handled:

.. doctest::

   >>> component.queryUtility(IGreeter, 'ted')
   >>> component.queryUtility(IGreeter, 'ted', 42)
   42
   >>> component.getUtility(IGreeter, 'ted')
   ... # doctest: +ELLIPSIS
   Traceback (most recent call last):
   ...
   ComponentLookupError: (<InterfaceClass ...IGreeter>, 'ted')

If a component provides only one interface, as in the example above,
then we can omit the provided interface from the call to `provideUtility`:

.. doctest::

   >>> ted = Greeter('ted')
   >>> component.provideUtility(ted, name='ted')
   >>> component.queryUtility(IGreeter, 'ted').greet()
   Hello ted

The name defaults to an empty string:

.. doctest::

   >>> world = Greeter()
   >>> component.provideUtility(world)
   >>> component.queryUtility(IGreeter).greet()
   Hello world

Adapters
--------

Adapters are components that are computed from other components to
adapt them to some interface.  Because they are computed from other
objects, they are provided as factories, usually classes.  Here, we'll
create a greeter for persons, so we can provide personalized greetings
for different people:

.. doctest::

   >>> class IPerson(interface.Interface):
   ...     name = interface.Attribute("Name")

   >>> class PersonGreeter:
   ...
   ...     component.adapts(IPerson)
   ...     interface.implements(IGreeter)
   ...
   ...     def __init__(self, person):
   ...         self.person = person
   ...
   ...     def greet(self):
   ...         print "Hello", self.person.name

The class defines a constructor that takes an argument for every
object adapted.

We used `component.adapts` to declare what we adapt.  We can find
out if an object declares that it adapts anything using adaptedBy:

.. doctest::

   >>> list(component.adaptedBy(PersonGreeter)) == [IPerson]
   True

If an object makes no declaration, then None is returned:

.. doctest::

   >>> component.adaptedBy(Greeter()) is None
   True


If we declare the interfaces adapted and if we provide only one
interface, as in the example above, then we can provide the adapter
very simply [1]_:

.. doctest::

   >>> component.provideAdapter(PersonGreeter)

For adapters that adapt a single interface to a single interface
without a name, we can get the adapter by simply calling the
interface:

.. doctest::

   >>> class Person:
   ...     interface.implements(IPerson)
   ...
   ...     def __init__(self, name):
   ...         self.name = name

   >>> IGreeter(Person("Sally")).greet()
   Hello Sally

We can also provide arguments to be very specific about what
how to register the adapter.

.. doctest::

   >>> class BobPersonGreeter(PersonGreeter):
   ...     name = 'Bob'
   ...     def greet(self):
   ...         print "Hello", self.person.name, "my name is", self.name

   >>> component.provideAdapter(
   ...                        BobPersonGreeter, [IPerson], IGreeter, 'bob')

The arguments can also be provided as keyword arguments:

.. doctest::

   >>> class TedPersonGreeter(BobPersonGreeter):
   ...     name = "Ted"

   >>> component.provideAdapter(
   ...     factory=TedPersonGreeter, adapts=[IPerson],
   ...     provides=IGreeter, name='ted')

For named adapters, use `queryAdapter`, or `getAdapter`:

.. doctest::

   >>> component.queryAdapter(Person("Sally"), IGreeter, 'bob').greet()
   Hello Sally my name is Bob

   >>> component.getAdapter(Person("Sally"), IGreeter, 'ted').greet()
   Hello Sally my name is Ted

If an adapter can't be found, `queryAdapter` returns a default value
and `getAdapter` raises an error:

.. doctest::

   >>> component.queryAdapter(Person("Sally"), IGreeter, 'frank')
   >>> component.queryAdapter(Person("Sally"), IGreeter, 'frank', 42)
   42
   >>> component.getAdapter(Person("Sally"), IGreeter, 'frank')
   ... # doctest: +ELLIPSIS
   Traceback (most recent call last):
   ...
   ComponentLookupError: (...Person...>, <...IGreeter>, 'frank')

Adapters can adapt multiple objects:

.. doctest::

   >>> class TwoPersonGreeter:
   ...
   ...     component.adapts(IPerson, IPerson)
   ...     interface.implements(IGreeter)
   ...
   ...     def __init__(self, person, greeter):
   ...         self.person = person
   ...         self.greeter = greeter
   ...
   ...     def greet(self):
   ...         print "Hello", self.person.name
   ...         print "my name is", self.greeter.name

   >>> component.provideAdapter(TwoPersonGreeter)

Note that the declaration-order of the Interfaces beeing adapted to is
important for adapter look up. It must be the the same as the order of
parameters given to the adapter and used to query the adapter. This is
especially the case when different Interfaces are adapt to (opposed to
this example).

To look up a multi-adapter, use either `queryMultiAdapter` or
`getMultiAdapter`:

.. doctest::

   >>> component.queryMultiAdapter((Person("Sally"), Person("Bob")),
   ...                                  IGreeter).greet()
   Hello Sally
   my name is Bob

Adapters need not be classes.  Any callable will do.  We use the
adapter decorator to declare that a callable object adapts some interfaces
(or classes):

.. doctest::

   >>> class IJob(interface.Interface):
   ...     "A job"

   >>> @interface.implementer(IJob)
   ... class Job:
   ...     pass
   >>> @interface.implementer(IJob)
   ... @component.adapter(IPerson)
   ... def personJob(person):
   ...     return getattr(person, 'job', None)


In this example, the personJob function simply returns the person's
`job` attribute if present, or None if it's not present.  An adapter
factory can return None to indicate that adaptation wasn't possible.
Let's register this adapter and try it out:

.. doctest::

   >>> component.provideAdapter(personJob)
   >>> sally = Person("Sally")
   >>> IJob(sally) # doctest: +ELLIPSIS
   Traceback (most recent call last):
   ...
   TypeError: ('Could not adapt', ...

The adaptation failed because sally didn't have a job.  Let's give her
one:

.. doctest::

   >>> job = Job()
   >>> sally.job = job
   >>> IJob(sally) is job
   True

Subscription Adapters
---------------------

Unlike regular adapters, subscription adapters are used when we want
all of the adapters that adapt an object to a particular adapter.

Consider a validation problem.  We have objects and we want to assess
whether they meet some sort of standards.  We define a validation
interface:

.. doctest::

   >>> class IValidate(interface.Interface):
   ...     def validate(ob):
   ...         """Determine whether the object is valid
   ...
   ...         Return a string describing a validation problem.
   ...         An empty string is returned to indicate that the
   ...         object is valid.
   ...         """

Perhaps we have documents:

.. doctest::

   >>> class IDocument(interface.Interface):
   ...     summary = interface.Attribute("Document summary")
   ...     body = interface.Attribute("Document text")

   >>> class Document:
   ...     interface.implements(IDocument)
   ...     def __init__(self, summary, body):
   ...         self.summary, self.body = summary, body

Now, we may want to specify various validation rules for
documents. For example, we might require that the summary be a single
line:

.. doctest::

   >>> class SingleLineSummary:
   ...     component.adapts(IDocument)
   ...     interface.implements(IValidate)
   ...
   ...     def __init__(self, doc):
   ...         self.doc = doc
   ...
   ...     def validate(self):
   ...         if '\n' in self.doc.summary:
   ...             return 'Summary should only have one line'
   ...         else:
   ...             return ''

Or we might require the body to be at least 1000 characters in length:

.. doctest::

   >>> class AdequateLength:
   ...     component.adapts(IDocument)
   ...     interface.implements(IValidate)
   ...
   ...     def __init__(self, doc):
   ...         self.doc = doc
   ...
   ...     def validate(self):
   ...         if len(self.doc.body) < 1000:
   ...             return 'too short'
   ...         else:
   ...             return ''

We can register these as subscription adapters [1]_:

.. doctest::

   >>> component.provideSubscriptionAdapter(SingleLineSummary)
   >>> component.provideSubscriptionAdapter(AdequateLength)

We can then use the subscribers to validate objects:

.. doctest::

   >>> doc = Document("A\nDocument", "blah")
   >>> [adapter.validate()
   ...  for adapter in component.subscribers([doc], IValidate)
   ...  if adapter.validate()]
   ['Summary should only have one line', 'too short']

   >>> doc = Document("A\nDocument", "blah" * 1000)
   >>> [adapter.validate()
   ...  for adapter in component.subscribers([doc], IValidate)
   ...  if adapter.validate()]
   ['Summary should only have one line']

   >>> doc = Document("A Document", "blah")
   >>> [adapter.validate()
   ...  for adapter in component.subscribers([doc], IValidate)
   ...  if adapter.validate()]
   ['too short']

Handlers
--------

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

Event subscribers are different from other subscription adapters in
that the caller of event subscribers doesn't expect to interact with
them in any direct way.  For example, an event publisher doesn't
expect to get any return value.  Because subscribers don't need to
provide an API to their callers, it is more natural to define them
with functions, rather than classes.  For example, in a
document-management system, we might want to record creation times for
documents:

.. doctest::

   >>> import datetime

   >>> def documentCreated(event):
   ...     event.doc.created = datetime.datetime.utcnow()

In this example, we have a function that takes an event and performs
some processing.  It doesn't actually return anything.  This is a
special case of a subscription adapter that adapts an event to
nothing.  All of the work is done when the adapter "factory" is
called.  We call subscribers that don't actually create anything
"handlers".  There are special APIs for registering and calling
them.

To register the subscriber above, we define a document-created event:

.. doctest::

   >>> class IDocumentCreated(interface.Interface):
   ...     doc = interface.Attribute("The document that was created")

   >>> class DocumentCreated:
   ...     interface.implements(IDocumentCreated)
   ...
   ...     def __init__(self, doc):
   ...         self.doc = doc

We'll also change our handler definition to:

.. doctest::

   >>> @component.adapter(IDocumentCreated)
   ... def documentCreated(event):
   ...     event.doc.created = datetime.datetime.utcnow()

This marks the handler as an adapter of `IDocumentCreated` events.

Now we'll register the handler  [1]_:

.. doctest::

   >>> component.provideHandler(documentCreated)

Now, if we can create an event and use the `handle` function to call
handlers registered for the event:

.. doctest::

   >>> component.handle(DocumentCreated(doc))
   >>> doc.created.__class__.__name__
   'datetime'



.. [1] CAUTION: This API should only be used from test or
       application-setup code. This API shouldn't be used by regular
       library modules, as component registration is a configuration
       activity.