cpython: a2bf6d1e018e (original) (raw)
Mercurial > cpython
changeset 100596:a2bf6d1e018e
Merge for issue #26095 [#26095]
Brett Cannon brett@python.org | |
---|---|
date | Fri, 18 Mar 2016 13:24:15 -0700 |
parents | dc24ab548e2b(current diff)d5beb4978832(diff) |
children | 79888b970cc4 |
files | |
diffstat | 1 files changed, 46 insertions(+), 0 deletions(-)[+] [-] Doc/howto/pyporting.rst 46 |
line wrap: on
line diff
--- a/Doc/howto/pyporting.rst
+++ b/Doc/howto/pyporting.rst
@@ -282,6 +282,50 @@ To summarize:
appropriate
#. Be careful when indexing binary data
+
+Use feature detection instead of version detection
+++++++++++++++++++++++++++++++++++++++++++++++++++
+Inevitably you will have code that has to choose what to do based on what
+version of Python is running. The best way to do this is with feature detection
+of whether the version of Python you're running under supports what you need.
+If for some reason that doesn't work then you should make the version check is
+against Python 2 and not Python 3. To help explain this, let's look at an
+example.
+
+Let's pretend that you need access to a feature of importlib_ that
+is available in Python's standard library since Python 3.3 and available for
+Python 2 through importlib2_ on PyPI. You might be tempted to write code to
+access e.g. the importlib.abc
module by doing the following::
+
- import sys +
- if sys.version[0] == 3:
from importlib import abc[](#l1.25)
- else:
from importlib2 import abc[](#l1.27)
+ +The problem with this code is what happens when Python 4 comes out? It would +be better to treat Python 2 as the exceptional case instead of Python 3 and +assume that future Python versions will be more compatible with Python 3 than +Python 2:: +
- import sys +
- if sys.version[0] > 2:
from importlib import abc[](#l1.37)
- else:
from importlib2 import abc[](#l1.39)
+ +The best solution, though, is to do no version detection at all and instead rely +on feature detection. That avoids any potential issues of getting the version +detection wrong and helps keep you future-compatible:: +
+ + Prevent compatibility regressions --------------------------------- @@ -381,6 +425,8 @@ supported by Python 2. You should also u .. _cheat sheet: http://python-future.org/compatible_idioms.html[](#l1.55) .. _coverage.py: https://pypi.python.org/pypi/coverage[](#l1.56) .. _Futurize: http://python-future.org/automatic_conversion.html[](#l1.57) +.. _importlib: https://docs.python.org/3/library/importlib.html#module-importlib[](#l1.58) +.. _importlib2: https://pypi.python.org/pypi/importlib2[](#l1.59) .. _Modernize: http://python-modernize.readthedocs.org/en/latest/[](#l1.60) .. _Porting to Python 3: http://python3porting.com/[](#l1.61) .. _Pylint: https://pypi.python.org/pypi/pylint[](#l1.62)