|
| 1 | +"""five: six, redux""" |
| 2 | +# pylint:disable=invalid-name |
| 3 | +PY2 = (str is bytes) |
| 4 | +PY3 = (str is not bytes) |
| 5 | + |
| 6 | +# provide a symettrical `text` type to `bytes` |
| 7 | +if PY2: |
| 8 | + text = unicode # flake8: noqa |
| 9 | +else: |
| 10 | + text = str |
| 11 | + |
| 12 | + |
| 13 | +def n(obj): |
| 14 | + """Produce a native string. |
| 15 | +
|
| 16 | + Similar in behavior to str(), but uses US-ASCII encoding when necessary. |
| 17 | + """ |
| 18 | + if isinstance(obj, str): |
| 19 | + return obj |
| 20 | + elif PY2 and isinstance(obj, text): |
| 21 | + return obj.encode('US-ASCII') |
| 22 | + elif PY3 and isinstance(obj, bytes): |
| 23 | + return obj.decode('US-ASCII') |
| 24 | + else: |
| 25 | + return str(obj) |
| 26 | + |
| 27 | + |
| 28 | +def u(obj): |
| 29 | + """Produces text. |
| 30 | +
|
| 31 | + Similar in behavior to str() in python3 or unicode() in python2, |
| 32 | + but uses US-ASCII encoding when necessary. |
| 33 | + """ |
| 34 | + if isinstance(obj, text): |
| 35 | + return obj |
| 36 | + elif isinstance(obj, bytes): |
| 37 | + return obj.decode('US-ASCII') |
| 38 | + else: |
| 39 | + return text(obj) |
| 40 | + |
| 41 | + |
| 42 | +def b(obj): |
| 43 | + """Produces bytes. |
| 44 | +
|
| 45 | + Similar in behavior to bytes(), but uses US-ASCII encoding when necessary. |
| 46 | + """ |
| 47 | + if isinstance(obj, bytes): |
| 48 | + return obj |
| 49 | + elif isinstance(obj, text): |
| 50 | + return obj.encode('US-ASCII') |
| 51 | + else: |
| 52 | + return bytes(obj) |
| 53 | + |
| 54 | + |
| 55 | +def udict(*args, **kwargs): |
| 56 | + """Similar to dict(), but keyword-keys are text.""" |
| 57 | + kwargs = dict([ |
| 58 | + (u(key), val) |
| 59 | + for key, val in kwargs.items() |
| 60 | + ]) |
| 61 | + |
| 62 | + return dict(*args, **kwargs) |
| 63 | + |
| 64 | +def ndict(*args, **kwargs): |
| 65 | + """Similar to dict(), but keyword-keys are forced to native strings.""" |
| 66 | + # I hate this :( |
| 67 | + kwargs = dict([ |
| 68 | + (n(key), val) |
| 69 | + for key, val in kwargs.items() |
| 70 | + ]) |
| 71 | + |
| 72 | + return dict(*args, **kwargs) |
| 73 | + |
| 74 | +def open(*args, **kwargs): |
| 75 | + """Override the builtin open() to return text and use utf8 by default.""" |
| 76 | + from io import open |
| 77 | + kwargs.setdefault('encoding', 'UTF-8') |
| 78 | + return open(*args, **kwargs) |
0 commit comments