Commit adcb9dcd authored by Simon Conseil's avatar Simon Conseil

Add some utilities (isiter, progressbar, isnotebook)

parent f078c725
......@@ -40,10 +40,17 @@ import warnings
from astropy.utils import minversion
from mpdaf.tools.util import (chdir, deprecated, broadcast_to_cube, timeit,
timer)
timer, isiter, progressbar)
PYTEST_LT_3_3 = not minversion('pytest', '3.3')
try:
import tqdm
except ImportError:
HAS_TQDM = False
else:
HAS_TQDM = True
def test_chdir(tmpdir):
cwd = os.getcwd()
......@@ -106,3 +113,17 @@ def test_timer(caplog):
assert out == 'a'
assert re.search(r'Request took 0.1\d\d sec.', caplog.text) is not None
def test_isiter():
assert isiter([])
assert isiter((1, 2, 3))
assert not isiter(1)
assert isiter(np.array([1, 2, 3]))
@pytest.mark.skipif(not HAS_TQDM, reason="requires tqdm")
def test_progressbar():
bar = progressbar([1, 2, 3])
assert isinstance(bar, tqdm.tqdm)
assert next(iter(bar)) == 1
......@@ -48,7 +48,7 @@ from time import time
__all__ = ('MpdafWarning', 'MpdafUnitsWarning', 'deprecated', 'chdir',
'timeit', 'timer', 'broadcast_to_cube', 'LowercaseOrderedDict',
'all_subclasses')
'all_subclasses', 'isiter', 'isnotebook', 'progressbar')
# NOTE(kgriffs): We don't want our deprecations to be ignored by default,
......@@ -145,6 +145,37 @@ def all_subclasses(cls):
[s for c in cls.__subclasses__() for s in all_subclasses(c)])
def isiter(val):
"""Return True is val is iterable."""
try:
iter(val)
except TypeError:
return False
else:
return True
def isnotebook(): # pragma: no cover
"""Detect if running inside a jupyter notebook."""
try:
shell = get_ipython().__class__.__name__
if shell == 'ZMQInteractiveShell':
return True # Jupyter notebook or qtconsole
elif shell == 'TerminalInteractiveShell':
return False # Terminal running IPython
else:
return False # Other type (?)
except NameError:
return False # Probably standard Python interpreter
def progressbar(*args, **kwargs):
"""Wrapper for tqdm progress bar, with notebook detection."""
from tqdm import tqdm, tqdm_notebook
func = tqdm_notebook if isnotebook() else tqdm
return func(*args, **kwargs)
# Here we inherit unnecessarily from OrderedDict.
# This is because when merging astropy.table.Table() objects, an explicit
# check for the metadata object is a <dict> instance
......
......@@ -231,7 +231,7 @@ setup(
setup_requires=['numpy>=1.10.0'],
install_requires=['numpy>=1.10.0', 'scipy', 'matplotlib', 'astropy>=1.0'],
extras_require={
'all': ['numexpr', 'fitsio', 'adjustText'],
'all': ['numexpr', 'fitsio', 'adjustText', 'joblib', 'tqdm'],
},
tests_require=['pytest'],
package_dir={'': 'lib'},
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment