Skip to content

Commit

Permalink
Refactor Python 2/3 compatibility from imread (#48)
Browse files Browse the repository at this point in the history
* Refactor `_pycompat` from `imread.__init__`

Pulls out some Python 2/3 support content from `imread.__init__` into
`_pycompat`. Cleans up the `imread` function a bit as a result.

* Test Python 2/3 compatibility functions

Provide some basic tests of the Python 2/3 compatibility functions for
`imread` to make sure they work as expected on both Python versions.
  • Loading branch information
jakirkham committed Sep 1, 2018
1 parent e9b8315 commit 6be6b61
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 12 deletions.
16 changes: 4 additions & 12 deletions dask_image/imread/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
import numpy
import pims

from . import _pycompat


def imread(fname, nframes=1):
"""
Expand All @@ -36,16 +38,6 @@ def imread(fname, nframes=1):
A Dask Array representing the contents of all image files.
"""

try:
irange = xrange
except NameError:
irange = range

try:
izip = itertools.izip
except AttributeError:
izip = zip

if not isinstance(nframes, numbers.Integral):
raise ValueError("`nframes` must be an integer.")
if (nframes != -1) and not (nframes > 0):
Expand Down Expand Up @@ -76,13 +68,13 @@ def _read_frame(fn, i):
return numpy.asanyarray(imgs[i])

lower_iter, upper_iter = itertools.tee(itertools.chain(
irange(0, shape[0], nframes),
_pycompat.irange(0, shape[0], nframes),
[shape[0]]
))
next(upper_iter)

a = []
for i, j in izip(lower_iter, upper_iter):
for i, j in _pycompat.izip(lower_iter, upper_iter):
a.append(dask.array.from_delayed(
dask.delayed(_read_frame)(fname, slice(i, j)),
(j - i,) + shape[1:],
Expand Down
11 changes: 11 additions & 0 deletions dask_image/imread/_pycompat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# -*- coding: utf-8 -*-

try:
irange = xrange
except NameError:
irange = range

try:
from itertools import izip
except ImportError:
izip = zip
23 changes: 23 additions & 0 deletions tests/test_dask_image/test_imread/test__pycompat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-


from __future__ import absolute_import

import dask_image.imread._pycompat


def test_irange():
r = dask_image.imread._pycompat.irange(5)

assert not isinstance(r, list)

assert list(r) == [0, 1, 2, 3, 4]


def test_izip():
r = dask_image.imread._pycompat.izip([1, 2], [3, 4, 5])

assert not isinstance(r, list)

assert list(r) == [(1, 3), (2, 4)]

0 comments on commit 6be6b61

Please sign in to comment.