Ignore:
Timestamp:
Aug 11, 2017, 3:18:29 PM (7 years ago)
Author:
zarch
Message:

script.utils: Convert to string/bytes if needed, add doctests and unittests

File:
1 edited

Legend:

Unmodified
Added
Removed
  • grass/trunk/lib/python/script/utils.py

    r70335 r71394  
     1# -*- coding: utf-8 -*-
    12"""
    23Useful functions to be used in Python scripts.
     
    2425import shlex
    2526import re
     27
     28
     29try:
     30    from builtins import unicode
     31except ImportError:
     32    # python3
     33    unicode = str
     34
    2635
    2736def float_or_dms(s):
     
    164173
    165174    :param bytes bytes_: the bytes to decode
    166     """
     175
     176    Example
     177    -------
     178
     179    >>> decode(b'S\xc3\xbcdtirol')
     180    u'Südtirol'
     181    >>> decode(u'Südtirol')
     182    u'Südtirol'
     183    >>> decode(1234)
     184    u'1234'
     185    """
     186    if isinstance(bytes_, unicode):
     187        return bytes_
    167188    if isinstance(bytes_, bytes):
    168189        enc = _get_encoding()
    169190        return bytes_.decode(enc)
    170     return bytes_
     191    return unicode(bytes_)
    171192
    172193
     
    178199
    179200    :param str string: the string to encode
     201
     202    Example
     203    -------
     204
     205    >>> encode(b'S\xc3\xbcdtirol')
     206    b'S\xc3\xbcdtirol'
     207    >>> decode(u'Südtirol')
     208    b'S\xc3\xbcdtirol'
     209    >>> decode(1234)
     210    b'1234'
    180211    """
    181212    if isinstance(string, bytes):
    182213        return string
    183     enc = _get_encoding()
    184     return string.encode(enc)
     214    if isinstance(string, unicode):
     215        enc = _get_encoding()
     216        return string.encode(enc)
     217    return bytes(string)
    185218
    186219
Note: See TracChangeset for help on using the changeset viewer.