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类PY3的实例源码
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 test_py2k_disabled_builtins(self):
"""
On Py2 these should import.
"""
if not utils.PY3:
from future.builtins.disabled import (apply,
cmp,
coerce,
execfile,
file,
long,
raw_input,
reduce,
reload,
unicode,
xrange,
StandardError)
def test_python_2_unicode_compatible_decorator(self):
my_unicode_str = u'Unicode string: \u5b54\u5b50'
# With the decorator:
@python_2_unicode_compatible
class A(object):
def __str__(self):
return my_unicode_str
a = A()
assert len(str(a)) == 18
if not utils.PY3:
assert hasattr(a, '__unicode__')
self.assertEqual(str(a), my_unicode_str)
self.assertTrue(isinstance(str(a).encode('utf-8'), bytes))
# Manual equivalent on Py2 without the decorator:
if not utils.PY3:
class B(object):
def __unicode__(self):
return u'Unicode string: \u5b54\u5b50'
def __str__(self):
return unicode(self).encode('utf-8')
b = B()
assert str(a) == str(b)
def sendall(self, data):
# self.data += bytes(data)
olddata = self.data
assert isinstance(olddata, bytes)
if utils.PY3:
self.data += data
else:
if isinstance(data, type(u'')): # i.e. unicode
newdata = data.encode('ascii')
elif isinstance(data, type(b'')): # native string type. FIXME!
newdata = bytes(data)
elif isinstance(data, bytes):
newdata = data
elif isinstance(data, array.array):
newdata = data.tostring()
else:
newdata = bytes(b'').join(chr(d) for d in bytes(data))
self.data += newdata
def test_setdefault_atomic(self):
# Issue #13521: setdefault() calls __hash__ and __eq__ only once.
class Hashed(object):
def __init__(self):
self.hash_count = 0
self.eq_count = 0
def __hash__(self):
self.hash_count += 1
return 42
def __eq__(self, other):
self.eq_count += 1
return id(self) == id(other)
hashed1 = Hashed()
y = dict({hashed1: 5})
hashed2 = Hashed()
y.setdefault(hashed2, [])
self.assertEqual(hashed1.hash_count, 1)
if PY3:
self.assertEqual(hashed2.hash_count, 1)
self.assertEqual(hashed1.eq_count + hashed2.eq_count, 1)
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 detect_hooks():
"""
Returns True if the import hooks are installed, False if not.
"""
flog.debug('Detecting hooks ...')
present = any([hasattr(hook, 'RENAMER') for hook in sys.meta_path])
if present:
flog.debug('Detected.')
else:
flog.debug('Not detected.')
return present
# As of v0.12, this no longer happens implicitly:
# if not PY3:
# install_hooks()
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 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 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 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 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 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 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