Esempio n. 1
0
def error2str(error):
    '''Convert an error to string.'''
    from xoutil.eight import string_types
    from xoutil.types import type_coerce
    if isinstance(error, string_types):
        return safe_str(error)
    elif isinstance(error, BaseException):
        tname = type(error).__name__
        res = safe_str(error)
        if tname in res:
            return res
        else:
            return str(': ').join(tname, res) if res else tname
    elif issubclass(error, BaseException):
        return type(error).__name__
    else:
        prefix = str('unknown error: ')
        cls = type_coerce(error)
        tname = cls.__name__
        if cls is error:
            res = tname
        else:
            res = safe_str(error)
            if tname not in res:
                res = str('{}({})').format(tname, res) if res else tname
        return prefix + res
Esempio n. 2
0
def make_a10z(string):
    '''Utility to find out that "internationalization" is "i18n".

    Examples::

       >>> print(make_a10z('parametrization'))
       p13n
    '''
    return string[0] + str(len(string[1:-1])) + string[-1]
Esempio n. 3
0
def normalize_unicode(value):
    # FIXME: i18n
    if (value is None) or (value is str('')):
        return ''
    elif value is True:
        return safe_decode('Sí')
    elif value is False:
        return safe_decode('No')
    else:
        return safe_decode(value)
Esempio n. 4
0
def safe_str(obj=str()):
    '''Convert to normal string type in a safe way.

    Most of our Python 2.x code uses unicode as normal string, also in
    Python 3 converting bytes or byte-arrays to strings includes the "b"
    prefix in the resulting value.

    This function is useful in some scenarios that require `str` type (for
    example attribute ``__name__`` in functions and types).

    As ``str is bytes`` in Python2, using str(value) assures correct these
    scenarios in most cases, but in other is not enough, for example::

      >>> from xoutil.string import safe_str as sstr
      >>> def inverted_partial(func, *args, **keywords):
      ...     def inner(*a, **kw):
      ...         a += args
      ...         kw.update(keywords)
      ...         return func(*a, **kw)
      ...     inner.__name__ = sstr(func.__name__.replace('lambda', u'λ'))
      ...     return inner

    .. versionadded:: 1.7.0

    '''
    if _py3:
        if isinstance(obj, (bytes, bytearray)):
            return safe_decode(obj)
        else:
            return str(obj)
    else:
        try:
            return str(obj)
        except UnicodeEncodeError:
            # assert isinstance(value, unicode)
            return safe_encode(obj)