[73] | 1 | '''
|
---|
| 2 | A few simple but often needed tools.
|
---|
| 3 | '''
|
---|
| 4 | from _collections_abc import dict_items #type:ignore
|
---|
| 5 | from typing import TypeVar, Optional
|
---|
| 6 |
|
---|
| 7 |
|
---|
| 8 | def toStr(d)->str:
|
---|
| 9 | '''
|
---|
| 10 | prettyprint a "primitive" like dict or list,
|
---|
| 11 | similar to how java prints it.
|
---|
| 12 | In java, strings are NOT quoted.
|
---|
| 13 | '''
|
---|
| 14 | if isinstance(d, dict):
|
---|
| 15 | return "{"+ (", ".join([toStr(k)+"="+toStr(v) for (k,v) in d.items()]))+"}"
|
---|
| 16 | if isinstance(d, list):
|
---|
| 17 | return "["+(", ".join([toStr(v) for v in d])) + "]"
|
---|
| 18 | if isinstance(d, tuple):
|
---|
| 19 | return "("+(", ".join([toStr(v) for v in d]))+")"
|
---|
| 20 | if isinstance(d, set):
|
---|
| 21 | return "{"+(", ".join([toStr(v) for v in d]))+"}"
|
---|
| 22 | return str(d)
|
---|
| 23 |
|
---|
| 24 | def toTuple(d:dict) -> tuple:
|
---|
| 25 | '''
|
---|
| 26 | Converts dict into tuples of tuples. Used mainly to compute hash
|
---|
| 27 | '''
|
---|
| 28 | return tuple([(k,v) for (k,v) in d.items()])
|
---|
| 29 |
|
---|
| 30 | T = TypeVar('T')
|
---|
| 31 | def val(v:Optional[T])->T:
|
---|
| 32 | '''
|
---|
| 33 | @return the value contained in the optional.
|
---|
| 34 | Raises exception if the value is None.
|
---|
| 35 | '''
|
---|
| 36 | if not v:
|
---|
| 37 | raise ValueError("Value is not set")
|
---|
| 38 | return v
|
---|
| 39 |
|
---|
| 40 | def HASH(obj) -> int:
|
---|
| 41 | '''
|
---|
| 42 | hashes built-in objects, even dict and list of built-in objects.
|
---|
| 43 | '''
|
---|
| 44 | if isinstance(obj, list) or isinstance(obj, set) or\
|
---|
| 45 | isinstance(obj, tuple) or isinstance(obj, dict_items):
|
---|
| 46 | return 31+sum([HASH(e) for e in obj])
|
---|
| 47 | if isinstance(obj, dict):
|
---|
| 48 | return HASH(obj.items())
|
---|
| 49 | return hash(obj) |
---|