gpsd-dev
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[gpsd-dev] [PATCH 07/12] Changes type checks in misc.py:isotime to use i


From: Fred Wright
Subject: [gpsd-dev] [PATCH 07/12] Changes type checks in misc.py:isotime to use isinstance().
Date: Fri, 8 Apr 2016 10:07:48 -0700

Using isinstance() rather than type() == is preferable for a few
reasons:

1) It's generally considered more pythonic.

2) Referring to types by name is a bit more readable than applying
type() to sample values.

3) Both 'str' and the Python 2 'unicode' type can be checked in a
single call.

4) Since the 'str' type check was the only use of a Unicode literal in
the common code, changing this eliminates Python 3.2 incompatibility.

In Python 2, both 'str' and 'unicode' are derived from the abstract
'basestring' class.  In Python 3, 'unicode' has been folded into
'str', and the latter is itself the base class.  Thus, an import-time
conditional is used to set up the proper STR_CLASS for comparison.

TESTED:
Ran "scons build-all check" (with Python 2.7).  Also verified that the
regression tests and test_maidenhead.py run with Python 2.6, and that
gpsfake -T and test_maidenhead.py run with Python 3.2-3.5 when the
extensions are built for Python 3 (not yet a build option).  Also
verified that xgps and xgpsspeed work with 2.7 and 3.2-3.5 (with
a pending fix to xgps for 3.2).
---
 gps/misc.py | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)

diff --git a/gps/misc.py b/gps/misc.py
index eb9fe9d..e1c01fe 100644
--- a/gps/misc.py
+++ b/gps/misc.py
@@ -9,6 +9,12 @@ from __future__ import absolute_import, print_function, 
division
 
 import time, calendar, math
 
+# Determine a single class for testing "stringness"
+try:
+    STR_CLASS = basestring  # Base class for 'str' and 'unicode' in Python 2
+except NameError:
+    STR_CLASS = str         # In Python 3, 'str' is the base class
+
 # some multipliers for interpreting GPS output
 METERS_TO_FEET = 3.2808399     # Meters to U.S./British feet
 METERS_TO_MILES        = 0.00062137119 # Meters to miles
@@ -96,14 +102,14 @@ def MeterOffset(c1, c2):
 
 def isotime(s):
     "Convert timestamps in ISO8661 format to and from Unix time."
-    if type(s) == type(1):
+    if isinstance(s, int):
         return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(s))
-    elif type(s) == type(1.0):
+    elif isinstance(s, float):
         date = int(s)
         msec = s - date
         date = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(s))
         return date + "." + repr(msec)[3:]
-    elif type(s) == type("") or type(s) == type(u""):
+    elif isinstance(s, STR_CLASS):
         if s[-1] == "Z":
             s = s[:-1]
         if "." in s:
-- 
2.8.0




reply via email to

[Prev in Thread] Current Thread [Next in Thread]