Debian Codegraph @

docs/source/white_paper.rst

raw
1 .. _white_paper:
2
3 White Paper
4 ===========
5
6 This white paper shows some examples of how function deprecation is implemented in the Python Standard Library and Famous Open Source libraries.
7
8 You will see which kind of deprecation you can find in such libraries, and how it is documented in the user manuel.
9
10 .. _Python Standard Library:
11
12 The Python Standard Library
13 ---------------------------
14
15 :Library: Python_
16 :GitHub: `python/cpython <https://github.com/python/cpython>`_.
17 :Version: v3.8.dev
18
19 An example of function deprecation can be found in the :mod:`urllib` module (:file:`Lib/urllib/parse.py`):
20
21 .. code-block:: python
22
23 def to_bytes(url):
24 warnings.warn("urllib.parse.to_bytes() is deprecated as of 3.8",
25 DeprecationWarning, stacklevel=2)
26 return _to_bytes(url)
27
28 In the Python library, a warning is emitted in the function body using the function :func:`warnings.warn`.
29 This implementation is straightforward, it uses the category :exc:`DeprecationWarning` for warning filtering.
30
31 Another example is the deprecation of the *collections* ABC, which are now moved in the :mod:`collections.abc` module.
32 This example is available in the :mod:`collections` module (:file:`Lib/collections/__init__.py`):
33
34 .. code-block:: python
35
36 def __getattr__(name):
37 if name in _collections_abc.__all__:
38 obj = getattr(_collections_abc, name)
39 import warnings
40 warnings.warn("Using or importing the ABCs from 'collections' instead "
41 "of from 'collections.abc' is deprecated, "
42 "and in 3.8 it will stop working",
43 DeprecationWarning, stacklevel=2)
44 globals()[name] = obj
45 return obj
46 raise AttributeError(f'module {__name__!r} has no attribute {name!r}')
47
48 The warning is only emitted when an ABC is accessed from the :mod:`collections` instead of :mod:`collections.abc` module.
49
50 We can also see an example of keyword argument deprecation in the :class:`~collections.UserDict` class:
51
52 .. code-block:: python
53
54 def __init__(*args, **kwargs):
55 if not args:
56 raise TypeError("descriptor '__init__' of 'UserDict' object "
57 "needs an argument")
58 self, *args = args
59 if len(args) > 1:
60 raise TypeError('expected at most 1 arguments, got %d' % len(args))
61 if args:
62 dict = args[0]
63 elif 'dict' in kwargs:
64 dict = kwargs.pop('dict')
65 import warnings
66 warnings.warn("Passing 'dict' as keyword argument is deprecated",
67 DeprecationWarning, stacklevel=2)
68 else:
69 dict = None
70 self.data = {}
71 if dict is not None:
72 self.update(dict)
73 if len(kwargs):
74 self.update(kwargs)
75
76 Again, this implementation is straightforward: if the *dict* keyword argument is used, a warning is emitted.
77
78 Python make also use of the category :exc:`PendingDeprecationWarning` for instance in the :mod:`asyncio.tasks` module
79 (:file:`Lib/asyncio/tasks.py`):
80
81 .. code-block:: python
82
83 @classmethod
84 def current_task(cls, loop=None):
85 warnings.warn("Task.current_task() is deprecated, "
86 "use asyncio.current_task() instead",
87 PendingDeprecationWarning,
88 stacklevel=2)
89 if loop is None:
90 loop = events.get_event_loop()
91 return current_task(loop)
92
93 The category :exc:`FutureWarning` is also used to emit a warning when the functions is broken and will be
94 fixed in a "future" release. We can see for instance the method :meth:`~xml.etree.ElementTree.ElementTree.find`
95 of the class :class:`~xml.etree.ElementTree.ElementTree` (:file:`Lib/xml/etree/ElementTree.py`):
96
97 .. code-block:: python
98
99 def find(self, path, namespaces=None):
100 if path[:1] == "/":
101 path = "." + path
102 warnings.warn(
103 "This search is broken in 1.3 and earlier, and will be "
104 "fixed in a future version. If you rely on the current "
105 "behaviour, change it to %r" % path,
106 FutureWarning, stacklevel=2
107 )
108 return self._root.find(path, namespaces)
109
110 As a conclusion:
111
112 - Python library uses :func:`warnings.warn` to emit a deprecation warning in the body of functions.
113 - 3 categories are used: :exc:`DeprecationWarning`, :exc:`PendingDeprecationWarning` and :exc:`FutureWarning`.
114 - The docstring doesn't show anything about deprecation.
115 - The documentation warns about some, but not all, deprecated usages.
116
117 .. _Python: https://docs.python.org/fr/3/
118
119 .. _Flask Library:
120
121 The Flask Library
122 -----------------
123
124 :Library: Flask_
125 :GitHub: `pallets/flask <https://github.com/pallets/flask>`_.
126 :Version: v1.1.dev
127
128 In the source code of Flask, we find only few deprecations: in the :mod:`~flask.app` (:file:`flask/app.py`)
129 and in the :mod:`~flask.helpers` (:file:`flask/helpers.py`) modules.
130
131 In the Flask Library, like in the `Python Standard Library`_, deprecation warnings are emitted during function calls.
132 The implementation make use of the category :exc:`DeprecationWarning`.
133
134 Unlike the `Python Standard Library`_, the docstring documents explicitly the deprecation.
135 Flask uses Sphinx_’s `deprecated directive`_:
136
137 The bellow example shows the deprecation of the :meth:`~flask.Flask.open_session` method:
138
139 .. code-block:: python
140
141 def open_session(self, request):
142 """Creates or opens a new session. Default implementation stores all
143 session data in a signed cookie. This requires that the
144 :attr:`secret_key` is set. Instead of overriding this method
145 we recommend replacing the :class:`session_interface`.
146
147 .. deprecated: 1.0
148 Will be removed in 1.1. Use ``session_interface.open_session``
149 instead.
150
151 :param request: an instance of :attr:`request_class`.
152 """
153
154 warnings.warn(DeprecationWarning(
155 '"open_session" is deprecated and will be removed in 1.1. Use'
156 ' "session_interface.open_session" instead.'
157 ))
158 return self.session_interface.open_session(self, request)
159
160 .. _deprecated directive: https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-deprecated
161 .. _Sphinx: http://www.sphinx-doc.org/en/stable/index.html
162
163 .. hint::
164
165 When the function :func:`warnings.warn` is called with a :exc:`DeprecationWarning` instance,
166 the instance class is used like a warning category.
167
168 The documentation also mention a :exc:`flask.exthook.ExtDeprecationWarning` (which is not found in Flask’s source code):
169
170 .. code-block:: rst
171
172 Extension imports
173 `````````````````
174
175 Extension imports of the form ``flask.ext.foo`` are deprecated, you should use
176 ``flask_foo``.
177
178 The old form still works, but Flask will issue a
179 ``flask.exthook.ExtDeprecationWarning`` for each extension you import the old
180 way. We also provide a migration utility called `flask-ext-migrate
181 <https://github.com/pallets/flask-ext-migrate>`_ that is supposed to
182 automatically rewrite your imports for this.
183
184 As a conclusion:
185
186 - Flask library uses :func:`warnings.warn` to emit a deprecation warning in the body of functions.
187 - Only one category is used: :exc:`DeprecationWarning`.
188 - The docstring use `Sphinx`_’s `deprecated directive`_.
189 - The API documentation contains the deprecated usages.
190
191 .. _Flask: http://flask.pocoo.org/docs/
192
193 .. _Django Library:
194
195 The Django Library
196 ------------------
197
198 :Library: Django
199 :GitHub: `django/django <https://github.com/django/django>`_.
200 :Version: v3.0.dev
201
202 The `Django`_ Library defines several categories for deprecation in the module :mod:`django.utils.deprecation`:
203
204 - The category :exc:`~django.utils.deprecation.RemovedInDjango31Warning` which inherits
205 from :exc:`DeprecationWarning`.
206 - The category :exc:`~django.utils.deprecation.RemovedInDjango40Warning` which inherits
207 from :exc:`PendingDeprecationWarning`.
208 - The category :exc:`~django.utils.deprecation.RemovedInNextVersionWarning` which is an alias
209 of :exc:`~django.utils.deprecation.RemovedInDjango40Warning`.
210
211 The `Django`_ Library don't use :exc:`DeprecationWarning` or :exc:`PendingDeprecationWarning` directly,
212 but always use one of this 2 classes. The category :exc:`~django.utils.deprecation.RemovedInNextVersionWarning`
213 is only used in unit tests.
214
215 There are a lot of class deprecation examples. The deprecation warning is emitted during the call
216 of the ``__init__`` method. For instance in the class :class:`~django.contrib.postgres.forms.ranges.FloatRangeField`
217 (:file:`django/contrib/staticfiles/storage.py`):
218
219 .. code-block:: python
220
221 class FloatRangeField(DecimalRangeField):
222 base_field = forms.FloatField
223
224 def __init__(self, **kwargs):
225 warnings.warn(
226 'FloatRangeField is deprecated in favor of DecimalRangeField.',
227 RemovedInDjango31Warning, stacklevel=2,
228 )
229 super().__init__(**kwargs)
230
231 The implementation in the Django Library is similar to the one done in the `Python Standard Library`_:
232 deprecation warnings are emitted during function calls.
233 The implementation use the category :exc:`~django.utils.deprecation.RemovedInDjango31Warning`.
234
235 In the Django Library, we also find an example of property deprecation:
236 The property :meth:`~django.conf.LazySettings.FILE_CHARSET` of the class :class:`django.conf.LazySettings`.
237 The implementation of this property is:
238
239 .. code-block:: python
240
241 @property
242 def FILE_CHARSET(self):
243 stack = traceback.extract_stack()
244 # Show a warning if the setting is used outside of Django.
245 # Stack index: -1 this line, -2 the caller.
246 filename, _line_number, _function_name, _text = stack[-2]
247 if not filename.startswith(os.path.dirname(django.__file__)):
248 warnings.warn(
249 FILE_CHARSET_DEPRECATED_MSG,
250 RemovedInDjango31Warning,
251 stacklevel=2,
252 )
253 return self.__getattr__('FILE_CHARSET')
254
255 We also find function deprecations, mainly with the category :exc:`~django.utils.deprecation.RemovedInDjango40Warning`.
256 For instance, the function :func:`~django.utils.encoding.smart_text` emits a deprecation warning as follow:
257
258 .. code-block:: python
259
260 def smart_text(s, encoding='utf-8', strings_only=False, errors='strict'):
261 warnings.warn(
262 'smart_text() is deprecated in favor of smart_str().',
263 RemovedInDjango40Warning, stacklevel=2,
264 )
265 return smart_str(s, encoding, strings_only, errors)
266
267 The Django Library also define a decorator :class:`~django.utils.deprecation.warn_about_renamed_method`
268 which is used internally in the metaclass :class:`~django.utils.deprecation.RenameMethodsBase`.
269 This metaclass is only used in unit tests to check renamed methods.
270
271 As a conclusion:
272
273 - The Django library uses :func:`warnings.warn` to emit a deprecation warning in the body of functions.
274 - It uses two categories which inherits the standard categories :exc:`DeprecationWarning`
275 and :exc:`PendingDeprecationWarning`.
276 - The source code of the Django Library doesn't contains much docstring.
277 The deprecation never appears in the docstring anyway.
278 - The release notes contain information about deprecated features.
279
280 .. _Django: https://docs.djangoproject.com/
281
282 The lxml Library
283 ----------------
284
285 :Library: lxml_
286 :GitHub: `lxml/lxml <https://github.com/lxml/lxml>`_.
287 :Version: v4.3.2.dev
288
289 The lxml_ Library is developed in Cython, not Python. But, it is a similar language.
290 This library mainly use comments or docstring to mark function as deprecated.
291
292 For instance, in the class :class:`lxml.xpath._XPathEvaluatorBase`(:file:`src/lxml/xpath.pxi`),
293 the ``evaluate`` method is deprecated as follow:
294
295 .. code-block:: python
296
297 def evaluate(self, _eval_arg, **_variables):
298 u"""evaluate(self, _eval_arg, **_variables)
299
300 Evaluate an XPath expression.
301
302 Instead of calling this method, you can also call the evaluator object
303 itself.
304
305 Variables may be provided as keyword arguments. Note that namespaces
306 are currently not supported for variables.
307
308 :deprecated: call the object, not its method.
309 """
310 return self(_eval_arg, **_variables)
311
312 There is only one example of usage of the function :func:`warnings.warn`:
313 in the :class:`~lxml.etree._ElementTree` class (:file:`src/lxml/etree.pyx`):
314
315 .. code-block:: python
316
317 if docstring is not None and doctype is None:
318 import warnings
319 warnings.warn(
320 "The 'docstring' option is deprecated. Use 'doctype' instead.",
321 DeprecationWarning)
322 doctype = docstring
323
324
325 As a conclusion:
326
327 - Except in one example, the lxml library doesn't use :func:`warnings.warn` to emit a deprecation warnings.
328 - The deprecations are described in the function docstrings.
329 - The release notes contain information about deprecated features.
330
331 .. _lxml: https://lxml.de
332
333 The openpyxl Library
334 --------------------
335
336 :Library: openpyxl
337 :Bitbucket: `openpyxl/openpyxl <https://bitbucket.org/openpyxl/openpyxl>`_.
338 :Version: v2.6.1.dev
339
340 openpyxl_ is a Python library to read/write Excel 2010 xlsx/xlsm/xltx/xltm files.
341 Tu warn about deprecation, this library uses a home-made ``@deprecated`` decorator.
342
343 The implementation of this decorator is an adapted copy of the first version of Tantale’s ``@deprecated`` decorator.
344 It has the enhancement to update the docstring of the decorated function.
345 So, this is similar to the function :func:`deprecated.sphinx.deprecated`.
346
347 .. code-block:: python
348
349 string_types = (type(b''), type(u''))
350 def deprecated(reason):
351
352 if isinstance(reason, string_types):
353
354 def decorator(func1):
355
356 if inspect.isclass(func1):
357 fmt1 = "Call to deprecated class {name} ({reason})."
358 else:
359 fmt1 = "Call to deprecated function {name} ({reason})."
360
361 @wraps(func1)
362 def new_func1(*args, **kwargs):
363 #warnings.simplefilter('default', DeprecationWarning)
364 warnings.warn(
365 fmt1.format(name=func1.__name__, reason=reason),
366 category=DeprecationWarning,
367 stacklevel=2
368 )
369 return func1(*args, **kwargs)
370
371 # Enhance docstring with a deprecation note
372 deprecationNote = "\n\n.. note::\n Deprecated: " + reason
373 if new_func1.__doc__:
374 new_func1.__doc__ += deprecationNote
375 else:
376 new_func1.__doc__ = deprecationNote
377 return new_func1
378
379 return decorator
380
381 elif inspect.isclass(reason) or inspect.isfunction(reason):
382 raise TypeError("Reason for deprecation must be supplied")
383
384 else:
385 raise TypeError(repr(type(reason)))
386
387 As a conclusion:
388
389 - The openpyxl library uses a decorator to deprecate functions.
390 - It uses the category :exc:`DeprecationWarning`.
391 - The decorator update the docstring and add a ``.. note::`` directive,
392 which is visible in the documentation.
393
394 .. _openpyxl: https://openpyxl.readthedocs.io/