strtypes.py revision 781d71db
1"""Declare basic string types unambiguously for various Python versions.
2
3Authors
4-------
5* MinRK
6"""
7
8# Copyright (C) PyZMQ Developers
9# Distributed under the terms of the Modified BSD License.
10
11import sys
12
13if sys.version_info[0] >= 3:
14    bytes = bytes
15    unicode = str
16    basestring = (bytes, unicode)
17else:
18    unicode = unicode
19    bytes = str
20    basestring = basestring
21
22def cast_bytes(s, encoding='utf8', errors='strict'):
23    """cast unicode or bytes to bytes"""
24    if isinstance(s, bytes):
25        return s
26    elif isinstance(s, unicode):
27        return s.encode(encoding, errors)
28    else:
29        raise TypeError("Expected unicode or bytes, got %r" % s)
30
31def cast_unicode(s, encoding='utf8', errors='strict'):
32    """cast bytes or unicode to unicode"""
33    if isinstance(s, bytes):
34        return s.decode(encoding, errors)
35    elif isinstance(s, unicode):
36        return s
37    else:
38        raise TypeError("Expected unicode or bytes, got %r" % s)
39
40# give short 'b' alias for cast_bytes, so that we can use fake b('stuff')
41# to simulate b'stuff'
42b = asbytes = cast_bytes
43u = cast_unicode
44
45__all__ = ['asbytes', 'bytes', 'unicode', 'basestring', 'b', 'u', 'cast_bytes', 'cast_unicode']
46