compat.py 23 KB

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