2017-03-08 2 views
1

Je veux rendre ce code compatible avec python2-3:Comment faire une logique basée sur `unicode` compatible avec python2-3

def normalize_text(text, ignore_characters=''): 
    if type(ignore_characters) not in [list, str, unicode]: 
     ignore_characters = '' 
    if type(ignore_characters) == str: 
     ignore_characters = ignore_characters.decode('utf-8') 
    if type(ignore_characters) == list: 
     new_ignore_characters = [] 
     for item in ignore_characters: 
      if type(item) == str: 
       new_ignore_characters.append(item.decode('utf-8')) 
      elif type(item) == unicode: 
       new_ignore_characters.append(item) 
     ignore_characters = new_ignore_characters 

    if type(text) == str: 
     text = text.decode('utf-8') 

Il n'y a pas unicode ou decode sur str de type en python 3. Qu'est-ce que est la meilleure solution pour rendre ce code python2-3 compatible?

Répondre

1

Je recommande fortement d'utiliser la bibliothèque six pour écrire du code compatible Python 2/3.

Plus utiliser isinstance() pour vérifier le type au lieu de type(). type() ne fonctionnera pas en cas de l'héritage multiple:

from six import text_type, binary_type 

if isinstance(ignore_characters, binary_type): 
    # do something with bytes 
elif isinstance(ignore_characters, text_type): 
    # do something with unicode. 

# Python 2 
>>> import six 
>>> six.binary_type, six.text_type 
(<type 'str'>, <type 'unicode'>) 

# Python 3 
>>> import six 
>>> six.binary_type, six.text_type 
(<class 'bytes'>, <class 'str'>) 

Autre approche est d'écrire essentiellement vos propres alias pour la compatibilité basée sur la version Python obtenue en utilisant sys.version_info:

Un bon exemple de ceci est compat.py fichier de requests bibliothèque:

_ver = sys.version_info 

#: Python 2.x? 
is_py2 = (_ver[0] == 2) 

#: Python 3.x? 
is_py3 = (_ver[0] == 3) 

if is_py2: 
    builtin_str = str 
    bytes = str 
    str = unicode 
    basestring = basestring 
    numeric_types = (int, long, float) 
    integer_types = (int, long) 

elif is_py3: 
    builtin_str = str 
    str = str 
    bytes = bytes 
    basestring = (str, bytes) 
    numeric_types = (int, float) 
    integer_types = (int,) 

Vous pouvez maintenant importer ces fonctions à partir de ce fichier au lieu d'utiliser les intégrations directement.