@@ -282,6 +282,50 @@ To summarize:
282282 appropriate
283283#. Be careful when indexing binary data
284284
285+
286+ Use feature detection instead of version detection
287+ ++++++++++++++++++++++++++++++++++++++++++++++++++
288+ Inevitably you will have code that has to choose what to do based on what
289+ version of Python is running. The best way to do this is with feature detection
290+ of whether the version of Python you're running under supports what you need.
291+ If for some reason that doesn't work then you should make the version check is
292+ against Python 2 and not Python 3. To help explain this, let's look at an
293+ example.
294+
295+ Let's pretend that you need access to a feature of importlib _ that
296+ is available in Python's standard library since Python 3.3 and available for
297+ Python 2 through importlib2 _ on PyPI. You might be tempted to write code to
298+ access e.g. the ``importlib.abc `` module by doing the following::
299+
300+ import sys
301+
302+ if sys.version[0] == 3:
303+ from importlib import abc
304+ else:
305+ from importlib2 import abc
306+
307+ The problem with this code is what happens when Python 4 comes out? It would
308+ be better to treat Python 2 as the exceptional case instead of Python 3 and
309+ assume that future Python versions will be more compatible with Python 3 than
310+ Python 2::
311+
312+ import sys
313+
314+ if sys.version[0] > 2:
315+ from importlib import abc
316+ else:
317+ from importlib2 import abc
318+
319+ The best solution, though, is to do no version detection at all and instead rely
320+ on feature detection. That avoids any potential issues of getting the version
321+ detection wrong and helps keep you future-compatible::
322+
323+ try:
324+ from importlib import abc
325+ except ImportError:
326+ from importlib2 import abc
327+
328+
285329Prevent compatibility regressions
286330---------------------------------
287331
@@ -381,6 +425,8 @@ supported by Python 2. You should also update the classifiers in your
381425.. _cheat sheet : http://python-future.org/compatible_idioms.html
382426.. _coverage.py : https://pypi.python.org/pypi/coverage
383427.. _Futurize : http://python-future.org/automatic_conversion.html
428+ .. _importlib : https://docs.python.org/3/library/importlib.html#module-importlib
429+ .. _importlib2 : https://pypi.python.org/pypi/importlib2
384430.. _Modernize : http://python-modernize.readthedocs.org/en/latest/
385431.. _Porting to Python 3 : http://python3porting.com/
386432.. _Pylint : https://pypi.python.org/pypi/pylint
0 commit comments