This is the 17th day of my participation in Gwen Challenge

It is common to encounter packages with different names or guide paths in Python2 and Python3, and errors will occur if Python2 code is run in a version 3 environment.

For example, urlencode, the urllib query string conversion function commonly used by crawlers, has a different guide path

Urlencode is used in different versions

Python2:

import urllib
query_string = {
  'name': 'Python'.'version': 2
}
query_string = urllib.urlencode(query_string)  
# version=2&name=Python
Copy the code

Python3:

import urllib

query_string = {
   'name': 'Python'.'version': 3
}
query_string = urllib.parse.urlencode(query_string)
# version=3&name=Python
Copy the code

For code compatibility, we can use a very useful module to determine the Python version used in the current environment: six stands for very 666 (the least common multiple of Python versions 2 and 3).

Use six for Python version compatibility

import six

if six.PY2:
   import urllib
else:
   import urllib.parse as urllib

query_string = {
   'name': 'Python'.'version': 2
}
query_string = urllib.urlencode(query_string)
# version=2&name=Python
Copy the code

How does six implement this

See the source code for six in Python2:

PY2 = sys.version_info[0] = =2
PY3 = sys.version_info[0] = =3
Copy the code

See the source code for six in Python3:

PY2 = sys.version_info[0] = =2
PY3 = sys.version_info[0] = =3
Copy the code

Seeing this, I… So this is it:

Version_info [0] == 3 (True) PY3 = sys.version_info[0] == 3

Self-actualization six

So let’s implement a mySix module that does the same thing as six to dynamically fetch the Python version:

Ideas:

The sys module has a property to retrieve Python version information: version, so we can use this property to determine the current version of Python to determine which package to use

mysix.py:

# coding=utf-8
import sys


PY2 = False
PY3 = False

def python_version() :
   version = sys.version[0]
   # sys.version Returns the version information string 3.7.0......
   if version == '2':
       global PY2
       PY2 = True
   else:
       global PY3
       PY3 = True
   return

Get the version information directly during package guide
python_version()
Copy the code

Import and use the same as six directly:

import mysix

if mysix.PY2:
   import urllib
else:
   import urllib.parse as urllib

query_string = {
   'name': 'Python'.'version': 2
}
query_string = urllib.urlencode(query_string)
# version=2&name=Python
Copy the code

So far, we have implemented the function of judging Python versions in six to achieve code version compatibility.

Sometimes, look at the source code, will suddenly see a lot of, in fact, they can also achieve.

Learning to know why, that will be a lot of motivation, a lot of clarity.