Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard solution for supporting Python 2 and Python 3

I'm trying to write a forward compatible program and I was wondering what the "best" way to handle the case where you need different imports.

In my specific case, I am using ConfigParser.SafeConfigParser() from Python2 which becomes configparser.ConfigParser() in Python3.

So far I have made it work either by using a try-except on the import or by using a conditional on the version of Python (using sys). Both work, but I was wondering if there was a recommended solution (maybe one I haven't tried yet).

ETA: Thanks everyone. I used six.moves with no issues.

like image 821
Ruby Tuesday Avatar asked Sep 10 '15 16:09

Ruby Tuesday


2 Answers

Use six! It's a python compatibility module that irons out the differences between python3 and python2. The documentation available here will help you with this problem as well as any other issues you're having..

Specifically for your case you can just

from six.moves import configparser
import six

if six.PY2:
  ConfigParser = configparser.SafeConfigParser
else:
  ConfigParser = configparser.ConfigParser

and you'll be good to go.

like image 65
Chad S. Avatar answered Oct 05 '22 03:10

Chad S.


This pattern is pretty standard:

try:
    from configparser import ConfigParser
except ImportError:
    from ConfigParser import SafeConfigParser as ConfigParser
like image 37
tzaman Avatar answered Oct 05 '22 03:10

tzaman