adding print_args
[notebooks.git] / fmda / utils.py
blobac4cce6bcea497b68a4c1c0aa18cd1c2210cf2c2
1 import numpy as np
2 from functools import singledispatch
3 import pandas as pd
5 def vprint(*args):
6 import inspect
8 frame = inspect.currentframe()
9 if 'verbose' in frame.f_back.f_locals:
10 verbose = frame.f_back.f_locals['verbose']
11 else:
12 verbose = False
14 if verbose:
15 for s in args[:(len(args)-1)]:
16 print(s, end=' ')
17 print(args[-1])
20 ## Generic function to hash dictionary of various types
22 @singledispatch
23 ## Top level hash function with built-in hash function for str, float, int, etc
24 def hash2(x):
25 return hash(x)
27 @hash2.register(np.ndarray)
28 ## Hash numpy array, hash array with pandas and return integer sum
29 def _(x):
30 # return hash(x.tobytes())
31 return np.sum(pd.util.hash_array(x))
33 @hash2.register(list)
34 ## Hash list, convert to tuple
35 def _(x):
36 return hash2(tuple(x))
38 @hash2.register(tuple)
39 def _(x):
40 r = 0
41 for i in range(len(x)):
42 r+=hash2(x[i])
43 return r
45 @hash2.register(dict)
46 ## Hash dict, loop through keys and hash each element via dispatch. Return hashed integer sum of hashes
47 def _(x, keys = None, verbose = False):
48 r = 0 # return value integer
49 if keys is None: # allow user input of keys to hash, otherwise hash them all
50 keys = [*x.keys()]
51 keys.sort()
52 for key in keys:
53 if (verbose): print('Hashing', key)
54 r += hash2(x[key])
55 return hash(r)
57 def print_args(func, *args, **kwargs):
58 # wrapper to trace function call and arguments
59 print(f"Called: {func.__name__}")
60 print("Arguments:")
61 for arg in args:
62 print(f" {arg}")
63 for key, value in kwargs.items():
64 print(f" {key}={value}")
65 return func(*args, **kwargs)
67 def print_args_test():
68 def my_function(a, b):
69 # some code here
70 return a + b
71 print_args(my_function, a=1, b=2)