Using code for python versions 2 and 3 together by checking version number

On my Windows 10 laptop, I have a python 2 Django code base running on my python 3 environment setup. Recently I had to switch it over to a python 2 environment because of some python 2 specific libraries.

But we intend on migrating the small site from 2 to 3 in the near future.

So instead of deleting my environment for python 3, I created an environment for python 2 and am using them both in separate terminals.

Advisable to do this or not ?

import sys

py_version = sys.version_info[0]

if py_version == 2:
  from urllib2 import urlopen
else:
  from urllib.request import urlopen

response = urlopen('https://jsonplaceholder.typicode.com/users')
json = response.read()
# print(json) # do something with json
response.close()

Advisable would have been to drop Python 2 three years ago when its end-of-life was looming :wink:

Otherwise, supporting both Python 2 and 3 in the same codebase was a common thing for several years. The usual way to do it was not to explicitly check the version number, but instead use exception handling to check for Python 3 and fall back to Python 2. Your example using that scheme would look like:

try:
    from urllib.request import urlopen
except ImportError:
    from urllib2 import urlopen

response = urlopen('https://jsonplaceholder.typicode.com/users')
json = response.read()
# print(json) # do something with json
response.close()

When you’re ready to drop Python 2, just remove the try/except and continue on your merry way :slight_smile:

2 Likes

Thank You very much.

1 Like