blob: 87f46da972ce1168190d1e6bd74e2a3c46347e43 [file] [log] [blame]
Tor Norbye3a2425a2013-11-04 10:16:08 -08001# $Id: _compat.py 5908 2009-04-21 13:43:23Z goodger $
2# Author: Georg Brandl <georg@python.org>
3# Copyright: This module has been placed in the public domain.
4
5"""
6Python 2/3 compatibility definitions.
7
8This module currently provides the following helper symbols:
9
10* bytes (name of byte string type; str in 2.x, bytes in 3.x)
11* b (function converting a string literal to an ASCII byte string;
12 can be also used to convert a Unicode string into a byte string)
13* u_prefix (unicode repr prefix, 'u' in 2.x, nothing in 3.x)
14* BytesIO (a StringIO class that works with bytestrings)
15"""
16
17import sys
18
19if sys.version_info < (3,0):
20 b = bytes = str
21 u_prefix = 'u'
22 from StringIO import StringIO as BytesIO
23else:
24 import builtins
25 bytes = builtins.bytes
26 u_prefix = ''
27 def b(s):
28 if isinstance(s, str):
29 return s.encode('latin1')
30 elif isinstance(s, bytes):
31 return s
32 else:
33 raise TypeError("Invalid argument %r for b()" % (s,))
34 # using this hack since 2to3 "fixes" the relative import
35 # when using ``from io import BytesIO``
36 BytesIO = __import__('io').BytesIO