compat.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  1. # -*- test-case-name: twisted.test.test_compat -*-
  2. #
  3. # Copyright (c) Twisted Matrix Laboratories.
  4. # See LICENSE for details.
  5. """
  6. Compatibility module to provide backwards compatibility for useful Python
  7. features.
  8. This is mainly for use of internal Twisted code. We encourage you to use
  9. the latest version of Python directly from your code, if possible.
  10. @var unicode: The type of Unicode strings, C{unicode} on Python 2 and C{str}
  11. on Python 3.
  12. @var NativeStringIO: An in-memory file-like object that operates on the native
  13. string type (bytes in Python 2, unicode in Python 3).
  14. @var urllib_parse: a URL-parsing module (urlparse on Python 2, urllib.parse on
  15. Python 3)
  16. """
  17. from __future__ import absolute_import, division
  18. import inspect
  19. import os
  20. import platform
  21. import socket
  22. import struct
  23. import sys
  24. import tokenize
  25. from types import MethodType as _MethodType
  26. from io import TextIOBase, IOBase
  27. if sys.version_info < (3, 0):
  28. _PY3 = False
  29. else:
  30. _PY3 = True
  31. if sys.version_info >= (3, 4, 0):
  32. _PY34PLUS = True
  33. else:
  34. _PY34PLUS = False
  35. if sys.version_info >= (3, 5, 0):
  36. _PY35PLUS = True
  37. else:
  38. _PY35PLUS = False
  39. if platform.python_implementation() == 'PyPy':
  40. _PYPY = True
  41. else:
  42. _PYPY = False
  43. def _shouldEnableNewStyle():
  44. """
  45. Returns whether or not we should enable the new-style conversion of
  46. old-style classes. It inspects the environment for C{TWISTED_NEWSTYLE},
  47. accepting an empty string, C{no}, C{false}, C{False}, and C{0} as falsey
  48. values and everything else as a truthy value.
  49. @rtype: L{bool}
  50. """
  51. value = os.environ.get('TWISTED_NEWSTYLE', '')
  52. if value in ['', 'no', 'false', 'False', '0']:
  53. return False
  54. else:
  55. return True
  56. _EXPECT_NEWSTYLE = _PY3 or _shouldEnableNewStyle()
  57. def _shouldEnableNewStyle():
  58. """
  59. Returns whether or not we should enable the new-style conversion of
  60. old-style classes. It inspects the environment for C{TWISTED_NEWSTYLE},
  61. accepting an empty string, C{no}, C{false}, C{False}, and C{0} as falsey
  62. values and everything else as a truthy value.
  63. @rtype: L{bool}
  64. """
  65. value = os.environ.get('TWISTED_NEWSTYLE', '')
  66. if value in ['', 'no', 'false', 'False', '0']:
  67. return False
  68. else:
  69. return True
  70. _EXPECT_NEWSTYLE = _PY3 or _shouldEnableNewStyle()
  71. def currentframe(n=0):
  72. """
  73. In Python 3, L{inspect.currentframe} does not take a stack-level argument.
  74. Restore that functionality from Python 2 so we don't have to re-implement
  75. the C{f_back}-walking loop in places where it's called.
  76. @param n: The number of stack levels above the caller to walk.
  77. @type n: L{int}
  78. @return: a frame, n levels up the stack from the caller.
  79. @rtype: L{types.FrameType}
  80. """
  81. f = inspect.currentframe()
  82. for x in range(n + 1):
  83. f = f.f_back
  84. return f
  85. def inet_pton(af, addr):
  86. """
  87. Emulator of L{socket.inet_pton}.
  88. @param af: An address family to parse; C{socket.AF_INET} or
  89. C{socket.AF_INET6}.
  90. @type af: L{int}
  91. @param addr: An address.
  92. @type addr: native L{str}
  93. @return: The binary packed version of the passed address.
  94. @rtype: L{bytes}
  95. """
  96. if not addr:
  97. raise ValueError("illegal IP address string passed to inet_pton")
  98. if af == socket.AF_INET:
  99. return socket.inet_aton(addr)
  100. elif af == getattr(socket, 'AF_INET6', 'AF_INET6'):
  101. if '%' in addr and (addr.count('%') > 1 or addr.index("%") == 0):
  102. raise ValueError("illegal IP address string passed to inet_pton")
  103. addr = addr.split('%')[0]
  104. parts = addr.split(':')
  105. elided = parts.count('')
  106. ipv4Component = '.' in parts[-1]
  107. if len(parts) > (8 - ipv4Component) or elided > 3:
  108. raise ValueError("Syntactically invalid address")
  109. if elided == 3:
  110. return '\x00' * 16
  111. if elided:
  112. zeros = ['0'] * (8 - len(parts) - ipv4Component + elided)
  113. if addr.startswith('::'):
  114. parts[:2] = zeros
  115. elif addr.endswith('::'):
  116. parts[-2:] = zeros
  117. else:
  118. idx = parts.index('')
  119. parts[idx:idx+1] = zeros
  120. if len(parts) != 8 - ipv4Component:
  121. raise ValueError("Syntactically invalid address")
  122. else:
  123. if len(parts) != (8 - ipv4Component):
  124. raise ValueError("Syntactically invalid address")
  125. if ipv4Component:
  126. if parts[-1].count('.') != 3:
  127. raise ValueError("Syntactically invalid address")
  128. rawipv4 = socket.inet_aton(parts[-1])
  129. unpackedipv4 = struct.unpack('!HH', rawipv4)
  130. parts[-1:] = [hex(x)[2:] for x in unpackedipv4]
  131. parts = [int(x, 16) for x in parts]
  132. return struct.pack('!8H', *parts)
  133. else:
  134. raise socket.error(97, 'Address family not supported by protocol')
  135. def inet_ntop(af, addr):
  136. if af == socket.AF_INET:
  137. return socket.inet_ntoa(addr)
  138. elif af == socket.AF_INET6:
  139. if len(addr) != 16:
  140. raise ValueError("address length incorrect")
  141. parts = struct.unpack('!8H', addr)
  142. curBase = bestBase = None
  143. for i in range(8):
  144. if not parts[i]:
  145. if curBase is None:
  146. curBase = i
  147. curLen = 0
  148. curLen += 1
  149. else:
  150. if curBase is not None:
  151. bestLen = None
  152. if bestBase is None or curLen > bestLen:
  153. bestBase = curBase
  154. bestLen = curLen
  155. curBase = None
  156. if curBase is not None and (bestBase is None or curLen > bestLen):
  157. bestBase = curBase
  158. bestLen = curLen
  159. parts = [hex(x)[2:] for x in parts]
  160. if bestBase is not None:
  161. parts[bestBase:bestBase + bestLen] = ['']
  162. if parts[0] == '':
  163. parts.insert(0, '')
  164. if parts[-1] == '':
  165. parts.insert(len(parts) - 1, '')
  166. return ':'.join(parts)
  167. else:
  168. raise socket.error(97, 'Address family not supported by protocol')
  169. try:
  170. socket.AF_INET6
  171. except AttributeError:
  172. socket.AF_INET6 = 'AF_INET6'
  173. try:
  174. socket.inet_pton(socket.AF_INET6, "::")
  175. except (AttributeError, NameError, socket.error):
  176. socket.inet_pton = inet_pton
  177. socket.inet_ntop = inet_ntop
  178. adict = dict
  179. if _PY3:
  180. # These are actually useless in Python 2 as well, but we need to go
  181. # through deprecation process there (ticket #5895):
  182. del adict, inet_pton, inet_ntop
  183. set = set
  184. frozenset = frozenset
  185. try:
  186. from functools import reduce
  187. except ImportError:
  188. reduce = reduce
  189. def execfile(filename, globals, locals=None):
  190. """
  191. Execute a Python script in the given namespaces.
  192. Similar to the execfile builtin, but a namespace is mandatory, partly
  193. because that's a sensible thing to require, and because otherwise we'd
  194. have to do some frame hacking.
  195. This is a compatibility implementation for Python 3 porting, to avoid the
  196. use of the deprecated builtin C{execfile} function.
  197. """
  198. if locals is None:
  199. locals = globals
  200. with open(filename, "rb") as fin:
  201. source = fin.read()
  202. code = compile(source, filename, "exec")
  203. exec(code, globals, locals)
  204. try:
  205. cmp = cmp
  206. except NameError:
  207. def cmp(a, b):
  208. """
  209. Compare two objects.
  210. Returns a negative number if C{a < b}, zero if they are equal, and a
  211. positive number if C{a > b}.
  212. """
  213. if a < b:
  214. return -1
  215. elif a == b:
  216. return 0
  217. else:
  218. return 1
  219. def comparable(klass):
  220. """
  221. Class decorator that ensures support for the special C{__cmp__} method.
  222. On Python 2 this does nothing.
  223. On Python 3, C{__eq__}, C{__lt__}, etc. methods are added to the class,
  224. relying on C{__cmp__} to implement their comparisons.
  225. """
  226. # On Python 2, __cmp__ will just work, so no need to add extra methods:
  227. if not _PY3:
  228. return klass
  229. def __eq__(self, other):
  230. c = self.__cmp__(other)
  231. if c is NotImplemented:
  232. return c
  233. return c == 0
  234. def __ne__(self, other):
  235. c = self.__cmp__(other)
  236. if c is NotImplemented:
  237. return c
  238. return c != 0
  239. def __lt__(self, other):
  240. c = self.__cmp__(other)
  241. if c is NotImplemented:
  242. return c
  243. return c < 0
  244. def __le__(self, other):
  245. c = self.__cmp__(other)
  246. if c is NotImplemented:
  247. return c
  248. return c <= 0
  249. def __gt__(self, other):
  250. c = self.__cmp__(other)
  251. if c is NotImplemented:
  252. return c
  253. return c > 0
  254. def __ge__(self, other):
  255. c = self.__cmp__(other)
  256. if c is NotImplemented:
  257. return c
  258. return c >= 0
  259. klass.__lt__ = __lt__
  260. klass.__gt__ = __gt__
  261. klass.__le__ = __le__
  262. klass.__ge__ = __ge__
  263. klass.__eq__ = __eq__
  264. klass.__ne__ = __ne__
  265. return klass
  266. if _PY3:
  267. unicode = str
  268. long = int
  269. else:
  270. unicode = unicode
  271. long = long
  272. def ioType(fileIshObject, default=unicode):
  273. """
  274. Determine the type which will be returned from the given file object's
  275. read() and accepted by its write() method as an argument.
  276. In other words, determine whether the given file is 'opened in text mode'.
  277. @param fileIshObject: Any object, but ideally one which resembles a file.
  278. @type fileIshObject: L{object}
  279. @param default: A default value to return when the type of C{fileIshObject}
  280. cannot be determined.
  281. @type default: L{type}
  282. @return: There are 3 possible return values:
  283. 1. L{unicode}, if the file is unambiguously opened in text mode.
  284. 2. L{bytes}, if the file is unambiguously opened in binary mode.
  285. 3. L{basestring}, if we are on python 2 (the L{basestring} type
  286. does not exist on python 3) and the file is opened in binary
  287. mode, but has an encoding and can therefore accept both bytes
  288. and text reliably for writing, but will return L{bytes} from
  289. read methods.
  290. 4. The C{default} parameter, if the given type is not understood.
  291. @rtype: L{type}
  292. """
  293. if isinstance(fileIshObject, TextIOBase):
  294. # If it's for text I/O, then it's for text I/O.
  295. return unicode
  296. if isinstance(fileIshObject, IOBase):
  297. # If it's for I/O but it's _not_ for text I/O, it's for bytes I/O.
  298. return bytes
  299. encoding = getattr(fileIshObject, 'encoding', None)
  300. import codecs
  301. if isinstance(fileIshObject, (codecs.StreamReader, codecs.StreamWriter)):
  302. # On StreamReaderWriter, the 'encoding' attribute has special meaning;
  303. # it is unambiguously unicode.
  304. if encoding:
  305. return unicode
  306. else:
  307. return bytes
  308. if not _PY3:
  309. # Special case: if we have an encoding file, we can *give* it unicode,
  310. # but we can't expect to *get* unicode.
  311. if isinstance(fileIshObject, file):
  312. if encoding is not None:
  313. return basestring
  314. else:
  315. return bytes
  316. from cStringIO import InputType, OutputType
  317. from StringIO import StringIO
  318. if isinstance(fileIshObject, (StringIO, InputType, OutputType)):
  319. return bytes
  320. return default
  321. def nativeString(s):
  322. """
  323. Convert C{bytes} or C{unicode} to the native C{str} type, using ASCII
  324. encoding if conversion is necessary.
  325. @raise UnicodeError: The input string is not ASCII encodable/decodable.
  326. @raise TypeError: The input is neither C{bytes} nor C{unicode}.
  327. """
  328. if not isinstance(s, (bytes, unicode)):
  329. raise TypeError("%r is neither bytes nor unicode" % s)
  330. if _PY3:
  331. if isinstance(s, bytes):
  332. return s.decode("ascii")
  333. else:
  334. # Ensure we're limited to ASCII subset:
  335. s.encode("ascii")
  336. else:
  337. if isinstance(s, unicode):
  338. return s.encode("ascii")
  339. else:
  340. # Ensure we're limited to ASCII subset:
  341. s.decode("ascii")
  342. return s
  343. def _matchingString(constantString, inputString):
  344. """
  345. Some functions, such as C{os.path.join}, operate on string arguments which
  346. may be bytes or text, and wish to return a value of the same type. In
  347. those cases you may wish to have a string constant (in the case of
  348. C{os.path.join}, that constant would be C{os.path.sep}) involved in the
  349. parsing or processing, that must be of a matching type in order to use
  350. string operations on it. L{_matchingString} will take a constant string
  351. (either L{bytes} or L{unicode}) and convert it to the same type as the
  352. input string. C{constantString} should contain only characters from ASCII;
  353. to ensure this, it will be encoded or decoded regardless.
  354. @param constantString: A string literal used in processing.
  355. @type constantString: L{unicode} or L{bytes}
  356. @param inputString: A byte string or text string provided by the user.
  357. @type inputString: L{unicode} or L{bytes}
  358. @return: C{constantString} converted into the same type as C{inputString}
  359. @rtype: the type of C{inputString}
  360. """
  361. if isinstance(constantString, bytes):
  362. otherType = constantString.decode("ascii")
  363. else:
  364. otherType = constantString.encode("ascii")
  365. if type(constantString) == type(inputString):
  366. return constantString
  367. else:
  368. return otherType
  369. if _PY3:
  370. def reraise(exception, traceback):
  371. raise exception.with_traceback(traceback)
  372. else:
  373. exec("""def reraise(exception, traceback):
  374. raise exception.__class__, exception, traceback""")
  375. reraise.__doc__ = """
  376. Re-raise an exception, with an optional traceback, in a way that is compatible
  377. with both Python 2 and Python 3.
  378. Note that on Python 3, re-raised exceptions will be mutated, with their
  379. C{__traceback__} attribute being set.
  380. @param exception: The exception instance.
  381. @param traceback: The traceback to use, or L{None} indicating a new traceback.
  382. """
  383. if _PY3:
  384. from io import StringIO as NativeStringIO
  385. else:
  386. from io import BytesIO as NativeStringIO
  387. # Functions for dealing with Python 3's bytes type, which is somewhat
  388. # different than Python 2's:
  389. if _PY3:
  390. def iterbytes(originalBytes):
  391. for i in range(len(originalBytes)):
  392. yield originalBytes[i:i+1]
  393. def intToBytes(i):
  394. return ("%d" % i).encode("ascii")
  395. # Ideally we would use memoryview, but it has a number of differences from
  396. # the Python 2 buffer() that make that impractical
  397. # (http://bugs.python.org/issue15945, incompatibility with pyOpenSSL due to
  398. # PyArg_ParseTuple differences.)
  399. def lazyByteSlice(object, offset=0, size=None):
  400. """
  401. Return a copy of the given bytes-like object.
  402. If an offset is given, the copy starts at that offset. If a size is
  403. given, the copy will only be of that length.
  404. @param object: C{bytes} to be copied.
  405. @param offset: C{int}, starting index of copy.
  406. @param size: Optional, if an C{int} is given limit the length of copy
  407. to this size.
  408. """
  409. if size is None:
  410. return object[offset:]
  411. else:
  412. return object[offset:(offset + size)]
  413. def networkString(s):
  414. if not isinstance(s, unicode):
  415. raise TypeError("Can only convert text to bytes on Python 3")
  416. return s.encode('ascii')
  417. else:
  418. def iterbytes(originalBytes):
  419. return originalBytes
  420. def intToBytes(i):
  421. return b"%d" % i
  422. lazyByteSlice = buffer
  423. def networkString(s):
  424. if not isinstance(s, str):
  425. raise TypeError("Can only pass-through bytes on Python 2")
  426. # Ensure we're limited to ASCII subset:
  427. s.decode('ascii')
  428. return s
  429. iterbytes.__doc__ = """
  430. Return an iterable wrapper for a C{bytes} object that provides the behavior of
  431. iterating over C{bytes} on Python 2.
  432. In particular, the results of iteration are the individual bytes (rather than
  433. integers as on Python 3).
  434. @param originalBytes: A C{bytes} object that will be wrapped.
  435. """
  436. intToBytes.__doc__ = """
  437. Convert the given integer into C{bytes}, as ASCII-encoded Arab numeral.
  438. In other words, this is equivalent to calling C{bytes} in Python 2 on an
  439. integer.
  440. @param i: The C{int} to convert to C{bytes}.
  441. @rtype: C{bytes}
  442. """
  443. networkString.__doc__ = """
  444. Convert the native string type to C{bytes} if it is not already C{bytes} using
  445. ASCII encoding if conversion is necessary.
  446. This is useful for sending text-like bytes that are constructed using string
  447. interpolation. For example, this is safe on Python 2 and Python 3:
  448. networkString("Hello %d" % (n,))
  449. @param s: A native string to convert to bytes if necessary.
  450. @type s: C{str}
  451. @raise UnicodeError: The input string is not ASCII encodable/decodable.
  452. @raise TypeError: The input is neither C{bytes} nor C{unicode}.
  453. @rtype: C{bytes}
  454. """
  455. try:
  456. StringType = basestring
  457. except NameError:
  458. # Python 3+
  459. StringType = str
  460. try:
  461. from types import InstanceType
  462. except ImportError:
  463. # Python 3+
  464. InstanceType = object
  465. try:
  466. from types import FileType
  467. except ImportError:
  468. # Python 3+
  469. FileType = IOBase
  470. if _PY3:
  471. import urllib.parse as urllib_parse
  472. from html import escape
  473. from urllib.parse import quote as urlquote
  474. from urllib.parse import unquote as urlunquote
  475. from http import cookiejar as cookielib
  476. else:
  477. import urlparse as urllib_parse
  478. from cgi import escape
  479. from urllib import quote as urlquote
  480. from urllib import unquote as urlunquote
  481. import cookielib
  482. # Dealing with the differences in items/iteritems
  483. if _PY3:
  484. def iteritems(d):
  485. return d.items()
  486. def itervalues(d):
  487. return d.values()
  488. def items(d):
  489. return list(d.items())
  490. range = range
  491. xrange = range
  492. izip = zip
  493. else:
  494. def iteritems(d):
  495. return d.iteritems()
  496. def itervalues(d):
  497. return d.itervalues()
  498. def items(d):
  499. return d.items()
  500. range = xrange
  501. xrange = xrange
  502. from itertools import izip
  503. izip # shh pyflakes
  504. iteritems.__doc__ = """
  505. Return an iterable of the items of C{d}.
  506. @type d: L{dict}
  507. @rtype: iterable
  508. """
  509. itervalues.__doc__ = """
  510. Return an iterable of the values of C{d}.
  511. @type d: L{dict}
  512. @rtype: iterable
  513. """
  514. items.__doc__ = """
  515. Return a list of the items of C{d}.
  516. @type d: L{dict}
  517. @rtype: L{list}
  518. """
  519. def _keys(d):
  520. """
  521. Return a list of the keys of C{d}.
  522. @type d: L{dict}
  523. @rtype: L{list}
  524. """
  525. if _PY3:
  526. return list(d.keys())
  527. else:
  528. return d.keys()
  529. def bytesEnviron():
  530. """
  531. Return a L{dict} of L{os.environ} where all text-strings are encoded into
  532. L{bytes}.
  533. This function is POSIX only; environment variables are always text strings
  534. on Windows.
  535. """
  536. if not _PY3:
  537. # On py2, nothing to do.
  538. return dict(os.environ)
  539. target = dict()
  540. for x, y in os.environ.items():
  541. target[os.environ.encodekey(x)] = os.environ.encodevalue(y)
  542. return target
  543. def _constructMethod(cls, name, self):
  544. """
  545. Construct a bound method.
  546. @param cls: The class that the method should be bound to.
  547. @type cls: L{types.ClassType} or L{type}.
  548. @param name: The name of the method.
  549. @type name: native L{str}
  550. @param self: The object that the method is bound to.
  551. @type self: any object
  552. @return: a bound method
  553. @rtype: L{types.MethodType}
  554. """
  555. func = cls.__dict__[name]
  556. if _PY3:
  557. return _MethodType(func, self)
  558. return _MethodType(func, self, cls)
  559. from incremental import Version
  560. from twisted.python.deprecate import deprecatedModuleAttribute
  561. from collections import OrderedDict
  562. deprecatedModuleAttribute(
  563. Version("Twisted", 15, 5, 0),
  564. "Use collections.OrderedDict instead.",
  565. "twisted.python.compat",
  566. "OrderedDict")
  567. if _PY3:
  568. from base64 import encodebytes as _b64encodebytes
  569. from base64 import decodebytes as _b64decodebytes
  570. else:
  571. from base64 import encodestring as _b64encodebytes
  572. from base64 import decodestring as _b64decodebytes
  573. def _bytesChr(i):
  574. """
  575. Like L{chr} but always works on ASCII, returning L{bytes}.
  576. @param i: The ASCII code point to return.
  577. @type i: L{int}
  578. @rtype: L{bytes}
  579. """
  580. if _PY3:
  581. return bytes([i])
  582. else:
  583. return chr(i)
  584. try:
  585. from sys import intern
  586. except ImportError:
  587. intern = intern
  588. def _coercedUnicode(s):
  589. """
  590. Coerce ASCII-only byte strings into unicode for Python 2.
  591. In Python 2 C{unicode(b'bytes')} returns a unicode string C{'bytes'}. In
  592. Python 3, the equivalent C{str(b'bytes')} will return C{"b'bytes'"}
  593. instead. This function mimics the behavior for Python 2. It will decode the
  594. byte string as ASCII. In Python 3 it simply raises a L{TypeError} when
  595. passing a byte string. Unicode strings are returned as-is.
  596. @param s: The string to coerce.
  597. @type s: L{bytes} or L{unicode}
  598. @raise UnicodeError: The input L{bytes} is not ASCII decodable.
  599. @raise TypeError: The input is L{bytes} on Python 3.
  600. """
  601. if isinstance(s, bytes):
  602. if _PY3:
  603. raise TypeError("Expected str not %r (bytes)" % (s,))
  604. else:
  605. return s.decode('ascii')
  606. else:
  607. return s
  608. if _PY3:
  609. unichr = chr
  610. raw_input = input
  611. else:
  612. unichr = unichr
  613. raw_input = raw_input
  614. def _bytesRepr(bytestring):
  615. """
  616. Provide a repr for a byte string that begins with 'b' on both
  617. Python 2 and 3.
  618. @param bytestring: The string to repr.
  619. @type bytestring: L{bytes}
  620. @raise TypeError: The input is not L{bytes}.
  621. @return: The repr with a leading 'b'.
  622. @rtype: L{bytes}
  623. """
  624. if not isinstance(bytestring, bytes):
  625. raise TypeError("Expected bytes not %r" % (bytestring,))
  626. if _PY3:
  627. return repr(bytestring)
  628. else:
  629. return 'b' + repr(bytestring)
  630. if _PY3:
  631. _tokenize = tokenize.tokenize
  632. else:
  633. _tokenize = tokenize.generate_tokens
  634. __all__ = [
  635. "reraise",
  636. "execfile",
  637. "frozenset",
  638. "reduce",
  639. "set",
  640. "cmp",
  641. "comparable",
  642. "OrderedDict",
  643. "nativeString",
  644. "NativeStringIO",
  645. "networkString",
  646. "unicode",
  647. "iterbytes",
  648. "intToBytes",
  649. "lazyByteSlice",
  650. "StringType",
  651. "InstanceType",
  652. "FileType",
  653. "items",
  654. "iteritems",
  655. "itervalues",
  656. "range",
  657. "xrange",
  658. "urllib_parse",
  659. "bytesEnviron",
  660. "escape",
  661. "urlquote",
  662. "urlunquote",
  663. "cookielib",
  664. "_keys",
  665. "_b64encodebytes",
  666. "_b64decodebytes",
  667. "_bytesChr",
  668. "_coercedUnicode",
  669. "_bytesRepr",
  670. "intern",
  671. "unichr",
  672. "raw_input",
  673. "_tokenize"
  674. ]