def scrub_py2_sys_modules():
"""
Removes any Python 2 standard library modules from ``sys.modules`` that
would interfere with Py3-style imports using import hooks. Examples are
modules with the same names (like urllib or email).
(Note that currently import hooks are disabled for modules like these
with ambiguous names anyway ...)
"""
if PY3:
return {}
scrubbed = {}
for modulename in REPLACED_MODULES & set(RENAMES.keys()):
if not modulename in sys.modules:
continue
module = sys.modules[modulename]
if is_py2_stdlib_module(module):
flog.debug('Deleting (Py2) {} from sys.modules'.format(modulename))
scrubbed[modulename] = sys.modules[modulename]
del sys.modules[modulename]
return scrubbed
python类hooks()的实例源码
def install_hooks():
"""
This function installs the future.standard_library import hook into
sys.meta_path.
"""
if PY3:
return
install_aliases()
flog.debug('sys.meta_path was: {0}'.format(sys.meta_path))
flog.debug('Installing hooks ...')
# Add it unless it's there already
newhook = RenameImport(RENAMES)
if not detect_hooks():
sys.meta_path.append(newhook)
flog.debug('sys.meta_path is now: {0}'.format(sys.meta_path))
def remove_hooks(scrub_sys_modules=False):
"""
This function removes the import hook from sys.meta_path.
"""
if PY3:
return
flog.debug('Uninstalling hooks ...')
# Loop backwards, so deleting items keeps the ordering:
for i, hook in list(enumerate(sys.meta_path))[::-1]:
if hasattr(hook, 'RENAMER'):
del sys.meta_path[i]
# Explicit is better than implicit. In the future the interface should
# probably change so that scrubbing the import hooks requires a separate
# function call. Left as is for now for backward compatibility with
# v0.11.x.
if scrub_sys_modules:
scrub_future_sys_modules()
def scrub_py2_sys_modules():
"""
Removes any Python 2 standard library modules from ``sys.modules`` that
would interfere with Py3-style imports using import hooks. Examples are
modules with the same names (like urllib or email).
(Note that currently import hooks are disabled for modules like these
with ambiguous names anyway ...)
"""
if PY3:
return {}
scrubbed = {}
for modulename in REPLACED_MODULES & set(RENAMES.keys()):
if not modulename in sys.modules:
continue
module = sys.modules[modulename]
if is_py2_stdlib_module(module):
flog.debug('Deleting (Py2) {} from sys.modules'.format(modulename))
scrubbed[modulename] = sys.modules[modulename]
del sys.modules[modulename]
return scrubbed
def install_hooks():
"""
This function installs the future.standard_library import hook into
sys.meta_path.
"""
if PY3:
return
install_aliases()
flog.debug('sys.meta_path was: {0}'.format(sys.meta_path))
flog.debug('Installing hooks ...')
# Add it unless it's there already
newhook = RenameImport(RENAMES)
if not detect_hooks():
sys.meta_path.append(newhook)
flog.debug('sys.meta_path is now: {0}'.format(sys.meta_path))
def remove_hooks(scrub_sys_modules=False):
"""
This function removes the import hook from sys.meta_path.
"""
if PY3:
return
flog.debug('Uninstalling hooks ...')
# Loop backwards, so deleting items keeps the ordering:
for i, hook in list(enumerate(sys.meta_path))[::-1]:
if hasattr(hook, 'RENAMER'):
del sys.meta_path[i]
# Explicit is better than implicit. In the future the interface should
# probably change so that scrubbing the import hooks requires a separate
# function call. Left as is for now for backward compatibility with
# v0.11.x.
if scrub_sys_modules:
scrub_future_sys_modules()
def __enter__(self):
# flog.debug('Entering hooks context manager')
self.old_sys_modules = copy.copy(sys.modules)
self.hooks_were_installed = detect_hooks()
# self.scrubbed = scrub_py2_sys_modules()
install_hooks()
return self
def __exit__(self, *args):
# flog.debug('Exiting hooks context manager')
# restore_sys_modules(self.scrubbed)
if not self.hooks_were_installed:
remove_hooks()
# scrub_future_sys_modules()
# Sanity check for is_py2_stdlib_module(): We aren't replacing any
# builtin modules names:
def cache_py2_modules():
"""
Currently this function is unneeded, as we are not attempting to provide import hooks
for modules with ambiguous names: email, urllib, pickle.
"""
if len(sys.py2_modules) != 0:
return
assert not detect_hooks()
import urllib
sys.py2_modules['urllib'] = urllib
import email
sys.py2_modules['email'] = email
import pickle
sys.py2_modules['pickle'] = pickle
# Not all Python installations have test module. (Anaconda doesn't, for example.)
# try:
# import test
# except ImportError:
# sys.py2_modules['test'] = None
# sys.py2_modules['test'] = test
# import dbm
# sys.py2_modules['dbm'] = dbm
def test_urllib(self):
"""
Tests that urllib isn't changed from under our feet. (This might not
even be a problem?)
"""
from future import standard_library
import urllib
orig_file = urllib.__file__
with standard_library.hooks():
import urllib.response
self.assertEqual(orig_file, urllib.__file__)
def test_urllib_imports_cm(self):
with standard_library.hooks():
import urllib
import urllib.parse
import urllib.request
import urllib.robotparser
import urllib.error
import urllib.response
self.assertTrue(True)
def __enter__(self):
# flog.debug('Entering hooks context manager')
self.old_sys_modules = copy.copy(sys.modules)
self.hooks_were_installed = detect_hooks()
# self.scrubbed = scrub_py2_sys_modules()
install_hooks()
return self
def cache_py2_modules():
"""
Currently this function is unneeded, as we are not attempting to provide import hooks
for modules with ambiguous names: email, urllib, pickle.
"""
if len(sys.py2_modules) != 0:
return
assert not detect_hooks()
import urllib
sys.py2_modules['urllib'] = urllib
import email
sys.py2_modules['email'] = email
import pickle
sys.py2_modules['pickle'] = pickle
# Not all Python installations have test module. (Anaconda doesn't, for example.)
# try:
# import test
# except ImportError:
# sys.py2_modules['test'] = None
# sys.py2_modules['test'] = test
# import dbm
# sys.py2_modules['dbm'] = dbm
def __enter__(self):
# flog.debug('Entering hooks context manager')
self.old_sys_modules = copy.copy(sys.modules)
self.hooks_were_installed = detect_hooks()
# self.scrubbed = scrub_py2_sys_modules()
install_hooks()
return self
def __exit__(self, *args):
# flog.debug('Exiting hooks context manager')
# restore_sys_modules(self.scrubbed)
if not self.hooks_were_installed:
remove_hooks()
# scrub_future_sys_modules()
# Sanity check for is_py2_stdlib_module(): We aren't replacing any
# builtin modules names:
def cache_py2_modules():
"""
Currently this function is unneeded, as we are not attempting to provide import hooks
for modules with ambiguous names: email, urllib, pickle.
"""
if len(sys.py2_modules) != 0:
return
assert not detect_hooks()
import urllib
sys.py2_modules['urllib'] = urllib
import email
sys.py2_modules['email'] = email
import pickle
sys.py2_modules['pickle'] = pickle
# Not all Python installations have test module. (Anaconda doesn't, for example.)
# try:
# import test
# except ImportError:
# sys.py2_modules['test'] = None
# sys.py2_modules['test'] = test
# import dbm
# sys.py2_modules['dbm'] = dbm
def __enter__(self):
# flog.debug('Entering hooks context manager')
self.old_sys_modules = copy.copy(sys.modules)
self.hooks_were_installed = detect_hooks()
# self.scrubbed = scrub_py2_sys_modules()
install_hooks()
return self
def __exit__(self, *args):
# flog.debug('Exiting hooks context manager')
# restore_sys_modules(self.scrubbed)
if not self.hooks_were_installed:
remove_hooks()
# scrub_future_sys_modules()
# Sanity check for is_py2_stdlib_module(): We aren't replacing any
# builtin modules names:
def cache_py2_modules():
"""
Currently this function is unneeded, as we are not attempting to provide import hooks
for modules with ambiguous names: email, urllib, pickle.
"""
if len(sys.py2_modules) != 0:
return
assert not detect_hooks()
import urllib
sys.py2_modules['urllib'] = urllib
import email
sys.py2_modules['email'] = email
import pickle
sys.py2_modules['pickle'] = pickle
# Not all Python installations have test module. (Anaconda doesn't, for example.)
# try:
# import test
# except ImportError:
# sys.py2_modules['test'] = None
# sys.py2_modules['test'] = test
# import dbm
# sys.py2_modules['dbm'] = dbm
def __enter__(self):
# flog.debug('Entering hooks context manager')
self.old_sys_modules = copy.copy(sys.modules)
self.hooks_were_installed = detect_hooks()
# self.scrubbed = scrub_py2_sys_modules()
install_hooks()
return self