OLD | NEW |
(Empty) | |
| 1 # coding: utf-8 |
| 2 |
| 3 """ |
| 4 Exposes functionality needed throughout the project. |
| 5 |
| 6 """ |
| 7 |
| 8 from sys import version_info |
| 9 |
| 10 def _get_string_types(): |
| 11 # TODO: come up with a better solution for this. One of the issues here |
| 12 # is that in Python 3 there is no common base class for unicode strings |
| 13 # and byte strings, and 2to3 seems to convert all of "str", "unicode", |
| 14 # and "basestring" to Python 3's "str". |
| 15 if version_info < (3, ): |
| 16 return basestring |
| 17 # The latter evaluates to "bytes" in Python 3 -- even after conversion by 2t
o3. |
| 18 return (unicode, type(u"a".encode('utf-8'))) |
| 19 |
| 20 |
| 21 _STRING_TYPES = _get_string_types() |
| 22 |
| 23 |
| 24 def is_string(obj): |
| 25 """ |
| 26 Return whether the given object is a byte string or unicode string. |
| 27 |
| 28 This function is provided for compatibility with both Python 2 and 3 |
| 29 when using 2to3. |
| 30 |
| 31 """ |
| 32 return isinstance(obj, _STRING_TYPES) |
| 33 |
| 34 |
| 35 # This function was designed to be portable across Python versions -- both |
| 36 # with older versions and with Python 3 after applying 2to3. |
| 37 def read(path): |
| 38 """ |
| 39 Return the contents of a text file as a byte string. |
| 40 |
| 41 """ |
| 42 # Opening in binary mode is necessary for compatibility across Python |
| 43 # 2 and 3. In both Python 2 and 3, open() defaults to opening files in |
| 44 # text mode. However, in Python 2, open() returns file objects whose |
| 45 # read() method returns byte strings (strings of type `str` in Python 2), |
| 46 # whereas in Python 3, the file object returns unicode strings (strings |
| 47 # of type `str` in Python 3). |
| 48 f = open(path, 'rb') |
| 49 # We avoid use of the with keyword for Python 2.4 support. |
| 50 try: |
| 51 return f.read() |
| 52 finally: |
| 53 f.close() |
| 54 |
| 55 |
| 56 class MissingTags(object): |
| 57 |
| 58 """Contains the valid values for Renderer.missing_tags.""" |
| 59 |
| 60 ignore = 'ignore' |
| 61 strict = 'strict' |
| 62 |
| 63 |
| 64 class PystacheError(Exception): |
| 65 """Base class for Pystache exceptions.""" |
| 66 pass |
| 67 |
| 68 |
| 69 class TemplateNotFoundError(PystacheError): |
| 70 """An exception raised when a template is not found.""" |
| 71 pass |
OLD | NEW |