In [ ]:
import warnings
import numpy.testing as npt
import numpy as np
import sys
Errors & Exceptions in Python: https://docs.python.org/3/tutorial/errors.html
Built-In Excpetions in Python: https://docs.python.org/2/library/exceptions.html
Numpy Testing: http://docs.scipy.org/doc/numpy/reference/routines.testing.html
In [ ]:
def check_python_version():
print 'Python version:\n', sys.version
assert sys.version_info < (3,0)
In [ ]:
check_python_version()
In [ ]:
def improved_check_python_version():
print 'Python version:\n', sys.version
try:
assert sys.version_info < (3,0)
except:
raise AssertionError('Incompatible version of Python: use Python version < 3.0')
In [ ]:
improved_check_python_version()
In [ ]:
def test_type_float(var):
if not isinstance(var, float):
raise TypeError('Expected input type == float')
In [ ]:
f = 1.
In [ ]:
# Since the input type is a float, no error is raised.
test_type_float(f)
In [ ]:
i = 1
In [ ]:
# Since the input type is a list, an error is raised.
test_type_float(i)
In [ ]:
def incorrect_divide_by_two(var):
return var / 2
In [ ]:
print incorrect_divide_by_two(f)
In [ ]:
print incorrect_divide_by_two(i)
In [ ]:
def correct_divide_by_two(var):
'''
Divides input by two.
INPUT
var : float
'''
test_type_float(var)
return var / 2
In [ ]:
correct_divide_by_two?
In [ ]:
print correct_divide_by_two(f)
In [ ]:
print correct_divide_by_two(i)
In [ ]:
def divide_by_two(var):
if isinstance(var, int):
warnings.warn('Performing floor division. Input type == int', Warning)
return var / 2
In [ ]:
divide_by_two(1)
In [ ]:
divide_by_two(np.array([1]))
In [ ]:
def divide_by_two(var):
if isinstance(var, int):
warnings.warn('Performing floor division. Input type == int', Warning)
if isinstance(var, np.ndarray):
if var.dtype == int:
warnings.warn('Performing floor division. numpy.dtype == int', Warning)
return var / 2
In [ ]:
divide_by_two(np.array([1]))
In [ ]: