當前位置: 首頁>>代碼示例>>Python>>正文


Python newbytes.newbytes方法代碼示例

本文整理匯總了Python中future.types.newbytes.newbytes方法的典型用法代碼示例。如果您正苦於以下問題:Python newbytes.newbytes方法的具體用法?Python newbytes.newbytes怎麽用?Python newbytes.newbytes使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在future.types.newbytes的用法示例。


在下文中一共展示了newbytes.newbytes方法的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: native_str_to_bytes

# 需要導入模塊: from future.types import newbytes [as 別名]
# 或者: from future.types.newbytes import newbytes [as 別名]
def native_str_to_bytes(s, encoding=None):
        from future.types import newbytes    # to avoid a circular import
        return newbytes(s) 
開發者ID:Soft8Soft,項目名稱:verge3d-blender-addon,代碼行數:5,代碼來源:__init__.py

示例2: isnewbytes

# 需要導入模塊: from future.types import newbytes [as 別名]
# 或者: from future.types.newbytes import newbytes [as 別名]
def isnewbytes(obj):
    """
    Equivalent to the result of ``isinstance(obj, newbytes)`` were
    ``__instancecheck__`` not overridden on the newbytes subclass. In
    other words, it is REALLY a newbytes instance, not a Py2 native str
    object?
    """
    # TODO: generalize this so that it works with subclasses of newbytes
    # Import is here to avoid circular imports:
    from future.types.newbytes import newbytes
    return type(obj) == newbytes 
開發者ID:Soft8Soft,項目名稱:verge3d-blender-addon,代碼行數:13,代碼來源:__init__.py

示例3: ensure_new_type

# 需要導入模塊: from future.types import newbytes [as 別名]
# 或者: from future.types.newbytes import newbytes [as 別名]
def ensure_new_type(obj):
        from future.types.newbytes import newbytes
        from future.types.newstr import newstr
        from future.types.newint import newint
        from future.types.newdict import newdict

        native_type = type(native(obj))

        # Upcast only if the type is already a native (non-future) type
        if issubclass(native_type, type(obj)):
            # Upcast
            if native_type == str:  # i.e. Py2 8-bit str
                return newbytes(obj)
            elif native_type == unicode:
                return newstr(obj)
            elif native_type == int:
                return newint(obj)
            elif native_type == long:
                return newint(obj)
            elif native_type == dict:
                return newdict(obj)
            else:
                return obj
        else:
            # Already a new type
            assert type(obj) in [newbytes, newstr]
            return obj 
開發者ID:Soft8Soft,項目名稱:verge3d-blender-addon,代碼行數:29,代碼來源:__init__.py

示例4: __new__

# 需要導入模塊: from future.types import newbytes [as 別名]
# 或者: from future.types.newbytes import newbytes [as 別名]
def __new__(cls, *args, **kwargs):
        """
        From the Py3 str docstring:

          str(object='') -> str
          str(bytes_or_buffer[, encoding[, errors]]) -> str
          
          Create a new string object from the given object. If encoding or
          errors is specified, then the object must expose a data buffer
          that will be decoded using the given encoding and error handler.
          Otherwise, returns the result of object.__str__() (if defined)
          or repr(object).
          encoding defaults to sys.getdefaultencoding().
          errors defaults to 'strict'.
        
        """
        if len(args) == 0:
            return super(newstr, cls).__new__(cls)
        # Special case: If someone requests str(str(u'abc')), return the same
        # object (same id) for consistency with Py3.3. This is not true for
        # other objects like list or dict.
        elif type(args[0]) == newstr and cls == newstr:
            return args[0]
        elif isinstance(args[0], unicode):
            value = args[0]
        elif isinstance(args[0], bytes):   # i.e. Py2 bytes or newbytes
            if 'encoding' in kwargs or len(args) > 1:
                value = args[0].decode(*args[1:], **kwargs)
            else:
                value = args[0].__str__()
        else:
            value = args[0]
        return super(newstr, cls).__new__(cls, value) 
開發者ID:Soft8Soft,項目名稱:verge3d-blender-addon,代碼行數:35,代碼來源:newstr.py

示例5: join

# 需要導入模塊: from future.types import newbytes [as 別名]
# 或者: from future.types.newbytes import newbytes [as 別名]
def join(self, iterable):
        errmsg = 'sequence item {0}: expected unicode string, found bytes'
        for i, item in enumerate(iterable):
            # Here we use type() rather than isinstance() because
            # __instancecheck__ is being overridden. E.g.
            # isinstance(b'abc', newbytes) is True on Py2.
            if isnewbytes(item):
                raise TypeError(errmsg.format(i))
        # Support use as a staticmethod: str.join('-', ['a', 'b'])
        if type(self) == newstr:
            return newstr(super(newstr, self).join(iterable))
        else:
            return newstr(super(newstr, newstr(self)).join(iterable)) 
開發者ID:Soft8Soft,項目名稱:verge3d-blender-addon,代碼行數:15,代碼來源:newstr.py

示例6: from_bytes

# 需要導入模塊: from future.types import newbytes [as 別名]
# 或者: from future.types.newbytes import newbytes [as 別名]
def from_bytes(cls, mybytes, byteorder='big', signed=False):
        """
        Return the integer represented by the given array of bytes.

        The mybytes argument must either support the buffer protocol or be an
        iterable object producing bytes.  Bytes and bytearray are examples of
        built-in objects that support the buffer protocol.

        The byteorder argument determines the byte order used to represent the
        integer.  If byteorder is 'big', the most significant byte is at the
        beginning of the byte array.  If byteorder is 'little', the most
        significant byte is at the end of the byte array.  To request the native
        byte order of the host system, use `sys.byteorder' as the byte order value.

        The signed keyword-only argument indicates whether two's complement is
        used to represent the integer.
        """
        if byteorder not in ('little', 'big'):
            raise ValueError("byteorder must be either 'little' or 'big'")
        if isinstance(mybytes, unicode):
            raise TypeError("cannot convert unicode objects to bytes")
        # mybytes can also be passed as a sequence of integers on Py3.
        # Test for this:
        elif isinstance(mybytes, collections.Iterable):
            mybytes = newbytes(mybytes)
        b = mybytes if byteorder == 'big' else mybytes[::-1]
        if len(b) == 0:
            b = b'\x00'
        # The encode() method has been disabled by newbytes, but Py2's
        # str has it:
        num = int(native(b).encode('hex'), 16)
        if signed and (b[0] & 0x80):
            num = num - (2 ** (len(b)*8))
        return cls(num)


# def _twos_comp(val, bits):
#     """compute the 2's compliment of int value val"""
#     if( (val&(1<<(bits-1))) != 0 ):
#         val = val - (1<<bits)
#     return val 
開發者ID:Soft8Soft,項目名稱:verge3d-blender-addon,代碼行數:43,代碼來源:newint.py

示例7: __new__

# 需要導入模塊: from future.types import newbytes [as 別名]
# 或者: from future.types.newbytes import newbytes [as 別名]
def __new__(cls, *args, **kwargs):
        """
        From the Py3 str docstring:

          str(object='') -> str
          str(bytes_or_buffer[, encoding[, errors]]) -> str

          Create a new string object from the given object. If encoding or
          errors is specified, then the object must expose a data buffer
          that will be decoded using the given encoding and error handler.
          Otherwise, returns the result of object.__str__() (if defined)
          or repr(object).
          encoding defaults to sys.getdefaultencoding().
          errors defaults to 'strict'.

        """
        if len(args) == 0:
            return super(newstr, cls).__new__(cls)
        # Special case: If someone requests str(str(u'abc')), return the same
        # object (same id) for consistency with Py3.3. This is not true for
        # other objects like list or dict.
        elif type(args[0]) == newstr and cls == newstr:
            return args[0]
        elif isinstance(args[0], unicode):
            value = args[0]
        elif isinstance(args[0], bytes):   # i.e. Py2 bytes or newbytes
            if 'encoding' in kwargs or len(args) > 1:
                value = args[0].decode(*args[1:], **kwargs)
            else:
                value = args[0].__str__()
        else:
            value = args[0]
        return super(newstr, cls).__new__(cls, value) 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:35,代碼來源:newstr.py

示例8: encode

# 需要導入模塊: from future.types import newbytes [as 別名]
# 或者: from future.types.newbytes import newbytes [as 別名]
def encode(self, encoding='utf-8', errors='strict'):
        """
        Returns bytes

        Encode S using the codec registered for encoding. Default encoding
        is 'utf-8'. errors may be given to set a different error
        handling scheme. Default is 'strict' meaning that encoding errors raise
        a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
        'xmlcharrefreplace' as well as any other name registered with
        codecs.register_error that can handle UnicodeEncodeErrors.
        """
        from future.types.newbytes import newbytes
        # Py2 unicode.encode() takes encoding and errors as optional parameter,
        # not keyword arguments as in Python 3 str.

        # For the surrogateescape error handling mechanism, the
        # codecs.register_error() function seems to be inadequate for an
        # implementation of it when encoding. (Decoding seems fine, however.)
        # For example, in the case of
        #     u'\udcc3'.encode('ascii', 'surrogateescape_handler')
        # after registering the ``surrogateescape_handler`` function in
        # future.utils.surrogateescape, both Python 2.x and 3.x raise an
        # exception anyway after the function is called because the unicode
        # string it has to return isn't encodable strictly as ASCII.

        if errors == 'surrogateescape':
            if encoding == 'utf-16':
                # Known to fail here. See test_encoding_works_normally()
                raise NotImplementedError('FIXME: surrogateescape handling is '
                                          'not yet implemented properly')
            # Encode char by char, building up list of byte-strings
            mybytes = []
            for c in self:
                code = ord(c)
                if 0xD800 <= code <= 0xDCFF:
                    mybytes.append(newbytes([code - 0xDC00]))
                else:
                    mybytes.append(c.encode(encoding=encoding))
            return newbytes(b'').join(mybytes)
        return newbytes(super(newstr, self).encode(encoding, errors)) 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:42,代碼來源:newstr.py

示例9: ensure_new_type

# 需要導入模塊: from future.types import newbytes [as 別名]
# 或者: from future.types.newbytes import newbytes [as 別名]
def ensure_new_type(obj):
        from future.types.newbytes import newbytes
        from future.types.newstr import newstr
        from future.types.newint import newint
        from future.types.newdict import newdict

        native_type = type(native(obj))

        # Upcast only if the type is already a native (non-future) type
        if issubclass(native_type, type(obj)):
            # Upcast
            if native_type == str:  # i.e. Py2 8-bit str
                return newbytes(obj)
            elif native_type == unicode:
                return newstr(obj)
            elif native_type == int:
                return newint(obj)
            elif native_type == long:
                return newint(obj)
            elif native_type == dict:
                return newdict(obj)
            else:
                return NotImplementedError('type %s not supported' % type(obj))
        else:
            # Already a new type
            assert type(obj) in [newbytes, newstr]
            return obj 
開發者ID:hughperkins,項目名稱:kgsgo-dataset-preprocessor,代碼行數:29,代碼來源:__init__.py


注:本文中的future.types.newbytes.newbytes方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。