six
doesn't already shim_compat
module for isolationimport
detectiontry:
import configparser
PY2 = False
except ImportError:
import ConfigParser as configparser
PY2 = True
python-future
, configparser
, enum34
, etc.)# Suggested
from six import PY2
# Also ok
PY2 = sys.version_info[0] == 2
# Also works (unless you are using `futurize` stage 2)
PY2 = str is bytes
PY3
# or `from six import PY3`
PY3 = sys.version_info[0] == 3
if PY3:
# ...
else:
# ...
# do NOT
def foo():
if PY2:
...
else:
...
# do
if PY2:
def foo():
# python 2 implementation
else:
def foo():
# python 3+ implementation
from six import PY2
def to_text(s):
return s if isinstance(s, six.text_type) else s.decode('UTF-8')
def to_bytes(s):
return s if isinstance(s, bytes) else s.encode('UTF-8')
if PY2: # pragma: no cover (PY2)
to_native = to_bytes
else: # pragma: no cover (PY3+)
to_native = to_text