Python __builtin__ 模块,unicode() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用__builtin__.unicode()

项目:radar    作者:amoose136    | 项目源码 | 文件源码
def __init__(self, delimiter=None, comments=asbytes('#'), autostrip=True):
        self.comments = comments
        # Delimiter is a character
        if isinstance(delimiter, unicode):
            delimiter = delimiter.encode('ascii')
        if (delimiter is None) or _is_bytes_like(delimiter):
            delimiter = delimiter or None
            _handyman = self._delimited_splitter
        # Delimiter is a list of field widths
        elif hasattr(delimiter, '__iter__'):
            _handyman = self._variablewidth_splitter
            idx = np.cumsum([0] + list(delimiter))
            delimiter = [slice(i, j) for (i, j) in zip(idx[:-1], idx[1:])]
        # Delimiter is a single integer
        elif int(delimiter):
            (_handyman, delimiter) = (
                    self._fixedwidth_splitter, int(delimiter))
        else:
            (_handyman, delimiter) = (self._delimited_splitter, None)
        self.delimiter = delimiter
        if autostrip:
            self._handyman = self.autostrip(_handyman)
        else:
            self._handyman = _handyman
    #
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
def __init__(self, delimiter=None, comments=asbytes('#'), autostrip=True):
        self.comments = comments
        # Delimiter is a character
        if isinstance(delimiter, unicode):
            delimiter = delimiter.encode('ascii')
        if (delimiter is None) or _is_bytes_like(delimiter):
            delimiter = delimiter or None
            _handyman = self._delimited_splitter
        # Delimiter is a list of field widths
        elif hasattr(delimiter, '__iter__'):
            _handyman = self._variablewidth_splitter
            idx = np.cumsum([0] + list(delimiter))
            delimiter = [slice(i, j) for (i, j) in zip(idx[:-1], idx[1:])]
        # Delimiter is a single integer
        elif int(delimiter):
            (_handyman, delimiter) = (
                    self._fixedwidth_splitter, int(delimiter))
        else:
            (_handyman, delimiter) = (self._delimited_splitter, None)
        self.delimiter = delimiter
        if autostrip:
            self._handyman = self.autostrip(_handyman)
        else:
            self._handyman = _handyman
    #
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
def __init__(self, delimiter=None, comments=asbytes('#'), autostrip=True):
        self.comments = comments
        # Delimiter is a character
        if isinstance(delimiter, unicode):
            delimiter = delimiter.encode('ascii')
        if (delimiter is None) or _is_bytes_like(delimiter):
            delimiter = delimiter or None
            _handyman = self._delimited_splitter
        # Delimiter is a list of field widths
        elif hasattr(delimiter, '__iter__'):
            _handyman = self._variablewidth_splitter
            idx = np.cumsum([0] + list(delimiter))
            delimiter = [slice(i, j) for (i, j) in zip(idx[:-1], idx[1:])]
        # Delimiter is a single integer
        elif int(delimiter):
            (_handyman, delimiter) = (
                    self._fixedwidth_splitter, int(delimiter))
        else:
            (_handyman, delimiter) = (self._delimited_splitter, None)
        self.delimiter = delimiter
        if autostrip:
            self._handyman = self.autostrip(_handyman)
        else:
            self._handyman = _handyman
    #
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
def __init__(self, delimiter=None, comments=asbytes('#'), autostrip=True):
        self.comments = comments
        # Delimiter is a character
        if isinstance(delimiter, unicode):
            delimiter = delimiter.encode('ascii')
        if (delimiter is None) or _is_bytes_like(delimiter):
            delimiter = delimiter or None
            _handyman = self._delimited_splitter
        # Delimiter is a list of field widths
        elif hasattr(delimiter, '__iter__'):
            _handyman = self._variablewidth_splitter
            idx = np.cumsum([0] + list(delimiter))
            delimiter = [slice(i, j) for (i, j) in zip(idx[:-1], idx[1:])]
        # Delimiter is a single integer
        elif int(delimiter):
            (_handyman, delimiter) = (
                    self._fixedwidth_splitter, int(delimiter))
        else:
            (_handyman, delimiter) = (self._delimited_splitter, None)
        self.delimiter = delimiter
        if autostrip:
            self._handyman = self.autostrip(_handyman)
        else:
            self._handyman = _handyman
    #
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
def __init__(self, delimiter=None, comments=asbytes('#'), autostrip=True):
        self.comments = comments
        # Delimiter is a character
        if isinstance(delimiter, unicode):
            delimiter = delimiter.encode('ascii')
        if (delimiter is None) or _is_bytes_like(delimiter):
            delimiter = delimiter or None
            _handyman = self._delimited_splitter
        # Delimiter is a list of field widths
        elif hasattr(delimiter, '__iter__'):
            _handyman = self._variablewidth_splitter
            idx = np.cumsum([0] + list(delimiter))
            delimiter = [slice(i, j) for (i, j) in zip(idx[:-1], idx[1:])]
        # Delimiter is a single integer
        elif int(delimiter):
            (_handyman, delimiter) = (
                    self._fixedwidth_splitter, int(delimiter))
        else:
            (_handyman, delimiter) = (self._delimited_splitter, None)
        self.delimiter = delimiter
        if autostrip:
            self._handyman = self.autostrip(_handyman)
        else:
            self._handyman = _handyman
    #
项目:request_validator    作者:amirasaran    | 项目源码 | 文件源码
def check_int(self):
        if isinstance(self.data, int):
            return True
        if type(self.data) is long:
            self.data = int(self.data)
            return True
        if type(self.data) is Decimal:
            self.data = int(self.data)
            return True
        if isinstance(self.data, (str, unicode)):
            import re
            if re.match(r"\d+", self.data):
                self.data = int(self.data)
                return True
        if self.data is None:
            return True
        self.error = self._MESSAGES[self.INT].format(data_type=type(self.data).__name__)
        return False
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
def __init__(self, delimiter=None, comments=asbytes('#'), autostrip=True):
        self.comments = comments
        # Delimiter is a character
        if isinstance(delimiter, unicode):
            delimiter = delimiter.encode('ascii')
        if (delimiter is None) or _is_bytes_like(delimiter):
            delimiter = delimiter or None
            _handyman = self._delimited_splitter
        # Delimiter is a list of field widths
        elif hasattr(delimiter, '__iter__'):
            _handyman = self._variablewidth_splitter
            idx = np.cumsum([0] + list(delimiter))
            delimiter = [slice(i, j) for (i, j) in zip(idx[:-1], idx[1:])]
        # Delimiter is a single integer
        elif int(delimiter):
            (_handyman, delimiter) = (
                    self._fixedwidth_splitter, int(delimiter))
        else:
            (_handyman, delimiter) = (self._delimited_splitter, None)
        self.delimiter = delimiter
        if autostrip:
            self._handyman = self.autostrip(_handyman)
        else:
            self._handyman = _handyman
    #
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s.encode("ascii")
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s.encode("ascii")
项目:centos-base-consul    作者:zeroc0d3lab    | 项目源码 | 文件源码
def u(s):
    '''Return unicode instance assuming UTF-8 encoded string.
    '''
    if type(s) is unicode:
        return s
    else:
        return unicode(s, 'utf-8')
项目:centos-base-consul    作者:zeroc0d3lab    | 项目源码 | 文件源码
def out_u(s):
    '''Return unicode string suitable for displaying

    Unlike other functions assumes get_preferred_output_encoding() first. Unlike 
    u() does not throw exceptions for invalid unicode strings. Unlike 
    safe_unicode() does throw an exception if object is not a string.
    '''
    if isinstance(s, unicode):
        return s
    elif isinstance(s, bytes):
        return unicode(s, get_preferred_output_encoding(), 'powerline_decode_error')
    else:
        raise TypeError('Expected unicode or bytes instance, got {0}'.format(repr(type(s))))
项目:centos-base-consul    作者:zeroc0d3lab    | 项目源码 | 文件源码
def safe_unicode(s):
    '''Return unicode instance without raising an exception.

    Order of assumptions:
    * ASCII string or unicode object
    * UTF-8 string
    * Object with __str__() or __repr__() method that returns UTF-8 string or 
      unicode object (depending on python version)
    * String in powerline.lib.encoding.get_preferred_output_encoding() encoding
    * If everything failed use safe_unicode on last exception with which 
      everything failed
    '''
    try:
        try:
            if type(s) is bytes:
                return unicode(s, 'ascii')
            else:
                return unicode(s)
        except UnicodeDecodeError:
            try:
                return unicode(s, 'utf-8')
            except TypeError:
                return unicode(str(s), 'utf-8')
            except UnicodeDecodeError:
                return unicode(s, get_preferred_output_encoding())
    except Exception as e:
        return safe_unicode(e)
项目:HTTPIDL    作者:cikelengfeng    | 项目源码 | 文件源码
def __str__(self):
        return unicode(self)


# TODO: make all transitions sets? no, should remove set edges
项目:HTTPIDL    作者:cikelengfeng    | 项目源码 | 文件源码
def __unicode__(self):
        return unicode(self.label_)
项目:HTTPIDL    作者:cikelengfeng    | 项目源码 | 文件源码
def __unicode__(self):
        return u"pred_" + unicode(self.ruleIndex) + u":" + unicode(self.predIndex)
项目:HTTPIDL    作者:cikelengfeng    | 项目源码 | 文件源码
def __unicode__(self):
        return u"action_" + unicode(self.ruleIndex) + u":" + unicode(self.actionIndex)

# A transition containing a set of values.
项目:HTTPIDL    作者:cikelengfeng    | 项目源码 | 文件源码
def __unicode__(self):
        return unicode(self.label)
项目:HTTPIDL    作者:cikelengfeng    | 项目源码 | 文件源码
def getTokenErrorDisplay(self, t):
        if t is None:
            return u"<no token>"
        s = t.text
        if s is None:
            if t.type==Token.EOF:
                s = u"<EOF>"
            else:
                s = u"<" + unicode(t.type) + u">"
        s = s.replace(u"\n",u"\\n")
        s = s.replace(u"\r",u"\\r")
        s = s.replace(u"\t",u"\\t")
        return u"'" + s + u"'"
项目:Taigabot    作者:FrozenPigs    | 项目源码 | 文件源码
def _str(s, encoding="UTF-8"):
        s = unicode(s, encoding=encoding)
        return unichr_escape.sub(lambda x:
                                     x.group(0).decode('unicode-escape'),
                                 s)
项目:Callandtext    作者:iaora    | 项目源码 | 文件源码
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s
项目:Callandtext    作者:iaora    | 项目源码 | 文件源码
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s.encode("ascii")
项目:tichu-tournament    作者:aragos    | 项目源码 | 文件源码
def _str(s, encoding="UTF-8"):
        return unicode(s, encoding=encoding)
项目:MacHeap    作者:blankwall    | 项目源码 | 文件源码
def __init__(self, **attrs):
        super(_char_t,self).__init__(**attrs)

        # calculate the size of .length based on .encoding
        res = __builtin__.unicode('\x00', 'ascii').encode(self.encoding.name)
        self.length = len(res)
项目:MacHeap    作者:blankwall    | 项目源码 | 文件源码
def __setvalue__(self, value):
        '''Set the _char_t to the str ``value``.'''
        if isinstance(value, __builtin__.str):
            try: value = __builtin__.unicode(value, 'ascii')
            except UnicodeDecodeError: return super(pint.integer_t,self).__setvalue__(str(value))
        elif isinstance(value, __builtin__.unicode):
            value = value
        else:
            raise ValueError(self, '_char_t.set', 'User tried to set a value of an incorrect type : {:s}'.format(value.__class__))
        res = value.encode(self.encoding.name)
        return super(pint.integer_t,self).__setvalue__(res)
项目:MacHeap    作者:blankwall    | 项目源码 | 文件源码
def __init__(self, **attrs):
        res = super(string,self).__init__(**attrs)

        # ensure that self._object_ is using a fixed-width encoding
        _object_ = self._object_

        # encode 3 types of strings and ensure that their lengths scale up with their string sizes
        res,single,double = ( __builtin__.unicode(n, 'ascii').encode(_object_.encoding.name) for n in ('\x00', 'A', 'AA') )
        if len(res) * 2 == len(single) * 2 == len(double):
            return
        raise ValueError(self.classname(), 'string.__init__', 'User tried to specify a variable-width character encoding : {:s}'.format(_object_.encoding.name))
项目:MacHeap    作者:blankwall    | 项目源码 | 文件源码
def summary(self, **options):
        try:
            result = repr(self.str())
        except UnicodeDecodeError:
            Log.debug('{:s}.summary : {:s} : Unable to decode unicode string. Rendering as hexdump instead.'.format(self.classname(),self.instance()))
            return super(string,self).summary(**options)
        return result
项目:MacHeap    作者:blankwall    | 项目源码 | 文件源码
def test_str_wstring():
        x = pstr.wstring()
        oldstring = "ok, this is unicode"
        string = oldstring
        x.length = len(string)/2
        string = ''.join([c+'\x00' for c in string])
        x.source = provider.string(string)
        x.load()
        if x.str() == oldstring[:len(oldstring)/2]:
            raise Success
项目:Sudoku-Solver    作者:ayush1997    | 项目源码 | 文件源码
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s
项目:Sudoku-Solver    作者:ayush1997    | 项目源码 | 文件源码
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s.encode("ascii")
项目:GAMADV-X    作者:taers232c    | 项目源码 | 文件源码
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s
项目:GAMADV-X    作者:taers232c    | 项目源码 | 文件源码
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s.encode("ascii")
项目:GAMADV-X    作者:taers232c    | 项目源码 | 文件源码
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s
项目:GAMADV-X    作者:taers232c    | 项目源码 | 文件源码
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s.encode("ascii")
项目:enkiWS    作者:juliettef    | 项目源码 | 文件源码
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s
项目:enkiWS    作者:juliettef    | 项目源码 | 文件源码
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s.encode("ascii")
项目:dotfiles    作者:gbraad    | 项目源码 | 文件源码
def u(s):
    '''Return unicode instance assuming UTF-8 encoded string.
    '''
    if type(s) is unicode:
        return s
    else:
        return unicode(s, 'utf-8')
项目:dotfiles    作者:gbraad    | 项目源码 | 文件源码
def out_u(s):
    '''Return unicode string suitable for displaying

    Unlike other functions assumes get_preferred_output_encoding() first. Unlike 
    u() does not throw exceptions for invalid unicode strings. Unlike 
    safe_unicode() does throw an exception if object is not a string.
    '''
    if isinstance(s, unicode):
        return s
    elif isinstance(s, bytes):
        return unicode(s, get_preferred_output_encoding(), 'powerline_decode_error')
    else:
        raise TypeError('Expected unicode or bytes instance, got {0}'.format(repr(type(s))))
项目:dotfiles    作者:gbraad    | 项目源码 | 文件源码
def safe_unicode(s):
    '''Return unicode instance without raising an exception.

    Order of assumptions:
    * ASCII string or unicode object
    * UTF-8 string
    * Object with __str__() or __repr__() method that returns UTF-8 string or 
      unicode object (depending on python version)
    * String in powerline.lib.encoding.get_preferred_output_encoding() encoding
    * If everything failed use safe_unicode on last exception with which 
      everything failed
    '''
    try:
        try:
            if type(s) is bytes:
                return unicode(s, 'ascii')
            else:
                return unicode(s)
        except UnicodeDecodeError:
            try:
                return unicode(s, 'utf-8')
            except TypeError:
                return unicode(str(s), 'utf-8')
            except UnicodeDecodeError:
                return unicode(s, get_preferred_output_encoding())
    except Exception as e:
        return safe_unicode(e)
项目:request_validator    作者:amirasaran    | 项目源码 | 文件源码
def check_string(self):
        if isinstance(self.data, (str, unicode)):
            return True
        if self.data is None:
            return True

        self.error = self._MESSAGES[self.STRING].format(data_type=type(self.data).__name__)
        return False
项目:request_validator    作者:amirasaran    | 项目源码 | 文件源码
def check_date(self):
        if isinstance(self.data, (str, unicode)):
            self.data = self.data.strip()
        import datetime
        if self._value['convert_to_date']:
            if isinstance(self.data, datetime.datetime):
                self.data = self.data.date()
                return True
            elif isinstance(self.data, datetime.date):
                return True
            elif isinstance(self.data, (str, unicode)):
                try:
                    self.data = datetime.datetime.strptime(self.data, self._value['format']).date()
                    return True
                except Exception as e:
                    self.error = self._MESSAGES[self.DATE].format(date_format=self._value['format'],
                                                                  data=self.data)
                    return False
        else:
            if isinstance(self.data, datetime.datetime):
                self.data = self.data.date().strftime(self._value['format'])
                return True
            elif isinstance(self.data, datetime.date):
                self.data = self.data.strftime(self._value['format'])
                return True
            elif isinstance(self.data, (str, unicode)):
                try:
                    self.data = datetime.datetime.strptime(
                        self.data,
                        self._value['format']
                    ).date().strftime(self._value['format'])
                    return True
                except Exception as e:
                    self.error = self._MESSAGES[self.DATE].format(date_format=self._value['format'],
                                                                  data=self.data)
                    return False
        self.error = self._MESSAGES[self.DATE].format(date_format=self._value['format'], data=self.data)
        return False
项目:python-flask-security    作者:weinbergdavid    | 项目源码 | 文件源码
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s
项目:python-flask-security    作者:weinbergdavid    | 项目源码 | 文件源码
def uascii_to_str(s):
        assert isinstance(s, unicode)
        return s.encode("ascii")
项目:fortress    作者:rscircus    | 项目源码 | 文件源码
def unicode(s):
  """Force conversion of s to unicode."""
  if PY3:
    return s
  else:
    return __builtin__.unicode(s, 'utf-8')


# In Python 3.2+, readfp is deprecated in favor of read_file, which doesn't
# exist in Python 2 yet. To avoid deprecation warnings, subclass ConfigParser to
# fix this - now read_file works across all Python versions we care about.
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def print_(*args, **kwds):
        """The new-style print function."""
        # extract kwd args
        fp = kwds.pop("file", sys.stdout)
        sep = kwds.pop("sep", None)
        end = kwds.pop("end", None)
        if kwds:
            raise TypeError("invalid keyword arguments")

        # short-circuit if no target
        if fp is None:
            return

        # use unicode or bytes ?
        want_unicode = isinstance(sep, unicode) or isinstance(end, unicode) or \
                       any(isinstance(arg, unicode) for arg in args)

        # pick default end sequence
        if end is None:
            end = u("\n") if want_unicode else "\n"
        elif not isinstance(end, base_string_types):
            raise TypeError("end must be None or a string")

        # pick default separator
        if sep is None:
            sep = u(" ") if want_unicode else " "
        elif not isinstance(sep, base_string_types):
            raise TypeError("sep must be None or a string")

        # write to buffer
        first = True
        write = fp.write
        for arg in args:
            if first:
                first = False
            else:
                write(sep)
            if not isinstance(arg, basestring):
                arg = str(arg)
            write(arg)
        write(end)

#=============================================================================
# lazy overlay module
#=============================================================================
项目:radar    作者:amoose136    | 项目源码 | 文件源码
def bitname(obj):
    """Return a bit-width name for a given type object"""
    name = obj.__name__
    base = ''
    char = ''
    try:
        if name[-1] == '_':
            newname = name[:-1]
        else:
            newname = name
        info = typeinfo[english_upper(newname)]
        assert(info[-1] == obj)  # sanity check
        bits = info[2]

    except KeyError:     # bit-width name
        base, bits = _evalname(name)
        char = base[0]

    if name == 'bool_':
        char = 'b'
        base = 'bool'
    elif name == 'void':
        char = 'V'
        base = 'void'
    elif name == 'object_':
        char = 'O'
        base = 'object'
        bits = 0
    elif name == 'datetime64':
        char = 'M'
    elif name == 'timedelta64':
        char = 'm'

    if sys.version_info[0] >= 3:
        if name == 'bytes_':
            char = 'S'
            base = 'bytes'
        elif name == 'str_':
            char = 'U'
            base = 'str'
    else:
        if name == 'string_':
            char = 'S'
            base = 'string'
        elif name == 'unicode_':
            char = 'U'
            base = 'unicode'

    bytes = bits // 8

    if char != '' and bytes != 0:
        char = "%s%d" % (char, bytes)

    return base, bits, char
项目:radar    作者:amoose136    | 项目源码 | 文件源码
def _set_up_aliases():
    type_pairs = [('complex_', 'cdouble'),
                  ('int0', 'intp'),
                  ('uint0', 'uintp'),
                  ('single', 'float'),
                  ('csingle', 'cfloat'),
                  ('singlecomplex', 'cfloat'),
                  ('float_', 'double'),
                  ('intc', 'int'),
                  ('uintc', 'uint'),
                  ('int_', 'long'),
                  ('uint', 'ulong'),
                  ('cfloat', 'cdouble'),
                  ('longfloat', 'longdouble'),
                  ('clongfloat', 'clongdouble'),
                  ('longcomplex', 'clongdouble'),
                  ('bool_', 'bool'),
                  ('unicode_', 'unicode'),
                  ('object_', 'object')]
    if sys.version_info[0] >= 3:
        type_pairs.extend([('bytes_', 'string'),
                           ('str_', 'unicode'),
                           ('string_', 'string')])
    else:
        type_pairs.extend([('str_', 'string'),
                           ('string_', 'string'),
                           ('bytes_', 'string')])
    for alias, t in type_pairs:
        allTypes[alias] = allTypes[t]
        sctypeDict[alias] = sctypeDict[t]
    # Remove aliases overriding python types and modules
    to_remove = ['ulong', 'object', 'unicode', 'int', 'long', 'float',
                 'complex', 'bool', 'string', 'datetime', 'timedelta']
    if sys.version_info[0] >= 3:
        # Py3K
        to_remove.append('bytes')
        to_remove.append('str')
        to_remove.remove('unicode')
        to_remove.remove('long')
    for t in to_remove:
        try:
            del allTypes[t]
            del sctypeDict[t]
        except KeyError:
            pass
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
def bitname(obj):
    """Return a bit-width name for a given type object"""
    name = obj.__name__
    base = ''
    char = ''
    try:
        if name[-1] == '_':
            newname = name[:-1]
        else:
            newname = name
        info = typeinfo[english_upper(newname)]
        assert(info[-1] == obj)  # sanity check
        bits = info[2]

    except KeyError:     # bit-width name
        base, bits = _evalname(name)
        char = base[0]

    if name == 'bool_':
        char = 'b'
        base = 'bool'
    elif name == 'void':
        char = 'V'
        base = 'void'
    elif name == 'object_':
        char = 'O'
        base = 'object'
        bits = 0
    elif name == 'datetime64':
        char = 'M'
    elif name == 'timedelta64':
        char = 'm'

    if sys.version_info[0] >= 3:
        if name == 'bytes_':
            char = 'S'
            base = 'bytes'
        elif name == 'str_':
            char = 'U'
            base = 'str'
    else:
        if name == 'string_':
            char = 'S'
            base = 'string'
        elif name == 'unicode_':
            char = 'U'
            base = 'unicode'

    bytes = bits // 8

    if char != '' and bytes != 0:
        char = "%s%d" % (char, bytes)

    return base, bits, char
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
def _set_up_aliases():
    type_pairs = [('complex_', 'cdouble'),
                  ('int0', 'intp'),
                  ('uint0', 'uintp'),
                  ('single', 'float'),
                  ('csingle', 'cfloat'),
                  ('singlecomplex', 'cfloat'),
                  ('float_', 'double'),
                  ('intc', 'int'),
                  ('uintc', 'uint'),
                  ('int_', 'long'),
                  ('uint', 'ulong'),
                  ('cfloat', 'cdouble'),
                  ('longfloat', 'longdouble'),
                  ('clongfloat', 'clongdouble'),
                  ('longcomplex', 'clongdouble'),
                  ('bool_', 'bool'),
                  ('unicode_', 'unicode'),
                  ('object_', 'object')]
    if sys.version_info[0] >= 3:
        type_pairs.extend([('bytes_', 'string'),
                           ('str_', 'unicode'),
                           ('string_', 'string')])
    else:
        type_pairs.extend([('str_', 'string'),
                           ('string_', 'string'),
                           ('bytes_', 'string')])
    for alias, t in type_pairs:
        allTypes[alias] = allTypes[t]
        sctypeDict[alias] = sctypeDict[t]
    # Remove aliases overriding python types and modules
    to_remove = ['ulong', 'object', 'unicode', 'int', 'long', 'float',
                 'complex', 'bool', 'string', 'datetime', 'timedelta']
    if sys.version_info[0] >= 3:
        # Py3K
        to_remove.append('bytes')
        to_remove.append('str')
        to_remove.remove('unicode')
        to_remove.remove('long')
    for t in to_remove:
        try:
            del allTypes[t]
            del sctypeDict[t]
        except KeyError:
            pass