|
10 | 10 |
|
11 | 11 | import sys |
12 | 12 |
|
13 | | -__all__ = ('STRING_TYPES', 'RAW_STRING_TYPE', 'ALL_STRING_TYPES') |
| 13 | +__all__ = ('STRING_TYPES', 'RAW_STRING_TYPE', 'ALL_STRING_TYPES', 'ensureStringEncoded') |
14 | 14 |
|
15 | 15 | if sys.version_info.major < 3: |
16 | | - |
| 16 | + |
17 | 17 | # STRING_TYPES - Types that represent strings ("printable") |
18 | 18 | STRING_TYPES = (str, unicode) |
19 | 19 |
|
|
23 | 23 | # ALL_STRING_TYPES - All string-like types, encoded or otherwise |
24 | 24 | ALL_STRING_TYPES = (str, unicode) |
25 | 25 |
|
| 26 | + # DECODED_STR_TYPE - String type that has been decoded |
| 27 | + DECODED_STR_TYPE = unicode |
| 28 | + |
26 | 29 | else: |
27 | | - |
| 30 | + |
28 | 31 | # STRING_TYPES - Types that represent strings ("printable") |
29 | 32 | STRING_TYPES = (str, ) |
30 | 33 |
|
|
34 | 37 | # ALL_STRING_TYPES - All string-like types, encoded or otherwise |
35 | 38 | ALL_STRING_TYPES = (str, bytes) |
36 | 39 |
|
| 40 | + # DECODED_STR_TYPE - String type that has been decoded |
| 41 | + DECODED_STR_TYPE = str |
| 42 | + |
| 43 | + |
| 44 | +def ensureStringEncoded(theString, encoding='utf-8'): |
| 45 | + ''' |
| 46 | + ensureStringEncoded - Ensure we have the encoded type for a given string |
| 47 | +
|
| 48 | +
|
| 49 | + @param theString <str/unicode/bytes> - A string-like object |
| 50 | +
|
| 51 | + @param encoding <str> Default 'utf-8' - The encoding to use |
| 52 | +
|
| 53 | + NOTE: If this string is already encoded, we do NOT ensure it is encoded in this type, |
| 54 | + this type is only used when we have a decoded string, in order to encode it. |
| 55 | +
|
| 56 | +
|
| 57 | + @return (python3)<bytes> / (python2)<str> - A string encoded in utf-8 |
| 58 | + ''' |
| 59 | + |
| 60 | + if issubclass( theString.__class__, DECODED_STR_TYPE ): |
| 61 | + return theString.encode('utf-8') |
| 62 | + |
| 63 | + return theString |
| 64 | + |
37 | 65 | # vim: set ts=4 sw=4 st=4 expandtab : |
0 commit comments