__init__.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. """
  2. Python 3 reorganized the standard library (PEP 3108). This module exposes
  3. several standard library modules to Python 2 under their new Python 3
  4. names.
  5. It is designed to be used as follows::
  6. from future import standard_library
  7. standard_library.install_aliases()
  8. And then these normal Py3 imports work on both Py3 and Py2::
  9. import builtins
  10. import copyreg
  11. import queue
  12. import reprlib
  13. import socketserver
  14. import winreg # on Windows only
  15. import test.support
  16. import html, html.parser, html.entities
  17. import http, http.client, http.server
  18. import http.cookies, http.cookiejar
  19. import urllib.parse, urllib.request, urllib.response, urllib.error, urllib.robotparser
  20. import xmlrpc.client, xmlrpc.server
  21. import _thread
  22. import _dummy_thread
  23. import _markupbase
  24. from itertools import filterfalse, zip_longest
  25. from sys import intern
  26. from collections import UserDict, UserList, UserString
  27. from collections import OrderedDict, Counter, ChainMap # even on Py2.6
  28. from subprocess import getoutput, getstatusoutput
  29. from subprocess import check_output # even on Py2.6
  30. from multiprocessing import SimpleQueue
  31. (The renamed modules and functions are still available under their old
  32. names on Python 2.)
  33. This is a cleaner alternative to this idiom (see
  34. http://docs.pythonsprints.com/python3_porting/py-porting.html)::
  35. try:
  36. import queue
  37. except ImportError:
  38. import Queue as queue
  39. Limitations
  40. -----------
  41. We don't currently support these modules, but would like to::
  42. import dbm
  43. import dbm.dumb
  44. import dbm.gnu
  45. import collections.abc # on Py33
  46. import pickle # should (optionally) bring in cPickle on Python 2
  47. """
  48. from __future__ import absolute_import, division, print_function
  49. import sys
  50. import logging
  51. # imp was deprecated in python 3.6
  52. if sys.version_info >= (3, 6):
  53. import importlib as imp
  54. else:
  55. import imp
  56. import contextlib
  57. import copy
  58. import os
  59. # Make a dedicated logger; leave the root logger to be configured
  60. # by the application.
  61. flog = logging.getLogger('future_stdlib')
  62. _formatter = logging.Formatter(logging.BASIC_FORMAT)
  63. _handler = logging.StreamHandler()
  64. _handler.setFormatter(_formatter)
  65. flog.addHandler(_handler)
  66. flog.setLevel(logging.WARN)
  67. from future.utils import PY2, PY3
  68. # The modules that are defined under the same names on Py3 but with
  69. # different contents in a significant way (e.g. submodules) are:
  70. # pickle (fast one)
  71. # dbm
  72. # urllib
  73. # test
  74. # email
  75. REPLACED_MODULES = set(['test', 'urllib', 'pickle', 'dbm']) # add email and dbm when we support it
  76. # The following module names are not present in Python 2.x, so they cause no
  77. # potential clashes between the old and new names:
  78. # http
  79. # html
  80. # tkinter
  81. # xmlrpc
  82. # Keys: Py2 / real module names
  83. # Values: Py3 / simulated module names
  84. RENAMES = {
  85. # 'cStringIO': 'io', # there's a new io module in Python 2.6
  86. # that provides StringIO and BytesIO
  87. # 'StringIO': 'io', # ditto
  88. # 'cPickle': 'pickle',
  89. '__builtin__': 'builtins',
  90. 'copy_reg': 'copyreg',
  91. 'Queue': 'queue',
  92. 'future.moves.socketserver': 'socketserver',
  93. 'ConfigParser': 'configparser',
  94. 'repr': 'reprlib',
  95. 'multiprocessing.queues': 'multiprocessing',
  96. # 'FileDialog': 'tkinter.filedialog',
  97. # 'tkFileDialog': 'tkinter.filedialog',
  98. # 'SimpleDialog': 'tkinter.simpledialog',
  99. # 'tkSimpleDialog': 'tkinter.simpledialog',
  100. # 'tkColorChooser': 'tkinter.colorchooser',
  101. # 'tkCommonDialog': 'tkinter.commondialog',
  102. # 'Dialog': 'tkinter.dialog',
  103. # 'Tkdnd': 'tkinter.dnd',
  104. # 'tkFont': 'tkinter.font',
  105. # 'tkMessageBox': 'tkinter.messagebox',
  106. # 'ScrolledText': 'tkinter.scrolledtext',
  107. # 'Tkconstants': 'tkinter.constants',
  108. # 'Tix': 'tkinter.tix',
  109. # 'ttk': 'tkinter.ttk',
  110. # 'Tkinter': 'tkinter',
  111. '_winreg': 'winreg',
  112. 'thread': '_thread',
  113. 'dummy_thread': '_dummy_thread' if sys.version_info < (3, 9) else '_thread',
  114. # 'anydbm': 'dbm', # causes infinite import loop
  115. # 'whichdb': 'dbm', # causes infinite import loop
  116. # anydbm and whichdb are handled by fix_imports2
  117. # 'dbhash': 'dbm.bsd',
  118. # 'dumbdbm': 'dbm.dumb',
  119. # 'dbm': 'dbm.ndbm',
  120. # 'gdbm': 'dbm.gnu',
  121. 'future.moves.xmlrpc': 'xmlrpc',
  122. # 'future.backports.email': 'email', # for use by urllib
  123. # 'DocXMLRPCServer': 'xmlrpc.server',
  124. # 'SimpleXMLRPCServer': 'xmlrpc.server',
  125. # 'httplib': 'http.client',
  126. # 'htmlentitydefs' : 'html.entities',
  127. # 'HTMLParser' : 'html.parser',
  128. # 'Cookie': 'http.cookies',
  129. # 'cookielib': 'http.cookiejar',
  130. # 'BaseHTTPServer': 'http.server',
  131. # 'SimpleHTTPServer': 'http.server',
  132. # 'CGIHTTPServer': 'http.server',
  133. # 'future.backports.test': 'test', # primarily for renaming test_support to support
  134. # 'commands': 'subprocess',
  135. # 'urlparse' : 'urllib.parse',
  136. # 'robotparser' : 'urllib.robotparser',
  137. # 'abc': 'collections.abc', # for Py33
  138. # 'future.utils.six.moves.html': 'html',
  139. # 'future.utils.six.moves.http': 'http',
  140. 'future.moves.html': 'html',
  141. 'future.moves.http': 'http',
  142. # 'future.backports.urllib': 'urllib',
  143. # 'future.utils.six.moves.urllib': 'urllib',
  144. 'future.moves._markupbase': '_markupbase',
  145. }
  146. # It is complicated and apparently brittle to mess around with the
  147. # ``sys.modules`` cache in order to support "import urllib" meaning two
  148. # different things (Py2.7 urllib and backported Py3.3-like urllib) in different
  149. # contexts. So we require explicit imports for these modules.
  150. assert len(set(RENAMES.values()) & set(REPLACED_MODULES)) == 0
  151. # Harmless renames that we can insert.
  152. # These modules need names from elsewhere being added to them:
  153. # subprocess: should provide getoutput and other fns from commands
  154. # module but these fns are missing: getstatus, mk2arg,
  155. # mkarg
  156. # re: needs an ASCII constant that works compatibly with Py3
  157. # etc: see lib2to3/fixes/fix_imports.py
  158. # (New module name, new object name, old module name, old object name)
  159. MOVES = [('collections', 'UserList', 'UserList', 'UserList'),
  160. ('collections', 'UserDict', 'UserDict', 'UserDict'),
  161. ('collections', 'UserString','UserString', 'UserString'),
  162. ('collections', 'ChainMap', 'future.backports.misc', 'ChainMap'),
  163. ('itertools', 'filterfalse','itertools', 'ifilterfalse'),
  164. ('itertools', 'zip_longest','itertools', 'izip_longest'),
  165. ('sys', 'intern','__builtin__', 'intern'),
  166. ('multiprocessing', 'SimpleQueue', 'multiprocessing.queues', 'SimpleQueue'),
  167. # The re module has no ASCII flag in Py2, but this is the default.
  168. # Set re.ASCII to a zero constant. stat.ST_MODE just happens to be one
  169. # (and it exists on Py2.6+).
  170. ('re', 'ASCII','stat', 'ST_MODE'),
  171. ('base64', 'encodebytes','base64', 'encodestring'),
  172. ('base64', 'decodebytes','base64', 'decodestring'),
  173. ('subprocess', 'getoutput', 'commands', 'getoutput'),
  174. ('subprocess', 'getstatusoutput', 'commands', 'getstatusoutput'),
  175. ('subprocess', 'check_output', 'future.backports.misc', 'check_output'),
  176. ('math', 'ceil', 'future.backports.misc', 'ceil'),
  177. ('collections', 'OrderedDict', 'future.backports.misc', 'OrderedDict'),
  178. ('collections', 'Counter', 'future.backports.misc', 'Counter'),
  179. ('collections', 'ChainMap', 'future.backports.misc', 'ChainMap'),
  180. ('itertools', 'count', 'future.backports.misc', 'count'),
  181. ('reprlib', 'recursive_repr', 'future.backports.misc', 'recursive_repr'),
  182. ('functools', 'cmp_to_key', 'future.backports.misc', 'cmp_to_key'),
  183. # This is no use, since "import urllib.request" etc. still fails:
  184. # ('urllib', 'error', 'future.moves.urllib', 'error'),
  185. # ('urllib', 'parse', 'future.moves.urllib', 'parse'),
  186. # ('urllib', 'request', 'future.moves.urllib', 'request'),
  187. # ('urllib', 'response', 'future.moves.urllib', 'response'),
  188. # ('urllib', 'robotparser', 'future.moves.urllib', 'robotparser'),
  189. ]
  190. # A minimal example of an import hook:
  191. # class WarnOnImport(object):
  192. # def __init__(self, *args):
  193. # self.module_names = args
  194. #
  195. # def find_module(self, fullname, path=None):
  196. # if fullname in self.module_names:
  197. # self.path = path
  198. # return self
  199. # return None
  200. #
  201. # def load_module(self, name):
  202. # if name in sys.modules:
  203. # return sys.modules[name]
  204. # module_info = imp.find_module(name, self.path)
  205. # module = imp.load_module(name, *module_info)
  206. # sys.modules[name] = module
  207. # flog.warning("Imported deprecated module %s", name)
  208. # return module
  209. class RenameImport(object):
  210. """
  211. A class for import hooks mapping Py3 module names etc. to the Py2 equivalents.
  212. """
  213. # Different RenameImport classes are created when importing this module from
  214. # different source files. This causes isinstance(hook, RenameImport) checks
  215. # to produce inconsistent results. We add this RENAMER attribute here so
  216. # remove_hooks() and install_hooks() can find instances of these classes
  217. # easily:
  218. RENAMER = True
  219. def __init__(self, old_to_new):
  220. '''
  221. Pass in a dictionary-like object mapping from old names to new
  222. names. E.g. {'ConfigParser': 'configparser', 'cPickle': 'pickle'}
  223. '''
  224. self.old_to_new = old_to_new
  225. both = set(old_to_new.keys()) & set(old_to_new.values())
  226. assert (len(both) == 0 and
  227. len(set(old_to_new.values())) == len(old_to_new.values())), \
  228. 'Ambiguity in renaming (handler not implemented)'
  229. self.new_to_old = dict((new, old) for (old, new) in old_to_new.items())
  230. def find_module(self, fullname, path=None):
  231. # Handles hierarchical importing: package.module.module2
  232. new_base_names = set([s.split('.')[0] for s in self.new_to_old])
  233. # Before v0.12: Was: if fullname in set(self.old_to_new) | new_base_names:
  234. if fullname in new_base_names:
  235. return self
  236. return None
  237. def load_module(self, name):
  238. path = None
  239. if name in sys.modules:
  240. return sys.modules[name]
  241. elif name in self.new_to_old:
  242. # New name. Look up the corresponding old (Py2) name:
  243. oldname = self.new_to_old[name]
  244. module = self._find_and_load_module(oldname)
  245. # module.__future_module__ = True
  246. else:
  247. module = self._find_and_load_module(name)
  248. # In any case, make it available under the requested (Py3) name
  249. sys.modules[name] = module
  250. return module
  251. def _find_and_load_module(self, name, path=None):
  252. """
  253. Finds and loads it. But if there's a . in the name, handles it
  254. properly.
  255. """
  256. bits = name.split('.')
  257. while len(bits) > 1:
  258. # Treat the first bit as a package
  259. packagename = bits.pop(0)
  260. package = self._find_and_load_module(packagename, path)
  261. try:
  262. path = package.__path__
  263. except AttributeError:
  264. # This could be e.g. moves.
  265. flog.debug('Package {0} has no __path__.'.format(package))
  266. if name in sys.modules:
  267. return sys.modules[name]
  268. flog.debug('What to do here?')
  269. name = bits[0]
  270. module_info = imp.find_module(name, path)
  271. return imp.load_module(name, *module_info)
  272. class hooks(object):
  273. """
  274. Acts as a context manager. Saves the state of sys.modules and restores it
  275. after the 'with' block.
  276. Use like this:
  277. >>> from future import standard_library
  278. >>> with standard_library.hooks():
  279. ... import http.client
  280. >>> import requests
  281. For this to work, http.client will be scrubbed from sys.modules after the
  282. 'with' block. That way the modules imported in the 'with' block will
  283. continue to be accessible in the current namespace but not from any
  284. imported modules (like requests).
  285. """
  286. def __enter__(self):
  287. # flog.debug('Entering hooks context manager')
  288. self.old_sys_modules = copy.copy(sys.modules)
  289. self.hooks_were_installed = detect_hooks()
  290. # self.scrubbed = scrub_py2_sys_modules()
  291. install_hooks()
  292. return self
  293. def __exit__(self, *args):
  294. # flog.debug('Exiting hooks context manager')
  295. # restore_sys_modules(self.scrubbed)
  296. if not self.hooks_were_installed:
  297. remove_hooks()
  298. # scrub_future_sys_modules()
  299. # Sanity check for is_py2_stdlib_module(): We aren't replacing any
  300. # builtin modules names:
  301. if PY2:
  302. assert len(set(RENAMES.values()) & set(sys.builtin_module_names)) == 0
  303. def is_py2_stdlib_module(m):
  304. """
  305. Tries to infer whether the module m is from the Python 2 standard library.
  306. This may not be reliable on all systems.
  307. """
  308. if PY3:
  309. return False
  310. if not 'stdlib_path' in is_py2_stdlib_module.__dict__:
  311. stdlib_files = [contextlib.__file__, os.__file__, copy.__file__]
  312. stdlib_paths = [os.path.split(f)[0] for f in stdlib_files]
  313. if not len(set(stdlib_paths)) == 1:
  314. # This seems to happen on travis-ci.org. Very strange. We'll try to
  315. # ignore it.
  316. flog.warn('Multiple locations found for the Python standard '
  317. 'library: %s' % stdlib_paths)
  318. # Choose the first one arbitrarily
  319. is_py2_stdlib_module.stdlib_path = stdlib_paths[0]
  320. if m.__name__ in sys.builtin_module_names:
  321. return True
  322. if hasattr(m, '__file__'):
  323. modpath = os.path.split(m.__file__)
  324. if (modpath[0].startswith(is_py2_stdlib_module.stdlib_path) and
  325. 'site-packages' not in modpath[0]):
  326. return True
  327. return False
  328. def scrub_py2_sys_modules():
  329. """
  330. Removes any Python 2 standard library modules from ``sys.modules`` that
  331. would interfere with Py3-style imports using import hooks. Examples are
  332. modules with the same names (like urllib or email).
  333. (Note that currently import hooks are disabled for modules like these
  334. with ambiguous names anyway ...)
  335. """
  336. if PY3:
  337. return {}
  338. scrubbed = {}
  339. for modulename in REPLACED_MODULES & set(RENAMES.keys()):
  340. if not modulename in sys.modules:
  341. continue
  342. module = sys.modules[modulename]
  343. if is_py2_stdlib_module(module):
  344. flog.debug('Deleting (Py2) {} from sys.modules'.format(modulename))
  345. scrubbed[modulename] = sys.modules[modulename]
  346. del sys.modules[modulename]
  347. return scrubbed
  348. def scrub_future_sys_modules():
  349. """
  350. Deprecated.
  351. """
  352. return {}
  353. class suspend_hooks(object):
  354. """
  355. Acts as a context manager. Use like this:
  356. >>> from future import standard_library
  357. >>> standard_library.install_hooks()
  358. >>> import http.client
  359. >>> # ...
  360. >>> with standard_library.suspend_hooks():
  361. >>> import requests # incompatible with ``future``'s standard library hooks
  362. If the hooks were disabled before the context, they are not installed when
  363. the context is left.
  364. """
  365. def __enter__(self):
  366. self.hooks_were_installed = detect_hooks()
  367. remove_hooks()
  368. # self.scrubbed = scrub_future_sys_modules()
  369. return self
  370. def __exit__(self, *args):
  371. if self.hooks_were_installed:
  372. install_hooks()
  373. # restore_sys_modules(self.scrubbed)
  374. def restore_sys_modules(scrubbed):
  375. """
  376. Add any previously scrubbed modules back to the sys.modules cache,
  377. but only if it's safe to do so.
  378. """
  379. clash = set(sys.modules) & set(scrubbed)
  380. if len(clash) != 0:
  381. # If several, choose one arbitrarily to raise an exception about
  382. first = list(clash)[0]
  383. raise ImportError('future module {} clashes with Py2 module'
  384. .format(first))
  385. sys.modules.update(scrubbed)
  386. def install_aliases():
  387. """
  388. Monkey-patches the standard library in Py2.6/7 to provide
  389. aliases for better Py3 compatibility.
  390. """
  391. if PY3:
  392. return
  393. # if hasattr(install_aliases, 'run_already'):
  394. # return
  395. for (newmodname, newobjname, oldmodname, oldobjname) in MOVES:
  396. __import__(newmodname)
  397. # We look up the module in sys.modules because __import__ just returns the
  398. # top-level package:
  399. newmod = sys.modules[newmodname]
  400. # newmod.__future_module__ = True
  401. __import__(oldmodname)
  402. oldmod = sys.modules[oldmodname]
  403. obj = getattr(oldmod, oldobjname)
  404. setattr(newmod, newobjname, obj)
  405. # Hack for urllib so it appears to have the same structure on Py2 as on Py3
  406. import urllib
  407. from future.backports.urllib import request
  408. from future.backports.urllib import response
  409. from future.backports.urllib import parse
  410. from future.backports.urllib import error
  411. from future.backports.urllib import robotparser
  412. urllib.request = request
  413. urllib.response = response
  414. urllib.parse = parse
  415. urllib.error = error
  416. urllib.robotparser = robotparser
  417. sys.modules['urllib.request'] = request
  418. sys.modules['urllib.response'] = response
  419. sys.modules['urllib.parse'] = parse
  420. sys.modules['urllib.error'] = error
  421. sys.modules['urllib.robotparser'] = robotparser
  422. # Patch the test module so it appears to have the same structure on Py2 as on Py3
  423. try:
  424. import test
  425. except ImportError:
  426. pass
  427. try:
  428. from future.moves.test import support
  429. except ImportError:
  430. pass
  431. else:
  432. test.support = support
  433. sys.modules['test.support'] = support
  434. # Patch the dbm module so it appears to have the same structure on Py2 as on Py3
  435. try:
  436. import dbm
  437. except ImportError:
  438. pass
  439. else:
  440. from future.moves.dbm import dumb
  441. dbm.dumb = dumb
  442. sys.modules['dbm.dumb'] = dumb
  443. try:
  444. from future.moves.dbm import gnu
  445. except ImportError:
  446. pass
  447. else:
  448. dbm.gnu = gnu
  449. sys.modules['dbm.gnu'] = gnu
  450. try:
  451. from future.moves.dbm import ndbm
  452. except ImportError:
  453. pass
  454. else:
  455. dbm.ndbm = ndbm
  456. sys.modules['dbm.ndbm'] = ndbm
  457. # install_aliases.run_already = True
  458. def install_hooks():
  459. """
  460. This function installs the future.standard_library import hook into
  461. sys.meta_path.
  462. """
  463. if PY3:
  464. return
  465. install_aliases()
  466. flog.debug('sys.meta_path was: {0}'.format(sys.meta_path))
  467. flog.debug('Installing hooks ...')
  468. # Add it unless it's there already
  469. newhook = RenameImport(RENAMES)
  470. if not detect_hooks():
  471. sys.meta_path.append(newhook)
  472. flog.debug('sys.meta_path is now: {0}'.format(sys.meta_path))
  473. def enable_hooks():
  474. """
  475. Deprecated. Use install_hooks() instead. This will be removed by
  476. ``future`` v1.0.
  477. """
  478. install_hooks()
  479. def remove_hooks(scrub_sys_modules=False):
  480. """
  481. This function removes the import hook from sys.meta_path.
  482. """
  483. if PY3:
  484. return
  485. flog.debug('Uninstalling hooks ...')
  486. # Loop backwards, so deleting items keeps the ordering:
  487. for i, hook in list(enumerate(sys.meta_path))[::-1]:
  488. if hasattr(hook, 'RENAMER'):
  489. del sys.meta_path[i]
  490. # Explicit is better than implicit. In the future the interface should
  491. # probably change so that scrubbing the import hooks requires a separate
  492. # function call. Left as is for now for backward compatibility with
  493. # v0.11.x.
  494. if scrub_sys_modules:
  495. scrub_future_sys_modules()
  496. def disable_hooks():
  497. """
  498. Deprecated. Use remove_hooks() instead. This will be removed by
  499. ``future`` v1.0.
  500. """
  501. remove_hooks()
  502. def detect_hooks():
  503. """
  504. Returns True if the import hooks are installed, False if not.
  505. """
  506. flog.debug('Detecting hooks ...')
  507. present = any([hasattr(hook, 'RENAMER') for hook in sys.meta_path])
  508. if present:
  509. flog.debug('Detected.')
  510. else:
  511. flog.debug('Not detected.')
  512. return present
  513. # As of v0.12, this no longer happens implicitly:
  514. # if not PY3:
  515. # install_hooks()
  516. if not hasattr(sys, 'py2_modules'):
  517. sys.py2_modules = {}
  518. def cache_py2_modules():
  519. """
  520. Currently this function is unneeded, as we are not attempting to provide import hooks
  521. for modules with ambiguous names: email, urllib, pickle.
  522. """
  523. if len(sys.py2_modules) != 0:
  524. return
  525. assert not detect_hooks()
  526. import urllib
  527. sys.py2_modules['urllib'] = urllib
  528. import email
  529. sys.py2_modules['email'] = email
  530. import pickle
  531. sys.py2_modules['pickle'] = pickle
  532. # Not all Python installations have test module. (Anaconda doesn't, for example.)
  533. # try:
  534. # import test
  535. # except ImportError:
  536. # sys.py2_modules['test'] = None
  537. # sys.py2_modules['test'] = test
  538. # import dbm
  539. # sys.py2_modules['dbm'] = dbm
  540. def import_(module_name, backport=False):
  541. """
  542. Pass a (potentially dotted) module name of a Python 3 standard library
  543. module. This function imports the module compatibly on Py2 and Py3 and
  544. returns the top-level module.
  545. Example use:
  546. >>> http = import_('http.client')
  547. >>> http = import_('http.server')
  548. >>> urllib = import_('urllib.request')
  549. Then:
  550. >>> conn = http.client.HTTPConnection(...)
  551. >>> response = urllib.request.urlopen('http://mywebsite.com')
  552. >>> # etc.
  553. Use as follows:
  554. >>> package_name = import_(module_name)
  555. On Py3, equivalent to this:
  556. >>> import module_name
  557. On Py2, equivalent to this if backport=False:
  558. >>> from future.moves import module_name
  559. or to this if backport=True:
  560. >>> from future.backports import module_name
  561. except that it also handles dotted module names such as ``http.client``
  562. The effect then is like this:
  563. >>> from future.backports import module
  564. >>> from future.backports.module import submodule
  565. >>> module.submodule = submodule
  566. Note that this would be a SyntaxError in Python:
  567. >>> from future.backports import http.client
  568. """
  569. # Python 2.6 doesn't have importlib in the stdlib, so it requires
  570. # the backported ``importlib`` package from PyPI as a dependency to use
  571. # this function:
  572. import importlib
  573. if PY3:
  574. return __import__(module_name)
  575. else:
  576. # client.blah = blah
  577. # Then http.client = client
  578. # etc.
  579. if backport:
  580. prefix = 'future.backports'
  581. else:
  582. prefix = 'future.moves'
  583. parts = prefix.split('.') + module_name.split('.')
  584. modules = []
  585. for i, part in enumerate(parts):
  586. sofar = '.'.join(parts[:i+1])
  587. modules.append(importlib.import_module(sofar))
  588. for i, part in reversed(list(enumerate(parts))):
  589. if i == 0:
  590. break
  591. setattr(modules[i-1], part, modules[i])
  592. # Return the next-most top-level module after future.backports / future.moves:
  593. return modules[2]
  594. def from_import(module_name, *symbol_names, **kwargs):
  595. """
  596. Example use:
  597. >>> HTTPConnection = from_import('http.client', 'HTTPConnection')
  598. >>> HTTPServer = from_import('http.server', 'HTTPServer')
  599. >>> urlopen, urlparse = from_import('urllib.request', 'urlopen', 'urlparse')
  600. Equivalent to this on Py3:
  601. >>> from module_name import symbol_names[0], symbol_names[1], ...
  602. and this on Py2:
  603. >>> from future.moves.module_name import symbol_names[0], ...
  604. or:
  605. >>> from future.backports.module_name import symbol_names[0], ...
  606. except that it also handles dotted module names such as ``http.client``.
  607. """
  608. if PY3:
  609. return __import__(module_name)
  610. else:
  611. if 'backport' in kwargs and bool(kwargs['backport']):
  612. prefix = 'future.backports'
  613. else:
  614. prefix = 'future.moves'
  615. parts = prefix.split('.') + module_name.split('.')
  616. module = importlib.import_module(prefix + '.' + module_name)
  617. output = [getattr(module, name) for name in symbol_names]
  618. if len(output) == 1:
  619. return output[0]
  620. else:
  621. return output
  622. class exclude_local_folder_imports(object):
  623. """
  624. A context-manager that prevents standard library modules like configparser
  625. from being imported from the local python-future source folder on Py3.
  626. (This was need prior to v0.16.0 because the presence of a configparser
  627. folder would otherwise have prevented setuptools from running on Py3. Maybe
  628. it's not needed any more?)
  629. """
  630. def __init__(self, *args):
  631. assert len(args) > 0
  632. self.module_names = args
  633. # Disallow dotted module names like http.client:
  634. if any(['.' in m for m in self.module_names]):
  635. raise NotImplementedError('Dotted module names are not supported')
  636. def __enter__(self):
  637. self.old_sys_path = copy.copy(sys.path)
  638. self.old_sys_modules = copy.copy(sys.modules)
  639. if sys.version_info[0] < 3:
  640. return
  641. # The presence of all these indicates we've found our source folder,
  642. # because `builtins` won't have been installed in site-packages by setup.py:
  643. FUTURE_SOURCE_SUBFOLDERS = ['future', 'past', 'libfuturize', 'libpasteurize', 'builtins']
  644. # Look for the future source folder:
  645. for folder in self.old_sys_path:
  646. if all([os.path.exists(os.path.join(folder, subfolder))
  647. for subfolder in FUTURE_SOURCE_SUBFOLDERS]):
  648. # Found it. Remove it.
  649. sys.path.remove(folder)
  650. # Ensure we import the system module:
  651. for m in self.module_names:
  652. # Delete the module and any submodules from sys.modules:
  653. # for key in list(sys.modules):
  654. # if key == m or key.startswith(m + '.'):
  655. # try:
  656. # del sys.modules[key]
  657. # except KeyError:
  658. # pass
  659. try:
  660. module = __import__(m, level=0)
  661. except ImportError:
  662. # There's a problem importing the system module. E.g. the
  663. # winreg module is not available except on Windows.
  664. pass
  665. def __exit__(self, *args):
  666. # Restore sys.path and sys.modules:
  667. sys.path = self.old_sys_path
  668. for m in set(self.old_sys_modules.keys()) - set(sys.modules.keys()):
  669. sys.modules[m] = self.old_sys_modules[m]
  670. TOP_LEVEL_MODULES = ['builtins',
  671. 'copyreg',
  672. 'html',
  673. 'http',
  674. 'queue',
  675. 'reprlib',
  676. 'socketserver',
  677. 'test',
  678. 'tkinter',
  679. 'winreg',
  680. 'xmlrpc',
  681. '_dummy_thread',
  682. '_markupbase',
  683. '_thread',
  684. ]
  685. def import_top_level_modules():
  686. with exclude_local_folder_imports(*TOP_LEVEL_MODULES):
  687. for m in TOP_LEVEL_MODULES:
  688. try:
  689. __import__(m)
  690. except ImportError: # e.g. winreg
  691. pass