Chris@87: #!/usr/bin/env python Chris@87: """Prints type-coercion tables for the built-in NumPy types Chris@87: Chris@87: """ Chris@87: from __future__ import division, absolute_import, print_function Chris@87: Chris@87: import numpy as np Chris@87: Chris@87: # Generic object that can be added, but doesn't do anything else Chris@87: class GenericObject(object): Chris@87: def __init__(self, v): Chris@87: self.v = v Chris@87: Chris@87: def __add__(self, other): Chris@87: return self Chris@87: Chris@87: def __radd__(self, other): Chris@87: return self Chris@87: Chris@87: dtype = np.dtype('O') Chris@87: Chris@87: def print_cancast_table(ntypes): Chris@87: print('X', end=' ') Chris@87: for char in ntypes: print(char, end=' ') Chris@87: print() Chris@87: for row in ntypes: Chris@87: print(row, end=' ') Chris@87: for col in ntypes: Chris@87: print(int(np.can_cast(row, col)), end=' ') Chris@87: print() Chris@87: Chris@87: def print_coercion_table(ntypes, inputfirstvalue, inputsecondvalue, firstarray, use_promote_types=False): Chris@87: print('+', end=' ') Chris@87: for char in ntypes: print(char, end=' ') Chris@87: print() Chris@87: for row in ntypes: Chris@87: if row == 'O': Chris@87: rowtype = GenericObject Chris@87: else: Chris@87: rowtype = np.obj2sctype(row) Chris@87: Chris@87: print(row, end=' ') Chris@87: for col in ntypes: Chris@87: if col == 'O': Chris@87: coltype = GenericObject Chris@87: else: Chris@87: coltype = np.obj2sctype(col) Chris@87: try: Chris@87: if firstarray: Chris@87: rowvalue = np.array([rowtype(inputfirstvalue)], dtype=rowtype) Chris@87: else: Chris@87: rowvalue = rowtype(inputfirstvalue) Chris@87: colvalue = coltype(inputsecondvalue) Chris@87: if use_promote_types: Chris@87: char = np.promote_types(rowvalue.dtype, colvalue.dtype).char Chris@87: else: Chris@87: value = np.add(rowvalue, colvalue) Chris@87: if isinstance(value, np.ndarray): Chris@87: char = value.dtype.char Chris@87: else: Chris@87: char = np.dtype(type(value)).char Chris@87: except ValueError: Chris@87: char = '!' Chris@87: except OverflowError: Chris@87: char = '@' Chris@87: except TypeError: Chris@87: char = '#' Chris@87: print(char, end=' ') Chris@87: print() Chris@87: Chris@87: print("can cast") Chris@87: print_cancast_table(np.typecodes['All']) Chris@87: print() Chris@87: print("In these tables, ValueError is '!', OverflowError is '@', TypeError is '#'") Chris@87: print() Chris@87: print("scalar + scalar") Chris@87: print_coercion_table(np.typecodes['All'], 0, 0, False) Chris@87: print() Chris@87: print("scalar + neg scalar") Chris@87: print_coercion_table(np.typecodes['All'], 0, -1, False) Chris@87: print() Chris@87: print("array + scalar") Chris@87: print_coercion_table(np.typecodes['All'], 0, 0, True) Chris@87: print() Chris@87: print("array + neg scalar") Chris@87: print_coercion_table(np.typecodes['All'], 0, -1, True) Chris@87: print() Chris@87: print("promote_types") Chris@87: print_coercion_table(np.typecodes['All'], 0, 0, False, True)