pk3hunum¶
pykit3 is is a collection of toolkit in python3.
Documentation for the Code¶
pk3hunum convert numbers(or numbers in dict or list) to human readable format in string.
>>> hunum(103425)
'101.0K'
>>> hunum({ 'total': 10240, 'progress': [1, 1024*2.1, 1024*3.2], })
{'total': '10K', 'progress': ['1', '2.10K', '3.20K']}
>>> parsenum('5.2K')
5324.8
>>> parsenum('10%')
0.1
-
pk3hunum.
value_to_unit
¶ map of int to unit, e.g.: 1024 -> “K”, 1024² -> “M”.
Usage:
>>> value_to_unit[1024**2] 'M' >>> unit_to_value['K'] 1024
Type: dict
-
pk3hunum.
unit_to_value
¶ reverse map of value_to_unit.
Type: dict
Functions¶
-
pk3hunum.
hunum
(data, unit=None, include=None, exclude=None)¶ hunum convert number or dict/list of number to string in a format easy to read for human.
Parameters: - data –
could be a primitive type: int or float, or a non-primitive type object list or dict.
- For primitive type like int, it converts it to string.
- For non-primitive type like dict, it traverse recursively over all of its fields and convert them to string.
- unit (int) –
specifies the unit of the number in the result string. It could be one of: 1024 (K), 1024² (M) … 1024⁸ (Y).
If it is None, a proper unit will be chosen to output the shortest string. For example, for 102400 it chooses K. For 10240000 it chooses M.
- include (bool) –
specifies to convert only a subset of the keys of a dict data. It could be a list, tuple or set of keys.
- It has no effect on a primitive data.
- It is not passed to sub dict or list.
- exclude (bool) –
specifies NOT to convert some of the keys of a dict data. It could be a list, tuple or set of keys.
- It has no effect on a primitive data.
- It is not passed to sub dict or list.
Returns: int/dict/list.
- For a primitive type data, it returns a string representing the number.
- For a dict or list, it makes a duplicate of data and convert its number fields. It leaves the original data intact.
- data –
-
pk3hunum.
parsenum
(data, safe=None)¶ Parse humanized number string like 10.5K to int or float. It also parses percentage number to float.
Parameters: - data (str) –
number string.
Valid units are: k, m, g, t, p, e, z and y. Suffix b and i will be ignored. For example: 10.1K, 10.1k, 10.1Kb and 10.1Ki are all the same.
For percentage number, valid unit is %. For example: 10.1%.
- safe –
if safe is True and data is not a valid number string, it silently returns the original data, instead of raising an ValueError.
By default it is False.
Returns: int/float.
- data (str) –
-
pk3hunum.
parseint
(data, safe=None)¶ Same as parsenum but it always casts result to a int number.