File: api.rst

package info (click to toggle)
zope.deprecation 6.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 252 kB
  • sloc: python: 740; makefile: 131
file content (491 lines) | stat: -rw-r--r-- 13,754 bytes parent folder | download | duplicates (5)
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
=============================
 :mod:`zope.deprecation` API
=============================

Deprecating objects inside a module
===================================

Let's start with a demonstration of deprecating any name inside a module. To
demonstrate the functionality, First, let's set up an example module containing
fixtures we will use:

.. doctest::

   >>> import os
   >>> import tempfile
   >>> import zope.deprecation
   >>> tmp_d = tempfile.mkdtemp('deprecation')
   >>> zope.deprecation.__path__.append(tmp_d)
   >>> doctest_ex = '''\
   ... from . import deprecated
   ...
   ... def demo1():
   ...     return 1
   ... deprecated('demo1', 'demo1 is no more.')
   ...
   ... def demo2():
   ...     return 2
   ... deprecated('demo2', 'demo2 is no more.')
   ...
   ... def demo3():
   ...     return 3
   ... deprecated('demo3', 'demo3 is no more.')
   ...
   ... def demo4():
   ...     return 4
   ... def deprecatedemo4():
   ...     """Demonstrate that deprecated() also works in a local scope."""
   ...     deprecated('demo4', 'demo4 is no more.')
   ... '''
   >>> with open(os.path.join(tmp_d, 'doctest_ex.py'), 'w') as f:
   ...     _ = f.write(doctest_ex)

The first argument to the ``deprecated()`` function is a list of names that
should be declared deprecated. If the first argument is a string, it is
interpreted as one name. The second argument is the reason the particular name
has been deprecated. It is good practice to also list the version in which the
name will be removed completely.

Let's now see how the deprecation warnings are displayed.

.. doctest::

   >>> import warnings
   >>> from zope.deprecation import doctest_ex
   >>> with warnings.catch_warnings(record=True) as log:
   ...     del warnings.filters[:]
   ...     doctest_ex.demo1()
   1
   >>> print(log[0].category.__name__)
   DeprecationWarning
   >>> print(log[0].message)
   demo1: demo1 is no more.

   >>> import zope.deprecation.doctest_ex
   >>> with warnings.catch_warnings(record=True) as log:
   ...     del warnings.filters[:]
   ...     zope.deprecation.doctest_ex.demo2()
   2
   >>> print(log[0].message)
   demo2: demo2 is no more.

You can see that merely importing the affected module or one of its parents
does not cause a deprecation warning. Only when we try to access the name in
the module, we get a deprecation warning. On the other hand, if we import the
name directly, the deprecation warning will be raised immediately.

.. doctest::

   >>> with warnings.catch_warnings(record=True) as log:
   ...     del warnings.filters[:]
   ...     from zope.deprecation.doctest_ex import demo3
   >>> print(log[0].message)
   demo3: demo3 is no more.

Deprecation can also happen inside a function.  When we first access
``demo4``, it can be accessed without problems, then we call a
function that sets the deprecation message and we get the message upon
the next access:

.. doctest::

   >>> with warnings.catch_warnings(record=True) as log:
   ...     del warnings.filters[:]
   ...     doctest_ex.demo4()
   4
   >>> len(log)
   0
   >>> doctest_ex.deprecatedemo4()
   >>> with warnings.catch_warnings(record=True) as log:
   ...     del warnings.filters[:]
   ...     doctest_ex.demo4()
   4
   >>> print(log[0].message)
   demo4: demo4 is no more.


Deprecating methods and properties
==================================

New let's see how properties and methods can be deprecated. We are going to
use the same function as before, except that this time, we do not pass in names
as first argument, but the method or attribute itself. The function then
returns a wrapper that sends out a deprecation warning when the attribute or
method is accessed.

.. doctest::

   >>> from zope.deprecation import deprecation
   >>> class MyComponent(object):
   ...     foo = property(lambda self: 1)
   ...     foo = deprecation.deprecated(foo, 'foo is no more.')
   ...
   ...     bar = 2
   ...
   ...     def blah(self):
   ...         return 3
   ...     blah = deprecation.deprecated(blah, 'blah() is no more.')
   ...
   ...     def splat(self):
   ...         return 4
   ...
   ...     @deprecation.deprecate("clap() is no more.")
   ...     def clap(self):
   ...         return 5

And here is the result:

.. doctest::

   >>> my = MyComponent()
   >>> with warnings.catch_warnings(record=True) as log:
   ...     del warnings.filters[:]
   ...     my.foo
   1
   >>> print(log[0].message)
   foo is no more.
   >>> with warnings.catch_warnings(record=True) as log:
   ...     del warnings.filters[:]
   ...     my.bar
   2
   >>> len(log)
   0
   >>> with warnings.catch_warnings(record=True) as log:
   ...     del warnings.filters[:]
   ...     my.blah()
   3
   >>> print(log[0].message)
   blah() is no more.
   >>> with warnings.catch_warnings(record=True) as log:
   ...     del warnings.filters[:]
   ...     my.splat()
   4
   >>> len(log)
   0
   >>> with warnings.catch_warnings(record=True) as log:
   ...     del warnings.filters[:]
   ...     my.clap()
   5
   >>> print(log[0].message)
   clap() is no more.


Deprecating modules
===================

It is also possible to deprecate whole modules.  This is useful when
creating module aliases for backward compatibility.  Let's imagine,
the ``zope.deprecation`` module used to be called ``zope.wanda`` and
we'd like to retain backward compatibility:

.. doctest::

   >>> import sys
   >>> sys.modules['zope.wanda'] = deprecation.deprecated(
   ...     zope.deprecation, 'A module called Wanda is now zope.deprecation.')

Now we can import ``wanda``, but when accessing things from it, we get
our deprecation message as expected:

.. doctest::

   >>> with warnings.catch_warnings(record=True) as log:
   ...     del warnings.filters[:]
   ...     from zope.wanda import deprecated
   >>> print(log[0].message)
   A module called Wanda is now zope.deprecation.

Before we move on, we should clean up:

.. doctest::

   >>> del deprecated
   >>> del sys.modules['zope.wanda']


Moving modules
==============

When a module is moved, you often want to support importing from the
old location for a while, generating a deprecation warning when
someone uses the old location.  This can be done using the moved
function.

To see how this works, we'll use a helper function to create two fake
modules in the zope.deprecation package.  First will create a module
in the "old" location that used the moved function to indicate the a
module on the new location should be used:

.. doctest::

   >>> import os
   >>> created_modules = []
   >>> def create_module(modules=(), **kw): #** highlightfail
   ...     modules = dict(modules)
   ...     modules.update(kw)
   ...     for name, src in sorted(modules.items()):
   ...         pname = name.split('.')
   ...         if pname[-1] == '__init__':
   ...             os.mkdir(os.path.join(tmp_d, *pname[:-1])) #* highlightfail
   ...             name = '.'.join(pname[:-1])
   ...         with open(os.path.join(tmp_d, *pname) + '.py', 'w') as f:
   ...             f.write(src) #* hf
   ...         created_modules.append(name)
   ...     import importlib
   ...     if hasattr(importlib, 'invalidate_caches'):
   ...         importlib.invalidate_caches()
   >>> create_module(old_location=
   ... '''
   ... import zope.deprecation
   ... zope.deprecation.moved('zope.deprecation.new_location', 'version 2')
   ... ''')

and we define the module in the new location:

.. doctest::

   >>> create_module(new_location=
   ... '''\
   ... print("new module imported")
   ... x = 42
   ... ''')

Now, if we import the old location, we'll see the output of importing
the old location:

.. doctest::

   >>> with warnings.catch_warnings(record=True) as log:
   ...     del warnings.filters[:]
   ...     import zope.deprecation.old_location
   new module imported
   >>> print(log[0].message)
   ... # doctest: +NORMALIZE_WHITESPACE
   zope.deprecation.old_location has moved to zope.deprecation.new_location.
   Import of zope.deprecation.old_location will become unsupported
   in version 2
   >>> zope.deprecation.old_location.x
   42

Moving packages
===============

When moving packages, you need to leave placeholders for each
module.  Let's look at an example:

.. doctest::

   >>> create_module({
   ... 'new_package.__init__': '''\
   ... print(__name__ + ' imported')
   ... x=0
   ... ''',
   ... 'new_package.m1': '''\
   ... print(__name__ + ' imported')
   ... x=1
   ... ''',
   ... 'new_package.m2': '''\
   ... print(__name__ + ' imported')
   ... def x():
   ...     pass
   ... ''',
   ... 'new_package.m3': '''\
   ... print(__name__ + ' imported')
   ... x=3
   ... ''',
   ... 'old_package.__init__': '''\
   ... import zope.deprecation
   ... zope.deprecation.moved('zope.deprecation.new_package', 'version 2')
   ... ''',
   ... 'old_package.m1': '''\
   ... import zope.deprecation
   ... zope.deprecation.moved('zope.deprecation.new_package.m1', 'version 2')
   ... ''',
   ... 'old_package.m2': '''\
   ... import zope.deprecation
   ... zope.deprecation.moved('zope.deprecation.new_package.m2', 'version 2')
   ... ''',
   ... })


Now, if we import the old modules, we'll get warnings:

.. doctest::

   >>> with warnings.catch_warnings(record=True) as log:
   ...     del warnings.filters[:]
   ...     import zope.deprecation.old_package
   zope.deprecation.new_package imported
   >>> print(log[0].message)
   ... # doctest: +NORMALIZE_WHITESPACE
   zope.deprecation.old_package has moved to zope.deprecation.new_package.
   Import of zope.deprecation.old_package will become unsupported in version 2
   >>> zope.deprecation.old_package.x
   0

   >>> with warnings.catch_warnings(record=True) as log:
   ...     del warnings.filters[:]
   ...     import zope.deprecation.old_package.m1
   zope.deprecation.new_package.m1 imported
   >>> print(log[0].message)
   ... # doctest: +NORMALIZE_WHITESPACE
   zope.deprecation.old_package.m1 has moved to zope.deprecation.new_package.m1.
   Import of zope.deprecation.old_package.m1 will become unsupported in
   version 2
   >>> zope.deprecation.old_package.m1.x
   1

   >>> with warnings.catch_warnings(record=True) as log:
   ...     del warnings.filters[:]
   ...     import zope.deprecation.old_package.m2
   zope.deprecation.new_package.m2 imported
   >>> print(log[0].message)
   ... # doctest: +NORMALIZE_WHITESPACE
   zope.deprecation.old_package.m2 has moved to zope.deprecation.new_package.m2.
   Import of zope.deprecation.old_package.m2 will become unsupported in
   version 2
   >>> zope.deprecation.old_package.m2.x is zope.deprecation.new_package.m2.x
   True

   >>> (zope.deprecation.old_package.m2.x.__globals__
   ...  is zope.deprecation.new_package.m2.__dict__)
   True

   >>> zope.deprecation.old_package.m2.x.__module__
   'zope.deprecation.new_package.m2'

We'll get an error if we try to import m3, because we didn't create a
placeholder for it (Python 3.6 started raising ModuleNotFoundError, a
subclass of ImportError with a different error message than earlier
releases so we can't see that directly):

.. doctest::

   >>> try:
   ...     import zope.deprecation.old_package.m3
   ... except ImportError as e:
   ...    print("No module named" in str(e))
   ...    print("m3" in str(e))
   True
   True


Before we move on, let's clean up the temporary modules / packages:

.. doctest::

   >>> zope.deprecation.__path__.remove(tmp_d)
   >>> import shutil
   >>> shutil.rmtree(tmp_d)


Temporarily turning off deprecation warnings
============================================

In some cases it is desireable to turn off the deprecation warnings for a
short time.

To support such a feature, the ``zope.deprecation`` package
provides a context manager class, :class:`zope.deprecation.Suppressor`.
Code running inside the scope of a ``Suppressor`` will not emit deprecation
warnings.

.. doctest::

   >>> from zope.deprecation import Suppressor
   >>> class Foo(object):
   ...     bar = property(lambda self: 1)
   ...     bar = deprecation.deprecated(bar, 'bar is no more.')
   ...     blah = property(lambda self: 1)
   ...     blah = deprecation.deprecated(blah, 'blah is no more.')
   >>> foo = Foo()
   >>> with Suppressor():
   ...    foo.blah
   1

Note that no warning is emitted when ``foo.blah`` is accessed inside
the suppressor's scope.:

The suppressor is implemented in terms of a ``__show__`` object.
One can ask for its status by calling it:

.. doctest::

   >>> from zope.deprecation import __show__
   >>> __show__()
   True

Inside a suppressor's scope, that status is always false:

.. doctest::

   >>> with Suppressor():
   ...     __show__()
   False

.. doctest::

   >>> with warnings.catch_warnings(record=True) as log:
   ...     del warnings.filters[:]
   ...     foo.bar
   1
   >>> print(log[0].message)
   bar is no more.

If needed, your code can manage the depraction warnings manually using
the ``on()`` and ``off()`` methods of the ``__show__`` object:

.. doctest::

   >>> __show__.off()
   >>> __show__()
   False

   >>> foo.blah
   1

Now, you can also nest several turn-offs, so that calling ``off()`` multiple
times is meaningful:

.. doctest::

   >>> __show__.stack
   [False]

   >>> __show__.off()
   >>> __show__.stack
   [False, False]

   >>> __show__.on()
   >>> __show__.stack
   [False]
   >>> __show__()
   False

   >>> __show__.on()
   >>> __show__.stack
   []
   >>> __show__()
   True

You can also reset ``__show__`` to ``True``:

.. doctest::

   >>> __show__.off()
   >>> __show__.off()
   >>> __show__()
   False

   >>> __show__.reset()
   >>> __show__()
   True

Finally, you cannot call ``on()`` without having called ``off()`` before:

.. doctest::

   >>> __show__.on()
   Traceback (most recent call last):
   ...
   IndexError: pop from empty list