Skip to content

Commit fd9f951

Browse files
committed
Fixes Py2/3 compatibility with lca and file handling
1 parent 063560f commit fd9f951

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

taxonomy/core.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,25 @@
22
Main Taxonomy object/class code.
33
"""
44
import gzip
5-
import itertools
65
import networkx
76
import os
7+
import sys
8+
89
try:
910
import simplejson as json
1011
except ImportError:
1112
import json
1213

14+
try:
15+
from itertools import izip_longest as zip_longest
16+
except ImportError:
17+
from itertools import zip_longest
18+
19+
try:
20+
from functools import reduce
21+
except ImportError:
22+
pass
23+
1324
from networkx.readwrite import json_graph
1425

1526
from taxonomy.exceptions import TaxonomyException
@@ -74,13 +85,13 @@ def save(self, f, compress=True):
7485
out = {}
7586
out['node_link_data'] = json_graph.node_link_data(self.tax_graph)
7687
out['metadata'] = self.metadata
77-
if isinstance(f, (file, gzip.GzipFile)):
88+
if (sys.version_info[0] == 2 and isinstance(f, (file, gzip.GzipFile))) or hasattr(f, 'write'):
7889
json.dump(out, f)
7990
else:
8091
if gzip:
8192
if os.path.splitext(f)[1] != '.gz':
8293
f = f + '.gz'
83-
json.dump(out, gzip.open(f, mode='w'))
94+
json.dump(out, gzip.open(f, mode='wt'))
8495
else:
8596
json.dump(out, open(f, mode='w'))
8697

@@ -133,7 +144,7 @@ def lowest_common_ancestor_double(self, tax_id_1, tax_id_2):
133144
parent_gen_2 = networkx.dfs_preorder_nodes(self.tax_graph, tax_id_2)
134145
parent_tax_ids1 = set()
135146
parent_tax_ids2 = set()
136-
for ptax_id_1, ptax_id_2 in itertools.izip_longest(parent_gen_1, parent_gen_2,
147+
for ptax_id_1, ptax_id_2 in zip_longest(parent_gen_1, parent_gen_2,
137148
fillvalue='1'):
138149
parent_tax_ids1.add(ptax_id_1)
139150
if ptax_id_2 in parent_tax_ids1:

0 commit comments

Comments
 (0)