2

I want to make some common code of mine working through python2.7 and also python3.6 versions. In syntax manner it simply implies the following: converting prints to console of types: print "hello" to print("hello") which is acceptable in both versions.

The problem occurs only in one module import for Queue module.
In Python2.7: from Queue import Queue
In Python3.6: from queue import Queue

Trying to do something in the import section like:

try:  
    from Queue import Queue
except ImportError:
    from queue import Queue

Will work but its really not elegant and ugly, any ideas for making it more reasonable?

1
  • 1
    It's pretty elegant if you ask me. But if you're going to write more polyglot code, six will help Commented Jun 26, 2018 at 9:31

2 Answers 2

4

That is not actualy so bad practice and can be seen in quite a lot of python modules. When it comes to support of both Python2 and Python3, six module can be quite handy.

With six you can import queue like that.

from six.moves import queue

It will automatically proxy your import to the appropriate place depending on Python version.

Sign up to request clarification or add additional context in comments.

Comments

0

Maybe the below:

import platform
if platform.python_version().startswith('2.7'):  
    from Queue import Queue
elif platform.python_version().startswith('3.6'):
    from queue import Queue

1 Comment

I see no change except adding if else instead of try except and another module, imagine you have a section of import ...... import..... and then coming try: except clause or if else, both seems worse at the same level

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.