Package Bio :: Package _py3k
[hide private]
[frames] | no frames]

Source Code for Package Bio._py3k

  1  # Copyright 2010-2013 by Peter Cock.  All rights reserved. 
  2  # This code is part of the Biopython distribution and governed by its 
  3  # license.  Please see the LICENSE file that should have been included 
  4  # as part of this package. 
  5  """Python 3 compatibility tools (PRIVATE). 
  6   
  7  We used to have lines like this under Python 2 in order to use 
  8  iterator based zip, map and filter (in Python 3 these functions 
  9  are all iterator based):: 
 10   
 11      from future_builtins import zip 
 12   
 13  There is no similar option for range yet, other than:: 
 14   
 15      range = xrange 
 16      input = raw_input 
 17   
 18  or: 
 19   
 20      from __builtin__ import xrange as range 
 21      from __builtin__ import raw_input as input 
 22   
 23  Under Python 3 these imports need to be removed. Also, deliberate 
 24  importing of built in functions like open changes from Python 2:: 
 25   
 26      from __builtin__ import open 
 27   
 28  To do this under Python 3: 
 29   
 30      from builtins import open 
 31   
 32  Instead, we can do this under either Python 2 or 3: 
 33   
 34      from Bio._py3k import open 
 35      from Bio._py3k import zip 
 36   
 37  Once we drop support for Python 2, the whole of Bio._py3k will 
 38  go away. 
 39  """ 
 40   
 41  # From the point of view of pep8 and flake8, there are lots of issues with 
 42  # this file. This line tells flake8 to ignore it for quality assurance: 
 43  # flake8: noqa 
 44   
 45  import sys 
 46   
 47   
 48  if sys.version_info[0] >= 3: 
 49      # Code for Python 3 
 50      from builtins import open, zip, map, filter, range, input 
 51   
 52      import codecs 
 53   
 54      # Lots of our Python 2 code uses isinstance(x, basestring) 
 55      # which after 2to3 becomes isinstance(x, str) 
 56      basestring = str 
 57      unicode = str 
 58   
 59      _bytes_to_string = lambda b: b.decode()  # bytes to unicode string 
 60      _string_to_bytes = lambda s: s.encode()  # unicode string to bytes 
 61   
62 - def _bytes_bytearray_to_str(s):
63 """If s is bytes or bytearray, convert to a unicode string.""" 64 if isinstance(s, (bytes, bytearray)): 65 return s.decode() 66 return s
67
68 - def _as_unicode(s):
69 """Turn byte string or unicode string into a unicode string.""" 70 if isinstance(s, str): 71 return s 72 # Assume it is a bytes string 73 # Note ISO-8859-1 aka Latin-1 preserves first 256 chars 74 return codecs.latin_1_decode(s)[0]
75
76 - def _as_bytes(s):
77 """Turn byte string or unicode string into a bytes string. 78 79 The Python 2 version returns a (byte) string. 80 """ 81 if isinstance(s, bytes): 82 return s 83 # Assume it is a unicode string 84 # Note ISO-8859-1 aka Latin-1 preserves first 256 chars 85 return codecs.latin_1_encode(s)[0]
86 87 _as_string = _as_unicode 88
89 - def _is_int_or_long(i):
90 """Check if the value is an integer. 91 92 Note there are no longs on Python 3. 93 """ 94 return isinstance(i, int)
95 96 import io 97 98 # Python 3.4 onwards, the standard library wrappers should work:
99 - def _binary_to_string_handle(handle):
100 """Treat a binary (bytes) handle like a text (unicode) handle.""" 101 wrapped = io.TextIOWrapper(io.BufferedReader(handle)) 102 try: 103 # If wrapping an online handle, this is nice to have: 104 wrapped.url = handle.url 105 except AttributeError: 106 pass 107 return wrapped
108 109 # This is to avoid the deprecation warning from open(filename, "rU") 110 _universal_read_mode = "r" # text mode does universal new lines 111 112 # On Python 3, this will be a unicode StringIO 113 from io import StringIO 114 115 # On Python 3 urllib, urllib2, and urlparse were merged: 116 from urllib.request import urlopen, Request, urlretrieve, urlparse, urlcleanup 117 from urllib.parse import urlencode, quote 118 from urllib.error import HTTPError 119 120 else: 121 # Python 2 code 122 from __builtin__ import open, basestring, unicode 123 124 # Import Python3 like iterator functions: 125 from future_builtins import zip, map, filter 126 from __builtin__ import xrange as range 127 from __builtin__ import raw_input as input 128 129 _bytes_to_string = lambda b: b # bytes to string, i.e. do nothing 130 _string_to_bytes = lambda s: str(s) # str (or unicode) to bytes string 131
132 - def _bytes_bytearray_to_str(s):
133 """If s is bytes or bytearray, convert to a string.""" 134 if isinstance(s, (bytes, bytearray)): 135 return str(s) 136 return s
137
138 - def _as_unicode(s):
139 """Turn a (byte) string or a unicode string into a (byte) string.""" 140 # Will be changed by 2to3 to "isinstance(s, str)" but doesn't matter: 141 if isinstance(s, unicode): 142 return s 143 return s.decode()
144
145 - def _as_bytes(s):
146 """Turn a (byte) string or a unicode string into a (byte) string.""" 147 return str(s)
148 149 _as_string = _as_bytes 150
151 - def _is_int_or_long(i):
152 """Check if the value is an integer or long.""" 153 return isinstance(i, (int, long))
154
155 - def _binary_to_string_handle(handle):
156 """Treat a binary handle like a text handle.""" 157 return handle
158 159 # This private variable is set to "r" on Python 3 for text 160 # mode which include universal readlines mode 161 _universal_read_mode = "rU" 162 163 # On Python 2 this will be a (bytes) string based handle. 164 # Note this doesn't work as it is unicode based: 165 # from io import StringIO 166 try: 167 from cStringIO import StringIO 168 except ImportError: 169 from StringIO import StringIO 170 171 # Under urllib.request on Python 3: 172 from urllib2 import urlopen, Request 173 from urllib import urlretrieve, urlcleanup 174 from urlparse import urlparse 175 176 # Under urllib.parse on Python 3: 177 from urllib import urlencode, quote 178 179 # Under urllib.error on Python 3: 180 from urllib2 import HTTPError 181 182 183 if sys.platform == "win32": 184 # Can't use commands.getoutput on Python 2, Unix only/broken: 185 # http://bugs.python.org/issue15073 186 # Can't use subprocess.getoutput on Python 3, Unix only/broken: 187 # http://bugs.python.org/issue10197
188 - def getoutput(cmd):
189 import subprocess 190 child = subprocess.Popen(cmd, 191 stdin=subprocess.PIPE, 192 stdout=subprocess.PIPE, 193 stderr=subprocess.STDOUT, 194 universal_newlines=True, 195 shell=False) 196 stdout, stderr = child.communicate() 197 # Remove trailing \n to match the Unix function, 198 return stdout.rstrip("\n")
199 elif sys.version_info[0] >= 3: 200 # Use subprocess.getoutput on Python 3, 201 from subprocess import getoutput 202 else: 203 # Use commands.getoutput on Python 2, 204 from commands import getoutput 205