__init__.py 27 KB

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