python类PY3的实例源码

__init__.py 文件源码 项目:beepboop 作者: nicolehe 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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))
__init__.py 文件源码 项目:beepboop 作者: nicolehe 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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()
__init__.py 文件源码 项目:hackathon 作者: vertica 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
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
__init__.py 文件源码 项目:hackathon 作者: vertica 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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))
__init__.py 文件源码 项目:hackathon 作者: vertica 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
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()
__init__.py 文件源码 项目:yatta_reader 作者: sound88 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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
__init__.py 文件源码 项目:yatta_reader 作者: sound88 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
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))
__init__.py 文件源码 项目:yatta_reader 作者: sound88 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
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()
base.py 文件源码 项目:hakkuframework 作者: 4shadoww 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def expectedFailurePY3(func):
    if not PY3:
        return func
    return unittest.expectedFailure(func)
__init__.py 文件源码 项目:hakkuframework 作者: 4shadoww 项目源码 文件源码 阅读 68 收藏 0 点赞 0 评论 0
def is_py2_stdlib_module(m):
    """
    Tries to infer whether the module m is from the Python 2 standard library.
    This may not be reliable on all systems.
    """
    if PY3:
        return False
    if not 'stdlib_path' in is_py2_stdlib_module.__dict__:
        stdlib_files = [contextlib.__file__, os.__file__, copy.__file__]
        stdlib_paths = [os.path.split(f)[0] for f in stdlib_files]
        if not len(set(stdlib_paths)) == 1:
            # This seems to happen on travis-ci.org. Very strange. We'll try to
            # ignore it.
            flog.warn('Multiple locations found for the Python standard '
                         'library: %s' % stdlib_paths)
        # Choose the first one arbitrarily
        is_py2_stdlib_module.stdlib_path = stdlib_paths[0]

    if m.__name__ in sys.builtin_module_names:
        return True

    if hasattr(m, '__file__'):
        modpath = os.path.split(m.__file__)
        if (modpath[0].startswith(is_py2_stdlib_module.stdlib_path) and
            'site-packages' not in modpath[0]):
            return True

    return False
__init__.py 文件源码 项目:hakkuframework 作者: 4shadoww 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def from_import(module_name, *symbol_names, **kwargs):
    """
    Example use:
        >>> HTTPConnection = from_import('http.client', 'HTTPConnection')
        >>> HTTPServer = from_import('http.server', 'HTTPServer')
        >>> urlopen, urlparse = from_import('urllib.request', 'urlopen', 'urlparse')

    Equivalent to this on Py3:

        >>> from module_name import symbol_names[0], symbol_names[1], ...

    and this on Py2:

        >>> from future.moves.module_name import symbol_names[0], ...

    or:

        >>> from future.backports.module_name import symbol_names[0], ...

    except that it also handles dotted module names such as ``http.client``.
    """

    if PY3:
        return __import__(module_name)
    else:
        if 'backport' in kwargs and bool(kwargs['backport']):
            prefix = 'future.backports'
        else:
            prefix = 'future.moves'
        parts = prefix.split('.') + module_name.split('.')
        module = importlib.import_module(prefix + '.' + module_name)
        output = [getattr(module, name) for name in symbol_names]
        if len(output) == 1:
            return output[0]
        else:
            return output
surrogateescape.py 文件源码 项目:hakkuframework 作者: 4shadoww 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def u(text):
    if utils.PY3:
        return text
    else:
        return text.decode('unicode_escape')
surrogateescape.py 文件源码 项目:hakkuframework 作者: 4shadoww 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def b(data):
    if utils.PY3:
        return data.encode('latin1')
    else:
        return data
surrogateescape.py 文件源码 项目:hakkuframework 作者: 4shadoww 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def replace_surrogate_encode(mystring):
    """
    Returns a (unicode) string, not the more logical bytes, because the codecs
    register_error functionality expects this.
    """
    decoded = []
    for ch in mystring:
        # if utils.PY3:
        #     code = ch
        # else:
        code = ord(ch)

        # The following magic comes from Py3.3's Python/codecs.c file:
        if not 0xD800 <= code <= 0xDCFF:
            # Not a surrogate. Fail with the original exception.
            raise exc
        # mybytes = [0xe0 | (code >> 12),
        #            0x80 | ((code >> 6) & 0x3f),
        #            0x80 | (code & 0x3f)]
        # Is this a good idea?
        if 0xDC00 <= code <= 0xDC7F:
            decoded.append(_unichr(code - 0xDC00))
        elif code <= 0xDCFF:
            decoded.append(_unichr(code - 0xDC00))
        else:
            raise NotASurrogateError
    return str().join(decoded)
surrogateescape.py 文件源码 项目:hakkuframework 作者: 4shadoww 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def register_surrogateescape():
    """
    Registers the surrogateescape error handler on Python 2 (only)
    """
    if utils.PY3:
        return
    try:
        codecs.lookup_error(FS_ERRORS)
    except LookupError:
        codecs.register_error(FS_ERRORS, surrogateescape_handler)
feedparser.py 文件源码 项目:hakkuframework 作者: 4shadoww 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def __init__(self, _factory=message.Message, **_3to2kwargs):
        if 'policy' in _3to2kwargs: policy = _3to2kwargs['policy']; del _3to2kwargs['policy']
        else: policy = compat32
        """_factory is called with no arguments to create a new message obj

        The policy keyword specifies a policy object that controls a number of
        aspects of the parser's operation.  The default policy maintains
        backward compatibility.

        """
        self._factory = _factory
        self.policy = policy
        try:
            _factory(policy=self.policy)
            self._factory_kwds = lambda: {'policy': self.policy}
        except TypeError:
            # Assume this is an old-style factory
            self._factory_kwds = lambda: {}
        self._input = BufferedSubFile()
        self._msgstack = []
        if PY3:
            self._parse = self._parsegen().__next__
        else:
            self._parse = self._parsegen().next
        self._cur = None
        self._last = None
        self._headersonly = False

    # Non-public interface for supporting Parser's headersonly flag
test_builtins.py 文件源码 项目:packaging 作者: blockstack 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_isinstance_long(self):
        """
        Py2's long doesn't inherit from int!
        """
        self.assertTrue(isinstance(10**100, int))
        self.assertTrue(isinstance(int(2**64), int))
        if not PY3:
            self.assertTrue(isinstance(long(1), int))
        # Note: the following is a SyntaxError on Py3:
        # self.assertTrue(isinstance(1L, int))
test_httplib.py 文件源码 项目:packaging 作者: blockstack 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def test_bad_status_repr(self):
        exc = client.BadStatusLine('')
        if not utils.PY3:
            self.assertEqual(repr(exc), '''BadStatusLine("u\'\'",)''')
        else:
            self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
test_import_star.py 文件源码 项目:packaging 作者: blockstack 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def test_namespace_pollution_locals(self):
        if utils.PY3:
            self.assertEqual(len(new_locals), 0,
                             'namespace pollution: {0}'.format(new_locals))
        else:
            pass   # maybe check that no new symbols are introduced
test_import_star.py 文件源码 项目:packaging 作者: blockstack 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_namespace_pollution_globals(self):
        if utils.PY3:
            self.assertEqual(len(new_globals), 0,
                             'namespace pollution: {0}'.format(new_globals))
        else:
            pass   # maybe check that no new symbols are introduced


问题


面经


文章

微信
公众号

扫码关注公众号