source: geniuswebcore/geniusweb/utils.py@ 97

Last change on this file since 97 was 96, checked in by Bart Vastenhouw, 2 years ago

Fixed small issues in domaineditor.

File size: 1.4 KB
Line 
1'''
2A few simple but often needed tools.
3'''
4from _collections_abc import dict_items #type:ignore
5from typing import TypeVar, Optional
6
7
8def 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
24def 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
30T = TypeVar('T')
31def 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
40def 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)
Note: See TracBrowser for help on using the repository browser.