summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorChris Jerdonek <chris.jerdonek@gmail.com>2012-04-07 14:37:56 -0700
committerChris Jerdonek <chris.jerdonek@gmail.com>2012-04-08 14:20:59 -0700
commitba04172d95eb7bef2e4935a2057622edba8e9509 (patch)
treef08ce1fc56b0e2cb1486182dd9485b2e27f5fdcd
parent75030e7d6cd03507a6941fe8badedd5997a7518b (diff)
downloadpystache-ba04172d95eb7bef2e4935a2057622edba8e9509.tar.gz
Added module pystache.common with a read(path) function.
-rw-r--r--pystache/common.py26
-rw-r--r--pystache/loader.py10
2 files changed, 29 insertions, 7 deletions
diff --git a/pystache/common.py b/pystache/common.py
new file mode 100644
index 0000000..00f8a77
--- /dev/null
+++ b/pystache/common.py
@@ -0,0 +1,26 @@
+# coding: utf-8
+
+"""
+Exposes common functions.
+
+"""
+
+# This function was designed to be portable across Python versions -- both
+# with older versions and with Python 3 after applying 2to3.
+def read(path):
+ """
+ Return the contents of a text file as a byte string.
+
+ """
+ # Opening in binary mode is necessary for compatibility across Python
+ # 2 and 3. In both Python 2 and 3, open() defaults to opening files in
+ # text mode. However, in Python 2, open() returns file objects whose
+ # read() method returns byte strings (strings of type `str` in Python 2),
+ # whereas in Python 3, the file object returns unicode strings (strings
+ # of type `str` in Python 3).
+ f = open(path, 'rb')
+ # We avoid use of the with keyword for Python 2.4 support.
+ try:
+ return f.read()
+ finally:
+ f.close()
diff --git a/pystache/loader.py b/pystache/loader.py
index 3506acf..3a7d02c 100644
--- a/pystache/loader.py
+++ b/pystache/loader.py
@@ -8,6 +8,7 @@ This module provides a Loader class for locating and reading templates.
import os
import sys
+from pystache import common
from pystache import defaults
from pystache.locator import Locator
@@ -106,17 +107,12 @@ class Loader(object):
Read the template at the given path, and return it as a unicode string.
"""
- # We avoid use of the with keyword for Python 2.4 support.
- f = open(path, 'r')
- try:
- text = f.read()
- finally:
- f.close()
+ b = common.read(path)
if encoding is None:
encoding = self.file_encoding
- return self.unicode(text, encoding)
+ return self.unicode(b, encoding)
# TODO: unit-test this method.
def load_name(self, name):