Thursday, April 14, 2022

[FIXED] How to make an import statement work on both python 2 and python 3

Issue

I'm doing a migration for a code from python 2 to python 3. there is some code that I'm not migrating and is necessary to the code that i do migrating, therefor I need that some of the import statements work on both versions but the package got its name changed for example:

import urlparse  # Python2
import urllib.parse as urlparse  # Python 3

how can i code on statement that will work on both versions. keep in mind that this question is for the general case (the example above is only one of the problems created by the following migration)


Solution

For your imports, you can do the following:

import sys
if sys.version_info[0] < 3:
    #import your py2 packages
else:
    #import your py3 packages


Answered By - acrobat
Answer Checked By - Cary Denson (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.