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.
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.
This pattern is pretty standard:
try:
from configparser import ConfigParser
except ImportError:
from ConfigParser import SafeConfigParser as ConfigParser
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With