[PATCH] morph2: Improve compatibility with python < 2.7

Richard Maw richard.maw at codethink.co.uk
Fri Jan 18 17:03:26 GMT 2013


On Fri, Jan 18, 2013 at 11:30:33AM +0000, Javier Jardón wrote:
> ---
>  morphlib/morph2.py | 29 +++++++++--------------------
>  1 file changed, 9 insertions(+), 20 deletions(-)
> 
> diff --git a/morphlib/morph2.py b/morphlib/morph2.py
> index 73d55d1..6af9e9e 100644
> --- a/morphlib/morph2.py
> +++ b/morphlib/morph2.py
> @@ -14,16 +14,16 @@
>  # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
>  
>  
> -import sys
> -have_python27 = sys.version_info >= (2,7)
> -
> -import collections
> -if not hasattr(collections, 'OrderedDict'): # pragma: no cover
> -    collections.OrderedDict = dict
>  import copy
> -import json
>  import re
>  
> +try:
> +    from collections import OrderedDict
> +    import json
> +except ImportError: # pragma: no cover
> +    from ordereddict import OrderedDict
> +    import simplejson as json
> +

This implies that if your collections module doesn't have OrderedDict
then you also don't have json with object_pairs_hook.

I can't decide if this is elegant or incomplete.
I'll have to check what simplejson has before I can merge this.

>  
>  class Morphology(object):
>  
> @@ -58,19 +58,8 @@ class Morphology(object):
>          ]
>      }
>  
> -    if have_python27: # pragma: no cover
> -        @staticmethod
> -        def _order_keys(pairs):
> -            result = collections.OrderedDict()
> -            for k,v in pairs:
> -                result[k] = v
> -            return result
> -
>      def __init__(self, text):
> -        if have_python27: # pragma: no cover
> -            self._dict = json.loads(text, object_pairs_hook=self._order_keys)
> -        else: # pragma: no cover
> -            self._dict = json.loads(text)
> +        self._dict = json.loads(text, object_pairs_hook=OrderedDict)

I hadn't noticed that the _order_keys method was redundant, good catch.




More information about the baserock-dev mailing list