pawnlib.typing package
Submodules
pawnlib.typing.check module
from pawnlib.typing import check
- is_json(s)[source]
Check if a string is valid JSON.
- Parameters:
s – a string to check if it is valid JSON.
- Return type:
bool- Returns:
True if the string is valid JSON, False otherwise.
Example
check.is_json('{"name": "John", "age": 30, "city": "New York"}') # >> True check.is_json('{"name": "John", "age": 30, "city": "New York",}') # >> False
- is_float(s)[source]
Check if a value is float
- Parameters:
s (Any) – A value to check if it is a float
- Returns:
True if the value is a float, False otherwise
- Return type:
bool
Example
check.is_float(3.14) # >> True check.is_float("3.14") # >> True check.is_float("hello") # >> False
- is_int(s)[source]
Check if a value is integer.
- Parameters:
s (Any) – A value to check.
- Returns:
True if the value is an integer, False otherwise.
- Return type:
bool
Example
check.is_int(1) # >> True check.is_int(1.0) # >> False check.is_int("2") # >> True check.is_int("2.0") # >> False
- is_number(s)[source]
Check if a value is an int or a float (number).
- Parameters:
s (Any) – A value to check if it is a number
- Returns:
True if the value is an int or float, False otherwise
- Return type:
bool
Example
is_number(42) # >> True is_number(3.14) # >> True is_number("42") # >> True is_number("3.14") # >> True is_number("hello") # >> False
- is_hex(s)[source]
Check if a value is hexadecimal
- Parameters:
s – string to check
- Return type:
bool- Returns:
True if s is hexadecimal, False otherwise
Example
check.is_hex("1a") # >> True check.is_hex("g") # >> False
- is_regex_keyword(keyword, value)[source]
The is_regex_keyword function takes two strings, a keyword and a value. If the keyword starts with / and ends with /, then it is treated as a regex pattern. The function checks if the regex pattern is contained within the value string. If so, True is returned; otherwise False.
- Parameters:
keyword:str – Check if the value:str parameter matches the keyword
value:str – Check if the keyword is in the value
- Return type:
bool- Returns:
True if the keyword is a regex and matches
Example
check.is_regex_keyword("/hello/", "hello world") # >> True check.is_regex_keyword("(hello)+", "hello world") # >> True check.is_regex_keyword("hello", "world") # >> False
- is_regex_keywords(keywords, value)[source]
Check the value of the keyword regular expression.
- Parameters:
keywords –
value –
- Return type:
bool- Returns:
Example
from pawnlib.typing import check check.is_regex_keywords(keywords="/sdsd/", value="sdsd") # >> True check.is_regex_keywords(keywords="/ad/", value="sdsd") # >> False
- is_valid_ipv4(ip)[source]
Validates IPv4 addresses.
- Parameters:
ip – (str) IPv4 address to validate.
- Returns:
(bool) True if valid IPv4 address, False otherwise.
Example
check.is_valid_ipv4("192.168.0.1") # >> True check.is_valid_ipv4("255.255.255.0") # >> True check.is_valid_ipv4("300.168.0.1") # >> False
- is_valid_ipv6(ip)[source]
Validates IPv6 addresses.
- Parameters:
ip – A string representing an IPv6 address.
- Returns:
True if the given string is a valid IPv6 address, False otherwise.
Example
check.is_valid_ipv6("2001:0db8:85a3:0000:0000:8a2e:0370:7334") # >> True check.is_valid_ipv6("2001:0db8:85a3::8a2e:0370:7334") # >> True check.is_valid_ipv6("2001:0db8:85a3:0:0:8a2e:0370:7334:1234") # >> False
- is_valid_url(url, strict=True)[source]
Check if the given url is valid.
- Parameters:
url – (str) url to check
strict (optional) – If False, URLs without a TLD (e.g., “http://example”) are considered valid. Defaults to True. |default|
True
- Returns:
(bool) True if valid, False otherwise
Example
check.is_valid_url("google.com") # >> True check.is_valid_url("http://google.com") # >> True check.is_valid_url("https://www.google.com/search?q=python") # >> True check.is_valid_url("ftp://example.com") # >> False
- is_valid_private_key(text=None)[source]
Validates the Private Key
- Parameters:
text (str) – A string of private key text. |default|
None- Returns:
A boolean value indicating whether the private key is valid or not.
- Return type:
bool
Example
is_valid_private_key("0x1234567890123456789012345678901234567890123456789012345678901234") # >> True is_valid_private_key("0x12345678901234567890123456789012345678901234567890123456789012345") # >> False
- is_valid_token_address(text=None, prefix='hx')[source]
Validates the token address.
- Parameters:
- Returns:
A boolean value indicating whether the token address is valid or not.
Example
is_valid_token_address("hx1234567890123456789012345678901234567890") # >> True is_valid_token_address("tx1234567890123456789012345678901234567890") # >> False
- is_valid_tx_hash(text=None)[source]
Validates the txHash
- Parameters:
text (str) – A string of txHash text. |default|
None- Returns:
A boolean value indicating whether the txHash is valid or not.
- Return type:
bool
Example
is_valid_tx_hash("0x1234567890123456789012345678901234567890123456789012345678901234") # >> True is_valid_tx_hash("0x12345678901234567890123456789012345678901234567890123456789012345") # >> False
- list_depth(l)[source]
Returns the depth count of a list.
- Parameters:
l – A list.
- Returns:
An integer representing the depth count of the list.
Example
list_depth([1, 2, 3]) # >> 1 list_depth([1, [2, 3], [4, [5, 6]]]) # >> 3
- guess_type(s)[source]
Guess the type of string.
- Parameters:
s –
- Returns:
Example:
from pawnlib.typing import check check.guess_type("True") # >> <class 'bool'> check.guess_type("2.2") # >> <class 'float'>
- return_guess_type(value)[source]
This function returns the result of
guess_type()and_strbool()- Parameters:
value (any) – A value to guess the type of.
- Returns:
The guessed type of the input value.
- Return type:
any
Example
return_guess_type("True") # >> <class 'bool'> return_guess_type("2.2") # >> <class 'float'>
- error_and_exit(message, title='Error Occurred', exit_code=1)[source]
Print an error message with the caller’s file name and line number, then exit the program.
- sys_exit(message='', return_code=-1)[source]
This function executes the sys.exit() method.
- Parameters:
- Returns:
None
Example
# Example 1: Exit with default return code and message sys_exit() # Example 2: Exit with custom return code and message sys_exit("An error occurred!", 1)
- is_include_list(target=None, include_list=[], ignore_case=True)[source]
Check if target string exists in list.
- Parameters:
- Returns:
Return True if target string exists in include_list, else False.
- Return type:
bool
Example
result = is_include_list("hello world", ["hello", "world"]) # >> True result = is_include_list("hello world", ["hello", "world"], ignore_case=False) # >> False
- keys_exists(element, *keys)[source]
Check if keys (nested) exist in
element(dict).- Parameters:
element (
dict) – The dictionary to search.keys (
str) – The keys to traverse in the dictionary.
- Return type:
bool- Returns:
True if all keys exist, False otherwise.
Example
dict_example = { "name": "example", "description": { "description_2": "222", "description_3": "333", }, "none_value_key": None, } keys_exists(dict_example, 'name', 'description') # >> True keys_exists(dict_example, 'name', 'none_value_key') # >> True keys_exists(dict_example, 'name', 'none_key') # >> False
- get_if_keys_exist(element, *keys, default=None)[source]
Retrieve the value from a nested dictionary if keys exists in
element.- Parameters:
element (
dict) – The dictionary to search.keys (
str) – The keys to traverse in the dictionary.default (
Optional[Any], optional) – The default value to return if the keys do not exist. |default|None
- Return type:
Any- Returns:
The value if all keys exist, else the default value.
Example
dict_example = { "name": "example", "description": { "description_2": "222", "description_3": "333", }, "none_value_key": None, "nested_list": [{"key1": "value1"}, {"key2": "value2"}] } get_if_keys_exist(dict_example, 'name') # >> 'example' get_if_keys_exist(dict_example, 'description', 'description_2') # >> '222' get_if_keys_exist(dict_example, 'none_value_key') # >> None get_if_keys_exist(dict_example, 'name', 'none_key') # >> None get_if_keys_exist(dict_example, 'nested_list', '1', 'key2') # >> 'value2' get_if_keys_exist(dict_example, 'nested_list', '0', 'key1') # >> 'value1'
- detect_encoding(byte_data, default_encode='utf8')[source]
Detects the encoding of byte data.
- Parameters:
byte_data (bytes) – The byte data to be decoded.
default_encode (str) – The default encoding to be used if no suitable encoding is found. Defaults to “utf8”. |default|
'utf8'
- Returns:
The detected encoding.
- Return type:
str
- Raises:
UnicodeDecodeError – If the byte data cannot be decoded using any of the available encodings.
Examples
Detect the encoding of byte data:
byte_data = b"ABC" detect_encoding(byte_data) # Output: 'ascii' byte_data = b"ê°ëë¤" detect_encoding(byte_data) # Output: 'utf8' byte_data = b"°¡±âÆ®" detect_encoding(byte_data) # Output: 'euc-kr'
- check_key_and_type(data, key, expected_type)[source]
Checks if a specific key exists in a dictionary and if its value is of the expected type.
- Parameters:
data – The dictionary to check.
key – The key to check for in the dictionary.
expected_type – The expected type of the value (e.g., list, dict, etc.).
- Returns:
True if the key exists and its value is of the expected type, False otherwise.
Examples
result = { 'res': [1, 2, 3], 'config': {'option': True}, 'count': 10 } # Check if 'res' exists and is a list is_res_list = check_key_and_type(result, 'res', list) print(is_res_list) # Output: True # Check if 'config' exists and is a dict is_config_dict = check_key_and_type(result, 'config', dict) print(is_config_dict) # Output: True # Check if 'count' exists and is a string is_count_string = check_key_and_type(result, 'count', str) print(is_count_string) # Output: False # Check if 'nonexistent_key' exists and is a list is_nonexistent_list = check_key_and_type(result, 'nonexistent_key', list) print(is_nonexistent_list) # Output: False
pawnlib.typing.converter module
from pawnlib.typing import converter
- class HexConverter(data, convert_type='int', decimal_places=0, prefix='', suffix='')[source]
Bases:
UserDictA dictionary-like class for converting hexadecimal strings to numerical values in nested data structures.
Supports conversion of hex strings (starting with ‘0x’) to integers or scaled floats (tint). Provides options for formatting numbers with prefixes, suffixes, and thousands separators. Handles nested dictionaries and lists recursively.
- Parameters:
data (Union[dict, list, str]) – Input data structure containing hex values (dict/list/str)
convert_type (str) – Conversion type - ‘int’ for integer, ‘tint’ for scaled float (default: ‘int’) |default|
'int'decimal_places (int) – Number of decimal places for rounding (applies to ‘tint’ conversion) |default|
0prefix (str) – String prefix to add to converted values |default|
''suffix (str) – String suffix to add to converted values |default|
''
# Example usage from hexconverter import HexConverter data = { 'network': '0x1a', 'values': ['0x3e8', '0x1f4'], 'nested': {'threshold': '0x3b9aca00'} } # Basic conversion converter = HexConverter(data) print(converter) # Output: # {'network': 26, 'values': [1000, 500], 'nested': {'threshold': 1000000000}} # Formatted output with currency formatted = converter.pretty_format( prefix='$', thousands_separator=',', decimal_places=2 ) print(formatted['nested']['threshold']) # Output: '$1,000,000,000.00' # Debug information debug_data = converter.debug_info() print(debug_data['values'][0]) # Output: # {'original': '0x3e8', 'converted': 1000, 'type': 'int'}
Initialize HexConverter with configuration parameters.
- __init__(data, convert_type='int', decimal_places=0, prefix='', suffix='')[source]
Initialize HexConverter with configuration parameters.
- pretty_format(decimal_places=3, prefix='', suffix='', thousands_separator=',')[source]
Format the converted data with specified formatting options.
- Parameters:
decimal_places (Optional[int]) – Number of decimal places for formatting (default is 3). |default|
3prefix (str) – String prefix to add to formatted values. |default|
''suffix (str) – String suffix to add to formatted values. |default|
''thousands_separator (str) – Character to use as the thousands separator (default is ‘,’). |default|
','
- Returns:
A dictionary with formatted values.
- Return type:
Dict
# Example usage of pretty_format formatted = converter.pretty_format( decimal_places=2, prefix='$', thousands_separator=',' ) print(formatted['values']) # Output: # ['$1,000.00', '$500.00']
- debug_info()[source]
Provide detailed debug information about the conversion process.
Includes the original hex value, its converted numerical value, and the type of the converted value.
- Returns:
A dictionary containing debug information.
- Return type:
Dict
# Example usage of debug_info debug_data = converter.debug_info() print(debug_data['network']) # Output: # {'original': '0x1a', 'converted': 26, 'type': 'int'}
- class StackList(max_length=1000)[source]
Bases:
objectStack List
- Parameters:
max_length (optional) – max length size for list |default|
1000
Example
from pawnlib.typing.converter import StackList stack = StackList(max_length=10) for i in range(1, 100) stack.push(i) stack.mean() # > 94.5 stack.median() # > 94.5
- class ErrorCounter(max_consecutive_count=10, increase_index=0.5, reset_threshold_rate=80)[source]
Bases:
objectA class for counting consecutive errors and calculating dynamic count.
- Parameters:
Example
ec = ErrorCounter() ec.push(True) ec.push(False)
- push(error_boolean=True)[source]
Pushes an error boolean to the stack and updates counts.
- Parameters:
error_boolean (bool) – Boolean indicating if an error occurred. Default is True. |default|
True- Returns:
None
Example
ec.push(True) ec.push(False)
- calculate_dynamic_count()[source]
Calculates the dynamic count and updates hit rate and counter if necessary.
- Returns:
None
Example
ec.calculate_dynamic_count()
- is_ok()[source]
Checks if the consecutive count is less than the maximum allowed.
- Returns:
True if the consecutive count is less than the maximum allowed, False otherwise.
Example
ec.is_ok()
- push_ok(error_boolean=True)[source]
Pushes an error boolean to the stack and checks if it is ok.
- Parameters:
error_boolean (bool) – Boolean indicating if an error occurred. Default is True. |default|
True- Returns:
True if it is ok, False otherwise.
Example
ec.push_ok(True)
- class MedianFinder[source]
Bases:
objectA class to find the median of a stream of numbers.
Example
mf = MedianFinder() mf.add_number(1) mf.add_number(2) mf.median() # 1.5 mf.add_number(3) mf.median() # 2.0
Initialize the data structure.
Example
mf = MedianFinder()
- add_number(num)[source]
Add a number to the data structure.
- Parameters:
num (int) – An integer to be added to the data structure.
- Returns:
None
Example
mf = MedianFinder() mf.add_number(1) mf.add_number(2) mf.add_number(3)
- class FlatDict(value=None, delimiter='.', dict_class=<class 'dict'>)[source]
Bases:
MutableMappingFlatDictis a dictionary object that allows for single level, delimited key/value pair mapping of nested dictionaries. The default delimiter value is.but can be changed in the constructor or by callingFlatDict.set_delimiter().Example
from pawnlib.typing.converter import FlatDict config = { "1": "2", "1-2": { "2-1": "3-1" }, } dot_dict = FlatDict(config) dot_dict.get('1-2.2-1') # >> '3-1'
- as_dict()[source]
Return the
FlatDictas adictReturn the original nested dictionary structure as it was input. This reverses the flattening process to reconstruct the original data. :rtype: dict
- get(key, d=None)[source]
Return the value for key if key is in the flat dictionary, else default. If default is not given, it defaults to
None, so that this method never raisesKeyError. :param mixed key: The key to get :param mixed d: The default value :rtype: mixed
- items()[source]
Return a copy of the flat dictionary’s list of
(key, value)pairs.Note
CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the flat dictionary’s history of insertions and deletions.
- Return type:
list
- iteritems()[source]
Return an iterator over the flat dictionary’s (key, value) pairs. See the note for
flatdict.FlatDict.items(). Usingiteritems()while adding or deleting entries in the flat dictionary may raiseRuntimeErroror fail to iterate over all entries. :rtype: Iterator :raises: RuntimeError
- iterkeys()[source]
Iterate over the flat dictionary’s keys. See the note for
flatdict.FlatDict.items(). Usingiterkeys()while adding or deleting entries in the flat dictionary may raiseRuntimeErroror fail to iterate over all entries. :rtype: Iterator :raises: RuntimeError
- itervalues()[source]
Return an iterator over the flat dictionary’s values. See the note
flatdict.FlatDict.items(). Usingitervalues()while adding or deleting entries in the flat dictionary may raise aRuntimeErroror fail to iterate over all entries. :rtype: Iterator :raises: RuntimeError
- keys()[source]
Return a copy of the flat dictionary’s list of keys. See the note for
flatdict.FlatDict.items(). :rtype: list
- pop(key, default=<object object>)[source]
If key is in the flat dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary,
KeyErroris raised. :param mixed key: The key name :param mixed default: The default value :rtype: mixed
- setdefault(key=None, default=None)[source]
If key is in the flat dictionary, return its value. If not, insert key with a value of default and return default. default defaults to
None. :param mixed key: The key name :param mixed default: The default value :rtype: mixed
- set_delimiter(delimiter)[source]
Override the default or passed in delimiter with a new value. If the requested delimiter already exists in a key, a
ValueErrorwill be raised. :param str delimiter: The delimiter to use :raises: ValueError
- update(other=None, **kwargs)[source]
Update the flat dictionary with the key/value pairs from other, overwriting existing keys.
update()accepts either another flat dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the flat dictionary is then updated with those key/value pairs:d.update(red=1, blue=2). :param iterable other: Iterable of key, value pairs :rtype: None
- values()[source]
Return a copy of the flat dictionary’s list of values. See the note for
flatdict.FlatDict.items(). :rtype: list
- class FlatterDict(value=None, delimiter=':', dict_class=<class 'dict'>)[source]
Bases:
FlatDictLike
FlatDictbut also coerces lists and sets to child-dict instances with the offset as the key. Alternative to the implementation added in v1.2 of FlatDict.
- class Flattener(value=None, delimiter='.', keep_lists=False)[source]
Bases:
MutableMappingFlattener is a dictionary-like object that supports flattening and unflattening nested dictionaries and lists into a single-level dictionary with delimited keys.
- Parameters:
- unflatten()[source]
Reconstruct the original nested dictionary or list from the flat representation. :rtype: dict or list
- base64_decode(text)[source]
Decode the text to base64.
- Parameters:
text –
- Returns:
Example
from pawnlib.typing import converter decoded_base64 = converter.base64_decode("ampqampqag==") # >> jjjjjjj
- base64ify(bytes_or_str)[source]
Helper method to perform base64 encoding across Python 2.7 and Python 3.X
- Parameters:
bytes_or_str –
Example
from pawnlib.typing import converter encoded_base64 = converter.base64ify("jjjjjjj") # >> ampqampqag==
- convert_hex_to_int(data, is_comma=False)[source]
It will be changed to convert_dict_hex_to_int
- Parameters:
data (
Any) – datais_comma (
bool, optional) – human-readable notation |default|False
- Returns:
Example
from pawnlib.typing import converter data = {"aaa": "0x1323"} converter.convert_hex_to_int(data) # >> {"aaa": 4899}
- convert_dict_hex_to_int(data, is_comma=False, debug=False, ignore_keys=[], ansi=False, is_tint=False, symbol='')[source]
This function recursively converts hex to int.
- Parameters:
- Returns:
Example
from pawnlib.typing import converter data = {"aaa": "0x1323"} converter.convert_dict_hex_to_int(data) # >> {"aaa": 4899}
- decimal_hex_to_number(hex_value, precision=18, is_tint=False)[source]
Converts a hex value to a Decimal with precise handling of large numbers. :type hex_value:
Union[int,str] :param hex_value: The hexadecimal value (int or hex string). :type precision:int, optional :param precision: Number of decimal places to round the result to.|default|
18- Parameters:
is_tint (
bool, optional) – If True, divide the value by 10^18 (used for large number conversion). |default|False- Return type:
Decimal- Returns:
Decimal representation of the number.
- hex_to_number(hex_value, is_comma=False, debug=False, change=False, ansi=False, is_tint=False, symbol='', show_change=False, return_decimal_as_str=True)[source]
Convert a hexadecimal value to a decimal number.
- Parameters:
hex_value (
Union[int,float,str]) – The hexadecimal value to convert.is_comma (
bool, optional) – Whether to format the output with commas. |default|Falsedebug (
bool, optional) – If True, enables debug mode. |default|Falsechange (
bool, optional) – If True, allows value changes. |default|Falseansi (
bool, optional) – If True, enables ANSI formatting. |default|Falseis_tint (
bool, optional) – If True, converts to tint value. |default|Falsesymbol (
str, optional) – An optional symbol to prepend to the output. |default|''show_change (
bool, optional) – If True, shows the change status. |default|Falsereturn_decimal_as_str (
bool, optional) – If True, returns the result as a string. |default|Trueprecision – The number of decimal places to return.
Example
hex_to_number("0x1A") # >> 26 hex_to_number("0x1A", is_comma=True) # >> "26" hex_to_number(26) # >> 26 hex_to_number("1A") # >> 26 hex_to_number("0xFFFFFFFF") # >> 4294967295
- int_to_loop_hex(value, rounding='floor')[source]
Convert a float to a hexadecimal string representing the value multiplied by 10^18.
- Parameters:
value (float) – Float value to be converted. Must be non-negative.
rounding (Literal['floor', 'round']) – Rounding method to use (‘floor’ or ‘round’). Defaults to ‘floor’. |default|
'floor'
- Returns:
Hexadecimal string of the loop value.
- Return type:
str
- Raises:
ValueError – If the input value is negative.
TypeError – If the input value is not a numeric type.
Example
from pawnlib.typing import int_to_loop_hex int_to_loop_hex(1) # >> '0xde0b6b3a7640000' int_to_loop_hex(123) # >> '0x6f05b59d3b20000000' int_to_loop_hex(1.1, rounding='floor') # >> '0xf43fc2c04ee0000' int_to_loop_hex(1.1, rounding='round') # >> '0xf43fc2c04ee0000' int_to_loop_hex(0) # >> '0x0'
- get_size(file_path='', attr=False)[source]
Returns the size of the file.
Example
from pawnlib.typing import converter converter.get_size("./requirements.txt") # > '373.0 bytes' converter.get_size("./requirements.txt", attr=True) # > ['373.0 bytes', 'FILE']
- get_file_detail(file_path, time_format='%Y-%m-%d %H:%M:%S')[source]
Returns detailed information about the given file or directory.
- Parameters:
file_path (str) – The path to the file or directory.
time_format (str) – The format for displaying time (default: ‘YYYY-MM-DD HH:MM:SS’). |default|
'%Y-%m-%d %H:%M:%S'
- Raises:
FileNotFoundError – If the specified file or directory does not exist.
- Returns:
A dictionary containing detailed information about the file or directory.
- Return type:
dict
- The returned dictionary contains the following keys:
file_path (str): The absolute path of the file or directory.
size_in_bytes (int): The size of the file in bytes. 0 if it is a directory.
size_pretty (str): The human-readable size of the file (KB, MB, GB, etc.).
creation_time (str): The creation time of the file, formatted based on the provided time_format.
modification_time (str): The last modification time of the file, formatted based on the provided time_format.
is_file (bool): True if the path is a file, False otherwise.
is_directory (bool): True if the path is a directory, False otherwise.
Example
file_info = get_file_detail("genesis.zip") print(file_info)
Example output:
- {
“file_path”: “/absolute/path/to/genesis.zip”, “size_in_bytes”: 1048576, “size_pretty”: “1.0 MB”, “creation_time”: “2024-01-23 23:23:23”, “modification_time”: “2024-01-23 23:23:23”, “is_file”: True, “is_directory”: False
}
- get_value_size(value)[source]
Determine the size of the value based on its type, handling nested lists and dictionaries recursively.
- Parameters:
value (Any) – The value to determine the size of.
- Returns:
The size of the value.
- Return type:
int
Example
get_value_size(None) # >> 0 get_value_size([1, 2, 3]) # >> 3 get_value_size({"key1": "value1", "key2": "value2"}) # >> 2 get_value_size("Hello") # >> 5 get_value_size(True) # >> 1 get_value_size([1, [2, 3], {"key": "value"}]) # >> 5
- convert_bytes(num)[source]
this function will convert bytes to MB…. GB… etc
- Parameters:
num (
Union[int,float]) –- Return type:
str- Returns:
Example
from pawnlib.typing import converter converter.convert_bytes(2323223232323) # > '2.1 TB' converter.convert_bytes(2323223232.232) # > '2.2 GB'
- flatten(dictionary, parent_key=False, separator='.')[source]
Turn a nested dictionary into a flattened dictionary
- flatten_list(list_items, uniq=False)[source]
this function will convert complex list to flatten list
- Parameters:
list_items (
list) –uniq (optional) – |default|
False
- Return type:
list- Returns:
Example
# >>> [ 1, 2,[ 3, [4, 5, 6], 7]] => [1, 2, 3, 4, 5, 6, 7]
- flatten_dict(init, separator='。', lkey='')[source]
this function will convert complex dict to flatten dict
- Parameters:
- Return type:
dict- Returns:
Example
# >> { "aa": { "bb": { "cc": "here" } } } => {'aa。bb。cc': 'here'}
- dict_to_line(dict_param, quotes=None, separator='=', end_separator=',', pad_width=0, key_pad_width=0, alignment='left', key_alignment='right', callback=None)[source]
Converts a dictionary into a string with various formatting options. Optionally wraps values or string values in quotes.
- Parameters:
dict_param (
dict) – The dictionary to convert.quotes (
Optional[Literal[None,'all','strings_only']], optional) – ‘all’ to wrap all values in quotes, ‘strings_only’ to wrap only string values in quotes, or None. |default|Noneseparator (
str, optional) – The separator between keys and values. |default|'='end_separator (
str, optional) – The separator between key-value pairs. |default|','pad_width (
int, optional) – The minimum width for value alignment. |default|0key_pad_width (
int, optional) – The minimum width for key alignment. |default|0alignment (
str, optional) – The alignment of the values (‘left’, ‘right’, ‘center’). |default|'left'key_alignment (
str, optional) – The alignment of the keys (‘left’, ‘right’, ‘center’). |default|'right'callback (
Optional[callable], optional) – An optional callback function to apply to each value. |default|None
- Return type:
str- Returns:
The formatted string.
- dict_none_to_zero(data)[source]
Convert the None type of the dictionary to zero.
- Parameters:
data (
dict) –- Return type:
dict- Returns:
Example
# >> {"sdsdsds": None} => {"sdsdsds": 0}
- recursive_update_dict(source_dict=None, target_dict=None)[source]
- Parameters:
- Return type:
dict- Returns:
Example
from pawnlib.typing import converter source_dict = { "aaa": { "1111": 1111, "ssss": 1111, "i_need_one": 2222 } } target_dict = { "aaa": { "i_need_one": "CHANGED_VALUE", } } converter.recursive_update_dict(source_dict, target_dict) # >> { "aaa": { "1111": 1111, "ssss": 1111, "i_need_one": "CHANGED_VALUE" } }
- list_to_oneline_string(list_param, split_str='.')[source]
Convert the list to a string of one line.
- Parameters:
list_param (
list) – Listsplit_str (
str, optional) – String to separate |default|'.'
- Returns:
Example
# >> ["111", "222", "333"] => "111.222.333"
- list_to_dict_by_key(list_of_dicts, key)[source]
Converts a list of dictionaries into a dictionary, using a specified key from each dictionary as the new key.
This function iterates through a list of dictionaries, and for each dictionary, it checks if the specified key exists. If the key is present, it adds the dictionary to the resulting dictionary using the value of the specified key as the new key.
- Parameters:
list_of_dicts (list[dict]) – List of dictionaries to be converted.
key (str) – The key whose value will be used as the new key in the resulting dictionary.
- Returns:
A dictionary with keys derived from the specified key in each dictionary.
- Return type:
dict
Example
list_of_dicts = [ {"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}, {"id": 3, "name": "Charlie"} ] result = list_to_dict_by_key(list_of_dicts, "id") # Output: # { # 1: {"id": 1, "name": "Alice"}, # 2: {"id": 2, "name": "Bob"}, # 3: {"id": 3, "name": "Charlie"} # } result = list_to_dict_by_key(list_of_dicts, "name") # Output: # { # "Alice": {"id": 1, "name": "Alice"}, # "Bob": {"id": 2, "name": "Bob"}, # "Charlie": {"id": 3, "name": "Charlie"} # }
- long_to_bytes(val, endianness='big')[source]
Use string formatting and
unhexlify()to convertval, along(), to a bytestr().- Parameters:
val (long) – The value to pack
endianness (str) – The endianness of the result.
'big'for big-endian,'little'for little-endian. If you want byte- and word-ordering to differ, you’re on your own. Using string formatting lets us use Python’s C innards.
- class PrettyOrderedDict[source]
Bases:
OrderedDictA subclass of OrderedDict that provides a pretty string representation.
Example
from pawnlib.typing.converter import PrettyOrderedDict pod = PrettyOrderedDict() pod['one'] = 1 pod['two'] = 2 pod['three'] = 3 print(pod) # >> {'one': 1, 'two': 2, 'three': 3} repr(pod) # >> "{'one': 1, 'two': 2, 'three': 3}"
- ordereddict_to_dict(obj, reverse=False)[source]
Change the order of the keys in the dictionary.
- Parameters:
obj – (OrderedDict) The dictionary to change the order of keys.
reverse (optional) – (bool) Whether to sort in reverse order. Default is False. |default|
False
- Returns:
(dict) A new dictionary with the keys sorted in the specified order.
Example
from collections import OrderedDict from pawnlib.typing.converter import ordereddict_to_dict # Create an ordered dictionary od = OrderedDict([('c', 3), ('b', 2), ('a', 1)]) # Change the order of the keys in the dictionary new_dict = ordereddict_to_dict(od) # Print the new dictionary print(new_dict) # >> {'a': 1, 'b': 2, 'c': 3}
- recursive_operate_dict(obj, fn, target='key')[source]
- Parameters:
obj –
fn –
target (optional) – |default|
'key'
- Returns:
Example
from pawnlib.typing import converter obj = { "LLLLLL": "AAAAAAAA", "AAAAAA": "AAAAAAAA", "DDDDDD": 11111, "DDDDSD": { "ASDFASDF": 111, "ZXCZXCZXC": "DDDDDDDD" } } # recursive_operate_dict(obj, fn=lower_case, target="key") # # { # llllll: 'AAAAAAAA' <class 'str'> len=8 # aaaaaa: 'AAAAAAAA' <class 'str'> len=8 # dddddd: 11111 <class 'int'> len=5 # ddddsd: { # asdfasdf: 111 <class 'int'> len=3 # zxczxczxc: 'DDDDDDDD' <class 'str'> len=8 # } # # recursive_operate_dict(obj, fn=lower_case, target="value") # # { # LLLLLL: 'aaaaaaaa' <class 'str'> len=8 # AAAAAA: 'aaaaaaaa' <class 'str'> len=8 # DDDDDD: '11111' <class 'str'> len=5 # DDDDSD: { # ASDFASDF: '111' <class 'str'> len=3 # ZXCZXCZXC: 'dddddddd' <class 'str'> len=8 # } # }
- class UpdateType(is_debug=False, use_env=False, default_schema={}, input_schema={})[source]
Bases:
object
- execute_function(module_func)[source]
Run the specified function or method.
- Parameters:
module_func (str) – The name of the function or method to be executed. If the function is a method of a class, the format should be “module.class.method”. If the function is a top-level function, the format should be “module.function”.
- Returns:
The return value of the executed function or method.
- Return type:
any
Example
# Execute a top-level function execute_function("os.getcwd") # >> '/Users/username' # Execute a method of a class execute_function("requests.Session.get") # >> <Response [200]>
- influxdb_metrics_dict(tags, measurement)[source]
Default data set used by influxdb
- Parameters:
tags –
measurement –
- Returns:
- rm_space(value, replace_str='_')[source]
Remove all spaces from the given value. InfluxDB does not allow spaces
- Parameters:
value (str or any) – The value to remove spaces from.
replace_str (str) – The string to replace the spaces with. Default is “_”. |default|
'_'
- Returns:
The value without spaces.
- Return type:
str or any
Example
# Removing spaces from a string assert rm_space("hello world") == "hello_world" # Replacing spaces with a custom string assert rm_space("hello world", "-") == "hello-world" # Removing spaces from a non-string value assert rm_space(1234) == 1234 # Removing spaces from an empty string assert rm_space("") == 0
- replace_ignore_char(value, patterns=None, replace_str='_')[source]
Remove the ignoring character for adding to InfluxDB.
- Parameters:
- Returns:
A value without ignoring characters.
- Return type:
str, float, or int
Example
# example 1 >>> replace_ignore_char("hello world") 'hello_world' # example 2 >>> replace_ignore_char("1,234.56") '1_234.56' # example 3 >>> replace_ignore_char(1234) 1234
- replace_ignore_dict_kv(dict_data, *args, **kwargs)[source]
Replaces a string of patterns in a dictionary.
- Parameters:
dict_data –
args –
kwargs –
- Returns:
Example
from pawnlib.typing import converter tags = { "aaaa___": "aaa", "vvvv ": "vvvv", " s sss": "12222" } print(converter.replace_ignore_dict_kv(dict_data=tags, patterns=["___"], replace_str=">")) #> {'aaaa>': 'aaa', 'vvvv': 'vvvv', 's sss': '12222'}
- influx_key_value(key_values, sep=',', operator='=')[source]
Convert the dictionary to influxdb’s key=value format.
- Parameters:
- Returns:
Example
from pawnlib.typing import converter tags = { "a": "value1", "b ": "value3", "c": "value4" } print(converter.influx_key_value(tags)) # >> a=value1,b_=value3,c=value4
- extract_values_in_list(key='', list_of_dicts=[])[source]
Extract the values from a list of dictionaries.
- Parameters:
- Returns:
Example
from pawnlib.typing import converter sample_list = [ { "name": "John Doe", "age": 30, "height": 1.75, "weight": 70, },{ "name": "John", "age": 32, "height": 1.71, "weight": 71, } ] print(extract_values_in_list("age", sample_list)) # [30, 32] print(extract_values_in_list("none_key", sample_list)) # []
- split_every_n(data, n)[source]
Split a list into sublists of length n.
- Parameters:
data – (list) The list to split.
n – (int) The length of each sublist.
- Returns:
(list) A list of sublists.
Example
data = [1, 2, 3, 4, 5, 6, 7, 8, 9] split_every_n(data, 3) # >> [[1, 2, 3], [4, 5, 6], [7, 8, 9]] data = ['a', 'b', 'c', 'd', 'e', 'f'] split_every_n(data, 2) # >> [['a', 'b'], ['c', 'd'], ['e', 'f']]
- class_extract_attr_list(obj, attr_name='name')[source]
Extract a list of attributes from a list of objects or a single object.
- Parameters:
obj (list or object) – A list of objects or a single object.
attr_name (str) – The name of the attribute to extract. Default is “name”. |default|
'name'
- Returns:
A list of attributes.
- Return type:
list
Example
class Person: def __init__(self, name, age): self.name = name self.age = age people = [Person("Alice", 25), Person("Bob", 30), Person("Charlie", 35)] # Extract names from a list of objects names = class_extract_attr_list(people, "name") # >> ["Alice", "Bob", "Charlie"] # Extract age from a list of objects ages = class_extract_attr_list(people, "age") # >> [25, 30, 35] # Extract name from a single object name = class_extract_attr_list(Person("David", 40), "name") # >> "David"
- append_zero(value)[source]
Append zero to the value if it is less than 10.
- Parameters:
value – (int) The value to check.
- Returns:
(str) The value with zero appended if it is less than 10.
Example
append_zero(5) # >> '05' append_zero(15) # >> 15
- append_suffix(text=None, suffix=None)[source]
Append suffix to the end of the given text if it does not already end with the suffix.
- Parameters:
- Returns:
(str) The text with the suffix appended.
Example
text = "example" suffix = "_test" append_suffix(text, suffix) # >> "example_test" text = "example_test" suffix = "_test" append_suffix(text, suffix) # >> "example_test"
- append_prefix(text=None, prefix=None)[source]
Add a prefix to the given text if it doesn’t already start with the prefix.
- Parameters:
- Returns:
(str) The text with the prefix added.
Example
text = "world" prefix = "hello_" append_prefix(text, prefix) # >> "hello_world" text = "hello_world" prefix = "hello_" append_prefix(text, prefix) # >> "hello_world"
- replace_path_with_suffix(url, suffix)[source]
Replace the path of the given URL with the new suffix.
- Parameters:
url – (str) The original URL whose path will be replaced.
suffix – (str) The suffix to replace the path in the URL.
- Returns:
(str) The modified URL with the new path.
- camel_case_to_space_case(s)[source]
Convert a camel case string to a space separated string.
- Parameters:
s – (str) The camel case string to convert.
- Returns:
(str) The space separated string.
Example
print(camel_case_to_space_case("helloWorld")) # >> "hello world" print(camel_case_to_space_case("thisIsAReallyLongString")) # >> "this is a really long string"
- camelcase_to_underscore(name)[source]
Convert camelCase string to underscore_case string.
- Parameters:
name – A string in camelCase format.
- Returns:
A string in underscore_case format.
Example
camelcase_to_underscore("camelCaseString") # >> 'camel_case_string' camelcase_to_underscore("anotherExample") # >> 'another_example'
- lower_case(s)[source]
Convert string to lower case. :type s: :param s: :return:
Example
from pawnlib.typing import lower_case converter.lower_case('DDDDDDDDDDDDDDDD') # >> 'dddddddddddddddd'
- upper_case(s)[source]
Convert string to uppercase.
- Parameters:
s (str) – string to convert
- Returns:
uppercase string
- Return type:
str
Example
print(upper_case("hello world")) # >> "HELLO WORLD" print(upper_case("Python")) # >> "PYTHON"
- snake_case(s)[source]
Convert a string to snake_case.
- Parameters:
s – (str) The string to convert.
- Returns:
(str) The snake_case version of the string.
Example
snake_case("HelloWorld") # >> 'hello_world' snake_case("hello-world") # >> 'hello_world' snake_case("snake_case") # >> 'snake_case'
- snake_case_to_title_case(s, separator=' ')[source]
Convert a snake_case string to Title Case with a specified separator.
- Parameters:
s – The input snake_case string to convert.
separator (optional) – The separator to use between words. Default is a space. |default|
' '
- Returns:
The converted string in Title Case with the specified separator.
- camel_case_to_lower_case(s)[source]
Convert a string from camelcase to spacecase.
- Parameters:
s –
- Returns:
Example
from pawnlib.typing import converter converter.camel_case_to_lower_case('HelloWorld') # >> 'hello_world'
- lower_case_to_camel_case(s)[source]
Convert a string from camelcase to spacecase.
- Parameters:
s –
- Returns:
Example
from pawnlib.typing import converter converter.lower_case_to_camel_case('HelloWorld') # >> 'HelloWorld'
- camel_case_to_upper_case(s)[source]
Convert a string from camelcase to spacecase.
- Parameters:
s –
- Returns:
Example
from pawnlib.typing import converter converter.camel_case_to_upper_case('HelloWorld') # >> 'HELLO_WORLD'
- upper_case_to_camel_case(s)[source]
Convert a string from camelcase to spacecase.
- Parameters:
s –
- Returns:
Example
from pawnlib.typing import converter converter.upper_case_to_camel_case('HelloWorld') # >> 'HelloWorld'
- shorten_text(text='', width=None, placeholder='[...]', shorten_middle=False, truncate_side='right', use_tags=False)[source]
Shortens a text string to the specified width and placeholders.
- Parameters:
text (optional) – text to shorten. |default|
''width (optional) – maximum width of the string. |default|
Noneplaceholder (optional) – placeholder string to indicate truncated text. |default|
'[...]'shorten_middle (optional) – True if the text is to be shortened in the middle. |default|
Falsetruncate_side (optional) – ‘left’, ‘right’, or ‘middle’ to specify which part to truncate. |default|
'right'use_tags (optional) – True if ASCII and tags need to be removed from text. |default|
False
- Returns:
The shortened text.
Example
from pawnlib.typing.converter import shorten_text shorten_text("Hello, world!", width=8, placeholder='...') # >> "Hello..." shorten_text("Hello, world!", width=8, placeholder='...', shorten_middle=True) # >> "Hel...d!" shorten_text("Hello, world!", width=8, placeholder='...', truncate_side='left') # >> "...world!"
- get_shortened_tx_hash(input_data=None, width=14, placeholder='..', shorten_middle=True)[source]
Extracts and shortens a transaction hash from a dictionary or shortens a provided string.
- Parameters:
input_data (dict or str, optional) – Input data containing a txHash (dict) or a string to shorten. |default|
Nonewidth (int) – Maximum length of the shortened text (default: 14). |default|
14placeholder (str) – String to insert in the shortened text (default: “..”). |default|
'..'shorten_middle (bool) – Whether to shorten the middle of the text (default: True). |default|
True
- Returns:
Shortened transaction hash in the format “<shortened_text>” or None if invalid input.
- Return type:
str
Example
from pawnlib.typing.converter import get_shortened_tx_hash # Example usage payload = {"params": {"txHash": "0x1234567890abcdef1234567890abcdef12345678"}} print(get_shortened_tx_hash(payload)) # Output: <0x1234..5678> # Test with string tx_string = "0xabcdef1234567890abcdef1234567890abcdef12" print(get_shortened_tx_hash(tx_string)) # Output: <0xabc..ef12> # Test with invalid input print(get_shortened_tx_hash(None)) # Output: None
- truncate_float(number, digits=2)[source]
Truncate a float to a specified number of decimal places.
- Parameters:
number – float number to be truncated.
digits (optional) – number of decimal places to truncate to. Default is 2. |default|
2
- Return type:
float- Returns:
float truncated to the specified number of decimal places.
Example
from pawnlib.typing.converter import truncate_float truncate_float(16.42413, 3) # >> 16.424 truncate_float(-1.13034, 2) # >> -1.13
- truncate_decimal(number, digits=2)[source]
Truncate a decimal number to the specified number of decimal places without rounding.
- Parameters:
number – The decimal number to be truncated.
digits (
int, optional) – The number of decimal places to truncate the number to. Default is 2. |default|2
- Return type:
Decimal- Returns:
The truncated decimal number.
Example
from pawnlib.typing.converter import truncate_decimal truncate_decimal(3.14159, 2) # >> 3.14 truncate_decimal(3.14159, 4) # >> 3.1415
- remove_zero(int_value)[source]
Remove zero from the end of a float number if it’s an integer.
- Parameters:
int_value – The value to remove zero from.
- Returns:
The value without trailing zero if it’s a float number and is an integer, otherwise the original value.
Example
remove_zero(5.0) # >> 5 remove_zero(5.5) # >> 5.5
- remove_tags(text, case_sensitive='lower', tag_style='square')[source]
Remove specific tags from given text based on case sensitivity and tag style options.
- Parameters:
text – The input text from which tags need to be removed.
case_sensitive (
Literal['lower','upper','both'], optional) – The case sensitivity option for tags, default is “lower”. Available options are “lower”, “upper”, and “both”. |default|'lower'tag_style (
Literal['angle','square'], optional) – The tag style to be removed, default is “square”. Available options are “angle” and “square”. |default|'square'
- Return type:
str- Returns:
The cleaned text after specific tags have been removed.
- remove_ascii_color_codes(text)[source]
Remove ASCII color codes from a string.
- Parameters:
text – string to remove ASCII color codes from
- Returns:
string without ASCII color codes
Example
from pawnlib.typing.converter import remove_ascii_color_codes remove_ascii_color_codes("[31mHello[0m") # >> "Hello"
- json_to_hexadecimal(json_value)[source]
Encode a JSON value to a hexadecimal string.
- Parameters:
json_value – The JSON value to be encoded.
- Returns:
A hexadecimal string representation of the input JSON value.
Example
json_value = {"name": "Alice", "age": 30} json_to_hexadecimal(json_value) # >> '0x7b226e616d65223a2022416c696365222c2022616765223a2033307d' json_value = [1, 2, 3, 4, 5] json_to_hexadecimal(json_value) # >> '0x5b312c20322c20332c20342c20355d'
- hexadecimal_to_json(hexadecimal_string)[source]
Decode a hexadecimal string to a JSON object.
- Parameters:
hexadecimal_string – A hexadecimal string to be decoded.
- Returns:
A JSON object decoded from the hexadecimal string.
Example
decoded_json = hexadecimal_to_json("0x7b2268656c6c6f223a2022776f726c64227d") # >> {"hello": "world"} decoded_json = hexadecimal_to_json("7b2268656c6c6f223a2022776f726c64227d") # >> {"hello": "world"}
- decode_jwt(jwt_token, use_kst=False)[source]
Decode a JWT token and return its header, payload, and expiration details.
- Parameters:
jwt_token – The JWT token to decode.
use_kst (optional) – Boolean indicating whether to convert expiration time to KST timezone. |default|
False
- Returns:
A dictionary containing the decoded header, payload, expiration time, remaining time, and remaining seconds.
Example
decoded = decode_jwt("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhIiwicGVybWlzc2lvbnMiOiJ1c2VyIiwiZXhwIjoxNzIzNjAxMjI5fQ.OVkMM0MSH48qk25TN1LyJytfGa5QG4IyhBqVk9GyyzI") print(decoded["header"]) # >> {'typ': 'JWT', 'alg': 'HS256'} print(decoded["payload"]) # >> {'sub': 'a', 'permissions': 'user', 'exp': 1723601229} print(decoded["expiration_time"]) # >> '2024-08-14 02:07:09 UTC' print(decoded["remaining_time"]) # >> 'Token has expired' print(decoded["remaining_seconds"]) # >> 0
- escape_markdown(text)[source]
Escape Markdown special characters for Telegram’s MarkdownV2 format.
Converts input to string if it’s not already a string and escapes necessary characters.
- Parameters:
text – The text to escape for MarkdownV2, can be a number or string.
- Returns:
Escaped text for safe MarkdownV2 usage in Telegram.
- escape_non_markdown(text)[source]
Escapes special characters only in non-markdown parts of the input text.
- Parameters:
text – Input text with markdown content.
- Returns:
Text where special characters are escaped outside markdown syntax.
- format_network_traffic(size, unit=None, per_second=False, use_commas=True, show_unit=True)[source]
Convert network traffic data to appropriate units (bps, Kbps, Mbps, Gbps).
- Parameters:
size (
int) – Data size in bytes.unit (str, optional) – The desired unit for conversion(e.g., ‘Kbps’, ‘Mbps’, ‘Gbps’). If None, automatically chooses the best fit unit. |default|
Noneper_second (
bool, optional) – If True, use per second transmission units (bps). |default|Falseuse_commas (
bool, optional) – If True, add commas to numbers for better readability. |default|Trueshow_unit (
bool, optional) – If True, include the unit in the output string. If False, return only the numeric value. |default|True
- Return type:
Union[str,float]- Returns:
Converted string (e.g., ‘12.34 Mbps’ or ‘12.34 Mbps/s’) if show_unit is True, else a float.
Example
>>> format_network_traffic(1500) '12.00 Kbps' >>> format_network_traffic(1500000, use_commas=True) '1,200.00 Mbps' >>> format_network_traffic(1500000, per_second=True, use_commas=True) '1,200.00 Mbps/s' >>> format_network_traffic(1500000, show_unit=False) 1200.00
- format_size(size, unit=None, unit_type='storage', decimal_places=2, base=1024, use_iec=False, use_commas=True)[source]
Format a size into a human-readable string with appropriate units.
- Parameters:
size (float) – The size to format. Must be a non-negative number.
unit (str, optional) – The desired unit for conversion (e.g., ‘KB’, ‘MB’, ‘GB’, etc.). If None, automatically chooses the best fit unit. |default|
Noneunit_type (str, optional) – The type of units to use (‘storage’, ‘network’, or custom). Default is ‘storage’. |default|
'storage'decimal_places (int, optional) – The number of decimal places to round to. Default is 2. |default|
2base (int, optional) – The base for conversion, either 1024 (default for storage) or 1000 (for network). |default|
1024use_iec (bool, optional) – Whether to use IEC units (KiB, MiB, GiB, …) instead of SI units. |default|
Falseuse_commas (bool, optional) – Whether to include commas in the formatted number. |default|
True
- Returns:
Formatted size string with appropriate unit.
- Return type:
str
Example
from pawnlib.typing.converter import format_size >>> format_size(1536) # Output: "1.50 KB" >>> format_size(1536000, unit_type="network") # Output: "12.29 Mbps" >>> format_size(1536000, unit_type="network", use_commas=True) # Output: "12.29 Mbps" >>> format_size(1536, decimal_places=1, unit_type="storage") # Output: "1.5 KB"
- format_text(text='', style='', output_format='slack', custom_delimiters=None, max_length=None)[source]
Apply the specified Slack, Markdown, or HTML-compatible formatting to the entire text. If the style is not supported, return the original text unchanged. Supports custom delimiters and a maximum length limit.
- Parameters:
text (optional) – The original string to be formatted. |default|
''style (optional) – The style to apply (e.g., ‘bold’, ‘italic’, ‘code’, ‘pre’, ‘strike’, ‘quote’). |default|
''output_format (optional) – The format for the output (‘slack’, ‘html’). Default is ‘slack’. |default|
'slack'custom_delimiters (optional) – A tuple of custom delimiters (start, end) to use for formatting. |default|
Nonemax_length (optional) – Maximum length of the text. If exceeded, the text is truncated with ellipsis. |default|
None
- Returns:
The formatted string, or the original text if the style is unsupported.
Example
from pawnlib.typing.converter import format_text formatted_bold = format_text("Important Notice", "bold") print(formatted_bold) # >> *Important Notice* formatted_truncated = format_text("This is a very long text", "bold", max_length=10) print(formatted_truncated) # >> *This is a...* formatted_custom = format_text("Custom", "bold", custom_delimiters=("<<", ">>")) print(formatted_custom) # >> <<Custom>>
- format_link(url, text=None, output_format='slack', custom_delimiters=None, html_attributes=None)[source]
Apply link formatting compatible with Slack, Markdown, HTML, or custom delimiters. If text is not provided, the URL will be used as the text.
- Parameters:
url – The URL to be linked. This is required.
text (optional) – The visible text of the link. If not provided, the URL will be used as the text. |default|
Noneoutput_format (optional) – The format for the output (‘slack’, ‘markdown’, ‘html’, ‘custom’). Default is ‘slack’. |default|
'slack'custom_delimiters (optional) – A tuple of custom delimiters (start, end) to use for custom output. Only used if output_format is ‘custom’. |default|
None
- Returns:
The formatted link.
Example
from pawnlib.typing.converter import format_link # Slack-style link formatted_link = format_link("http://google.com", "Google") print(formatted_link) # >> <http://google.com|Google> # Markdown-style link formatted_link = format_link("http://google.com", "Google", output_format="markdown") print(formatted_link) # >> [Google](http://google.com) # HTML-style link formatted_link = format_link("http://google.com", "Google", output_format="html") print(formatted_link) # >> <a href="http://google.com">Google</a> # Custom delimiters formatted_link = format_link("http://google.com", "Google", output_format="custom", custom_delimiters=("<<", ">>")) print(formatted_link) # >> <<Google:http://google.com>>
- mask_string(s='', show_chars=4, show_length=True, align='right', mask_char='*')[source]
Mask a string by showing a specific number of characters at the specified position (left, right, center, or side), and optionally display the string’s length.
- Parameters:
s (str) – The string to mask. |default|
''show_chars (int, optional) – Number of characters to show. Defaults to 4. |default|
4show_length (bool, optional) – Whether to show the string length. Defaults to True. |default|
Truealign (str, optional) – Position of the visible characters: ‘left’, ‘right’, ‘center’, or ‘side’. Defaults to ‘right’. |default|
'right'mask_char (str, optional) – Character used for masking. Defaults to ‘*’. |default|
'*'
- Returns:
The masked string.
- Return type:
str
- Raises:
ValueError – If align is not one of ‘left’, ‘right’, ‘center’, or ‘side’.
Examples:
from pawnlib.typing.converter import mask_string >>> mask_string("AKIAIOSFODNN7EXAMPLE", show_chars=4, align='right') '*****************MPLE (len=20)' >>> mask_string("AKIAIOSFODNN7EXAMPLE", show_chars=4, align='side') 'AKIA************MPLE (len=20)' >>> mask_string("AKIAIOSFODNN7EXAMPLE", show_chars=6, align='center', mask_char='#') '####SFODNN####### (len=20)' >>> mask_string("AKIAIOSFODNN7EXAMPLE", show_chars=4, mask_char="🔒") '🔒🔒🔒🔒🔒🔒🔒🔒🔒🔒🔒🔒🔒🔒🔒MPLE (len=20)' >>> mask_string("SECRET-DATA", show_chars=5, mask_char="🍩") '🍩🍩🍩🍩🍩🍩-DATA (len=11)' >>> mask_string("CONFIDENTIAL", show_chars=3, align='center', mask_char="🌟") '🌟🌟🌟🌟🌟🌟🌟IAL🌟🌟🌟🌟🌟🌟 (len=12)'
- format_hx_addresses_recursively(data={}, preps_name_info={})[source]
Recursively formats a nested dictionary or list by appending node names to values starting with ‘hx’.
- Parameters:
- Returns:
The updated dictionary or list with formatted ‘hx’ addresses.
- Return type:
dict or list
Example
from pawnlib.typing.converter import format_hx_addresses_recursively data = { "roots": { "8.9.19.17:7100": "hx1ab5883939f2fd478e92aa1260438aa1f03440c1", "14.6.28.6:7100": "hxaf3fb9a9ff98df2145a36dabfcaa3837a289496b" }, "children": [ {"addr": "1.3.8.70:7100", "id": "hxa62afdeda4eba10f141fa5ef21796ac2bdcc6629"}, {"addr": "14.6.28.64:7100", "id": "hx2a3fb9a9ff98df2145936d2bfcaa3837a289496b"} ] } preps_name_info = { "hx1ab5883939f2fd478e92aa1260438aa1f03440c1": "Node1", "hxaf3fb9a9ff98df2145a36dabfcaa3837a289496b": "Node2", "hx2a3fb9a9ff98df2145936d2bfcaa3837a289496b": "Node3" } result = format_hx_addresses_recursively(data, preps_name_info) # Output: # { # "roots": { # "8.9.19.17:7100": "hx1ab5883939f2fd478e92aa1260438aa1f03440c1 (Node1)", # "14.6.28.6:7100": "hxaf3fb9a9ff98df2145a36dabfcaa3837a289496b (Node2)" # }, # "children": [ # {"addr": "1.3.8.70:7100", "id": "hxa62afdeda4eba10f141fa5ef21796ac2bdcc6629 (Node3)"}, # {"addr": "14.6.28.64:7100", "id": "hx2a3fb9a9ff98df2145936d2bfcaa3837a289496b (Node2)"} # ] # }
- filter_by_key(data, target_key)[source]
Recursively filters a nested dictionary or list to find and return the value of a specific key.
- Parameters:
data (dict or list) – The nested dictionary or list to search.
target_key (str) – The key to search for.
- Returns:
The value(s) associated with the target key.
- Return type:
dict, list, or any
Example
from pawnlib.typing.converter import filter_by_key # Example 1: Nested dictionary search data = { "level1": { "level2": { "target": "value1", "other": "value2" }, "another_level2": { "target": "value3" } } } result = filter_by_key(data, "target") # Output: {'level1': {'level2': {'target': 'value1'}, 'another_level2': {'target': 'value3'}}} # Example 2: Nested list search data = [ {"key1": "value1", "target": "value2"}, {"key2": {"target": "value3"}} ] result = filter_by_key(data, "target") # Output: [{'target': 'value2'}, {'key2': {'target': 'value3'}}] # Example 3: No matching key data = {"key1": {"key2": {"key3": "value"}}} result = filter_by_key(data, "non_existent_key") # Output: None
pawnlib.typing.date_utils module
from pawnlib.typing import date_utils
- class TimeCalculator(seconds=0)[source]
Bases:
objectA class to convert seconds into various human-readable string formats.
- Parameters:
seconds (
Union[int,float], optional) – The time in seconds to be converted (integer or float). |default|0
Example
tc = TimeCalculator(1224411.5) print(tc.to_strings()) # "14 days, 04:06:51" print(tc.to_strings(include_ms=True)) # "14 days, 04:06:51.500" print(tc.to_minutes()) # 20406
- set_seconds(seconds)[source]
Set the seconds value and recalculate the time components.
- Parameters:
seconds (
Union[int,float]) – The time in seconds (integer or float).- Raises:
TypeError – If seconds is not an int or float.
- Return type:
None
- calculate()[source]
Calculate the days, hours, minutes, and remaining seconds from the given seconds.
- Return type:
None
- to_strings(format_type='default', include_ms=False)[source]
Return the calculated time as a string.
- Parameters:
- Return type:
str- Returns:
The formatted time string.
- convert_unix_timestamp(date_param)[source]
Convert a date parameter to a Unix timestamp.
- Parameters:
date_param (datetime.datetime or int) – A date parameter to be converted to a Unix timestamp.
- Returns:
A Unix timestamp.
- Return type:
int
Example
import datetime # Convert a datetime object to a Unix timestamp. date = datetime.datetime(2022, 1, 1, 0, 0, 0) convert_unix_timestamp(date) # >> 1640995200 # Convert an integer to a Unix timestamp. date = 1640995200 convert_unix_timestamp(date) # >> 1640995200
- get_range_day_of_month(year, month, return_unix=True)[source]
This functions will be returned first_day and last_day in parameter.
- Parameters:
year (
int) –month (
int) –return_unix (
bool, optional) – |default|True
- Returns:
(1646060400, 1648738799)
Example
from pawnlib.typing import date_utils date_utils.get_range_day_of_month(year=2022, month=3, return_unix=False) # >> ('2022-3-01 00:00:00', '2022-03-31 23:59:59')
- todaydate(date_type=None, target_datetime=None, timezone=None)[source]
Returns today’s date as a formatted string based on the specified type.
- Parameters:
date_type (
Optional[Literal['file','md','time','time_sec','hour','ms','log','log_ms','ms_text','unix','ms_unix']], optional) – Optional format type. Options are: - None: “YYYYMMDD” (default) - “file”: “YYYYMMDD_HHMM” - “md”: “MMDD” - “time”: “HH:MM:SS.sss” - “time_sec”: “HH:MM:SS” - “hour”: “HHMM” - “ms” or “log” or “log_ms”: “YYYY-MM-DD HH:MM:SS.sss” - “ms_text”: “YYYYMMDD-HHMMSSsss” - “unix”: Hexadecimal Unix timestamp (seconds) - “ms_unix”: Hexadecimal Unix timestamp (microseconds) |default|Nonetarget_datetime (
Optional[datetime], optional) – Optional datetime object. Defaults to current time if None. |default|Nonetimezone (
Optional[str], optional) – Optional timezone name (e.g., “Asia/Seoul”). Uses system timezone if None or unsupported. |default|None
- Returns:
Formatted date string.
- Return type:
str
Examples
>>> todaydate("ms_unix") '0x5e66be4a93496' >>> todaydate("log") '2025-03-25 12:34:56.789'
- format_seconds_to_hhmmss(seconds=0)[source]
This functions will be returned seconds to hh:mm:ss format
- Parameters:
seconds (
int, optional) – |default|0- Returns:
Example
from pawnlib.typing import date_utils date_utils.format_seconds_to_hhmmss(2323) # >> '00:38:43'
- timestamp_to_string(unix_timestamp, str_format='%Y-%m-%d %H:%M:%S', tz=None)[source]
Converts a Unix timestamp to a formatted string based on local timezone or specified timezone.
- Parameters:
unix_timestamp (
int) – Unix timestamp (seconds, milliseconds, or microseconds)str_format (
str, optional) – Output string format (default: ‘%Y-%m-%d %H:%M:%S’) |default|'%Y-%m-%d %H:%M:%S'tz (
Union[str,tzinfo,None], optional) – Timezone as string (e.g., ‘UTC’, ‘Asia/Seoul’) or tzinfo object (default: None, uses local timezone) |default|None
- Return type:
str- Returns:
Formatted datetime string
Example
pawnlib.typing.constants module
from pawnlib.typing import constants
- class StatusType(value)[source]
Bases:
EnumAn enumeration.
- SUCCESS = 'success'
- FAILED = 'failed'
- WARNING = 'warning'
- INFO = 'info'
- CRITICAL = 'critical'
- IN_PROGRESS = 'in_progress'
- COMPLETE = 'complete'
- PAUSED = 'paused'
- RUNNING = 'running'
- ERROR = 'error'
- RETRYING = 'retrying'
- STOPPED = 'stopped'
- QUEUED = 'queued'
- CANCELED = 'canceled'
- APPROVED = 'approved'
- REJECTED = 'rejected'
- SCHEDULED = 'scheduled'
- MAINTENANCE = 'maintenance'
- UPDATE = 'update'
- class ICONPRepStatus[source]
Bases:
object- PREP_STATUS_ACTIVE = 0
- PREP_STATUS_UNREGISTERED = 1
- PREP_STATUS_DISQUALIFIED = 2
- PREP_LAST_STATE_NONE = 0
- PREP_LAST_STATE_READY = 1
- PREP_LAST_STATE_SUCCESS = 2
- PREP_LAST_STATE_FAILURE = 3
- PREP_STATUS_DESCRIPTIONS = {0: 'active', 1: 'unregistered', 2: 'disqualified'}
- PREP_LAST_STATE_DESCRIPTIONS = {0: None, 1: 'Ready', 2: 'Success', 3: 'Failure'}
- class ICONPenaltyType[source]
Bases:
object- PENALTY_TYPE_NO_PENALTY = 0
- PENALTY_TYPE_PREP_DISQUALIFICATION = 1
- PENALTY_TYPE_ACCUMULATED_BLOCK_VALIDATION_FAILURE = 2
- PENALTY_TYPE_VALIDATION_FAILURE = 3
- PENALTY_TYPE_MISSED_NETWORK_PROPOSAL_VOTE = 4
- PENALTY_TYPE_DOUBLE_SIGN = 5
- PENALTY_TYPE_DESCRIPTIONS = {0: 'No penalty', 1: 'P-Rep disqualification penalty', 2: 'Accumulated block validation failure penalty', 3: 'Validation failure penalty', 4: 'Missed Network Proposal vote penalty', 5: 'Double sign penalty'}
- class ICONJailFlags[source]
Bases:
object- ICON_IN_JAIL = 1
- ICON_UN_JAILING = 2
- ICON_ACCUMULATED_VALIDATION_FAILURE = 4
- ICON_DOUBLE_SIGN = 8
- FLAGS = {'accumulatedValidationFailure': 4, 'doubleSign': 8, 'inJail': 1, 'unJailing': 2}
- class SpecialCharacterConstants[source]
Bases:
object- SPECIAL_CHARACTERS = '_*[]()~`>#+-=|{}.!\\\\'
- ALL_SPECIAL_CHARACTERS = '!@#$%^&*()_+-=[]{}|;:\'\\",.<>?/'
- class HTTPConstants[source]
Bases:
object- class Headers[source]
Bases:
object- CONTENT_TYPE = 'Content-Type'
- AUTHORIZATION = 'Authorization'
- USER_AGENT = 'User-Agent'
- ACCEPT = 'Accept'
- ACCEPT_LANGUAGE = 'Accept-Language'
- CACHE_CONTROL = 'Cache-Control'
- SET_COOKIE = 'Set-Cookie'
- REFERER = 'Referer'
- ORIGIN = 'Origin'
- HOST = 'Host'
- CONNECTION = 'Connection'
- class MIMEType[source]
Bases:
object- APPLICATION_JSON = 'application/json'
- APPLICATION_XML = 'application/xml'
- APPLICATION_PDF = 'application/pdf'
- APPLICATION_OCTET_STREAM = 'application/octet-stream'
- TEXT_PLAIN = 'text/plain'
- TEXT_HTML = 'text/html'
- TEXT_CSS = 'text/css'
- TEXT_JAVASCRIPT = 'text/javascript'
- IMAGE_JPEG = 'image/jpeg'
- IMAGE_PNG = 'image/png'
- IMAGE_GIF = 'image/gif'
- IMAGE_SVG = 'image/svg+xml'
- AUDIO_MP3 = 'audio/mpeg'
- AUDIO_WAV = 'audio/wav'
- VIDEO_MP4 = 'video/mp4'
- VIDEO_WEBM = 'video/webm'
- MULTIPART_FORM_DATA = 'multipart/form-data'
- APPLICATION_FORM_URLENCODED = 'application/x-www-form-urlencoded'
- class DateFormatConstants[source]
Bases:
object- ISO_8601 = '%Y-%m-%dT%H:%M:%S'
- ISO_8601_WITH_MS = '%Y-%m-%dT%H:%M:%S.%f'
- ISO_8601_WITH_TZ = '%Y-%m-%dT%H:%M:%S%z'
- HUMAN_READABLE = '%A, %d %B %Y %I:%M %p'
- SIMPLE_DATE = '%Y-%m-%d'
- SIMPLE_TIME = '%H:%M:%S'
- SIMPLE_DATETIME = '%Y-%m-%d %H:%M:%S'
- DATE_WITHOUT_YEAR = '%d-%m'
- TIME_WITHOUT_SECONDS = '%H:%M'
- US_DATE = '%m/%d/%Y'
- US_DATE_TIME = '%m/%d/%Y %I:%M %p'
- UK_DATE = '%d/%m/%Y'
- UK_DATE_TIME = '%d/%m/%Y %H:%M:%S'
- UNIX_TIMESTAMP_SECONDS = '%s'
- UNIX_TIMESTAMP_MS = '%f'
- YEAR_ONLY = '%Y'
- MONTH_YEAR = '%B %Y'
- DAY_MONTH = '%d %B'
- TIME_12_HOUR = '%I:%M %p'
- TIME_24_HOUR = '%H:%M:%S'
- class StringConstants[source]
Bases:
object- EMPTY_STRING = ''
- SPACE = ' '
- UNDERSCORE = '_'
- DASH = '-'
- COLON = ':'
- SEMICOLON = ';'
- COMMA = ','
- PERIOD = '.'
- PIPE = '|'
- NEWLINE = '\n'
- TAB = '\t'
- class FilePermissionConstants[source]
Bases:
object- READ_ONLY = 'r'
- WRITE_ONLY = 'w'
- READ_WRITE = 'r+'
- APPEND = 'a'
- BINARY_READ = 'rb'
- BINARY_WRITE = 'wb'
- BINARY_READ_WRITE = 'r+b'
- BINARY_APPEND = 'ab'
- class RegexPatternConstants[source]
Bases:
object- PATTERN_EMAIL = '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$'
- PATTERN_URL = '^(https?|ftp)://[^\\s/$.?#].[^\\s]*$'
- PATTERN_PHONE = '^\\+?1?\\d{9,15}$'
- PATTERN_POSTAL_CODE = '^\\d{5}(?:[-\\s]\\d{4})?$'
- PATTERN_IP_ADDRESS = '^(?!.*\\.$)(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d|0)(\\.(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d|0)){3}$'
- PATTERN_IP_ADDRESS_IN_LOG = '\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b'
- PATTERN_CREDIT_CARD = '^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13})$'
- PATTERN_IPV6_ADDRESS = '^([0-9a-fA-F]{1,4}:){7}([0-9a-fA-F]{1,4}|:)$'
- PATTERN_HTML_TAG = '<(\\"[^\\"]*\\"|\'[^\']*\'|[^\'\\">])*>'
- PATTERN_SLUG = '^[a-z0-9]+(?:-[a-z0-9]+)*$'
- PATTERN_INTEGER = '^-?\\d+$'
- PATTERN_FLOAT = '^-?\\d*(\\.\\d+)?$'
- PATTERN_DATE_YYYY_MM_DD = '^\\d{4}-\\d{2}-\\d{2}$'
- PATTERN_TIME_HH_MM_SS = '^\\d{2}:\\d{2}:\\d{2}$'
- class TimeConstants[source]
Bases:
object- MINUTE_IN_SECONDS = 60
- HOUR_IN_SECONDS = 3600
- DAY_IN_SECONDS = 86400
- WEEK_IN_SECONDS = 604800
- MONTH_IN_SECONDS = 2592000
- YEAR_IN_SECONDS = 31536000
- MILLISECOND_IN_SECONDS = 0.001
- MICROSECOND_IN_SECONDS = 1e-06
- NANOSECOND_IN_SECONDS = 1e-09
- HOUR_IN_MINUTES = 60
- DAY_IN_MINUTES = 1440
- WEEK_IN_MINUTES = 10080
- MONTH_IN_MINUTES = 43200
- YEAR_IN_MINUTES = 525600
- class NumericConstants[source]
Bases:
object- TINT = 1000000000000000000
- ICX_IN_LOOP = 1000000000000000000
- EXA = 1000000000000000000
- PETA = 1000000000000000
- TERA = 1000000000000
- GIGA = 1000000000
- MEGA = 1000000
- KILO = 1000
- MILLI = 0.001
- MICRO = 1e-06
- NANO = 1e-09
- SQRT_2 = 1.4142135623730951
- EULER_MASCHERONI = 0.57721
- PI = 3.14159
- E = 2.71828
- GOLDEN_RATIO = 1.618033988749895
- class UnitMultiplierConstants[source]
Bases:
objectConstants for data transfer units with standardized multipliers for conversions.
- BPS = 1
- KBPS = 1024
- MBPS = 1048576
- GBPS = 1073741824
- TBPS = 1099511627776
- BITS_PER_SECOND = 0.125
- KILOBITS_PER_SECOND = 128.0
- MEGABITS_PER_SECOND = 131072.0
- GIGABITS_PER_SECOND = 134217728.0
- TERABITS_PER_SECOND = 137438953472.0
- UNIT_MULTIPLIERS = {'B/s': 1, 'GB/s': 1073741824, 'Gbps': 134217728.0, 'KB/s': 1024, 'Kbps': 128.0, 'MB/s': 1048576, 'Mbps': 131072.0, 'TB/s': 1099511627776, 'Tbps': 137438953472.0, 'bps': 0.125}
- class AddressConstants[source]
Bases:
object- ICON_ADDRESS = 42
- ICON_ADDRESS_WITHOUT_PREFIX = 40
- CHAIN_SCORE_ADDRESS = 'cx0000000000000000000000000000000000000000'
- GOVERNANCE_ADDRESS = 'cx0000000000000000000000000000000000000001'
- ETH_ADDRESS = 40
- ETH_ADDRESS_WITH_PREFIX = 42
- BTC_ADDRESS_P2PKH = 34
- BTC_ADDRESS_BECH32 = 42
- class TimeStampDigits[source]
Bases:
object- SECONDS_DIGITS = 10
- MILLI_SECONDS_DIGITS = 13
- MICRO_SECONDS_DIGITS = 16
- NANO_SECONDS_DIGITS = 19
- PICO_SECONDS_DIGITS = 22
- FEMTO_SECONDS_DIGITS = 25
- class ICONConstants[source]
Bases:
object- ICON_METHODS = {'cx0000000000000000000000000000000000000000': ['disableScore', 'enableScore', 'acceptScore', 'rejectScore', 'blockScore', 'unblockScore', 'getBlockedScores', 'blockAccount', 'unblockAccount', 'isBlocked', 'setRevision', 'setStepPrice', 'setStepCost', 'setMaxStepLimit', 'getRevision', 'getStepPrice', 'getStepCost', 'getStepCosts', 'getMaxStepLimit', 'getScoreStatus', 'getServiceConfig', 'getFeeSharingConfig', 'getNetworkInfo', 'getIISSInfo', 'setStake', 'getStake', 'setDelegation', 'getDelegation', 'claimIScore', 'queryIScore', 'registerPRep', 'getPRep', 'unregisterPRep', 'setPRep', 'getPReps', 'getMainPReps', 'getSubPReps', 'setBond', 'getBond', 'setBonderList', 'getBonderList', 'estimateUnstakeLockPeriod', 'getPRepTerm', 'getPRepStats', 'getPRepStatsOf', 'disqualifyPRep', 'burn', 'validateRewardFund', 'setRewardFund', 'setRewardFundAllocation2', 'getScoreOwner', 'setScoreOwner', 'setNetworkScore', 'getNetworkScores', 'addTimer', 'removeTimer', 'penalizeNonvoters', 'setSlashingRates', 'getSlashingRates', 'setUseSystemDeposit', 'getUseSystemDeposit', 'getBTPNetworkTypeID', 'getPRepNodePublicKey', 'setPRepNodePublicKey', 'registerPRepNodePublicKey', 'openBTPNetwork', 'closeBTPNetwork', 'sendBTPMessage', 'getMinimumBond', 'setMinimumBond', 'initCommissionRate', 'setCommissionRate', 'requestUnjail', 'handleDoubleSignReport', 'setPRepCountConfig', 'getPRepCountConfig', 'setBondRequirementRate'], 'cx0000000000000000000000000000000000000001': ['getRevision', 'getVersion', 'getStepPrice', 'getStepCosts', 'getMaxStepLimit', 'getScoreStatus', 'acceptScore', 'rejectScore', 'addAuditor', 'removeAuditor', 'isInScoreBlackList', 'getProposal', 'getProposals', 'registerProposal', 'voteProposal', 'applyProposal', 'cancelProposal', 'onTimer']}
- class HAVAHConstants[source]
Bases:
object- HAVAH_METHODS = {'cx0000000000000000000000000000000000000000': ['setRevision', 'setStepPrice', 'setStepCost', 'setMaxStepLimit', 'getRevision', 'getStepPrice', 'getStepCost', 'getStepCosts', 'getMaxStepLimit', 'getServiceConfig', 'getScoreOwner', 'setScoreOwner', 'setRoundLimitFactor', 'getRoundLimitFactor', 'setUSDTPrice', 'getUSDTPrice', 'getIssueInfo', 'startRewardIssue', 'addPlanetManager', 'removePlanetManager', 'isPlanetManager', 'registerPlanet', 'unregisterPlanet', 'setPlanetOwner', 'getPlanetInfo', 'reportPlanetWork', 'claimPlanetReward', 'getRewardInfoOf', 'getRewardInfo', 'setPrivateClaimableRate', 'getPrivateClaimableRate', 'addDeployer', 'removeDeployer', 'isDeployer', 'getDeployers', 'setTimestampThreshold', 'getTimestampThreshold', 'grantValidator', 'revokeValidator', 'getValidators', 'getRewardInfosOf', 'withdrawLostTo', 'getLost', 'getBTPNetworkTypeID', 'getBTPPublicKey', 'openBTPNetwork', 'closeBTPNetwork', 'sendBTPMessage', 'setBTPPublicKey', 'setBlockVoteCheckParameters', 'getBlockVoteCheckParameters', 'registerValidator', 'unregisterValidator', 'getNetworkStatus', 'setValidatorInfo', 'setNodePublicKey', 'enableValidator', 'getValidatorInfo', 'getValidatorStatus', 'setActiveValidatorCount', 'getActiveValidatorCount', 'getValidatorsOf', 'getValidatorsInfo', 'getDisqualifiedValidatorsInfo'], 'cx0000000000000000000000000000000000000001': ['setRevision', 'setStepPrice', 'setStepCost', 'setMaxStepLimit', 'grantValidator', 'revokeValidator', 'setTimestampThreshold', 'setRoundLimitFactor', 'setUSDTPrice', 'setUSDTPriceOracle', 'getUSDTPriceOracle', 'addPlanetManager', 'removePlanetManager', 'startRewardIssue', 'setPrivateClaimableRate', 'withdrawLostTo', 'registerValidator', 'enableValidator', 'unregisterValidator', 'setBlockVoteCheckParameters', 'setActiveValidatorCount', 'name', 'openBTPNetwork', 'delegate', 'setDelegate']}
- class CryptographicConstants[source]
Bases:
object- SHA256_DIGEST_SIZE = 32
- SHA3_256_DIGEST_SIZE = 32
- KECCAK_256_DIGEST_SIZE = 32
- SECP256K1_PRIVATE_KEY_SIZE = 32
- SECP256K1_PUBLIC_KEY_SIZE = 64
- SECP256K1_SIGNATURE_SIZE = 64
- ED25519_PRIVATE_KEY_SIZE = 32
- ED25519_PUBLIC_KEY_SIZE = 32
- ED25519_SIGNATURE_SIZE = 64
- class NetworkConstants[source]
Bases:
object- DEFAULT_HTTP_PORT = 80
- DEFAULT_HTTPS_PORT = 443
- DEFAULT_ICON_RPC_PORT = 9000
- DEFAULT_ICON_P2P_PORT = 7100
- DEFAULT_ETHEREUM_PORT = 8545
- DEFAULT_BITCOIN_PORT = 8333
- LOCALHOST = '127.0.0.1'
- LOCALHOST_IPV6 = '::1'
- IPV4_LOOPBACK = '127.0.0.1'
- IPV6_LOOPBACK = '::1'
- IPV4_BROADCAST = '255.255.255.255'
- IPV6_BROADCAST = 'ff02::1'
- MAC_ADDRESS_BROADCAST = 'ff:ff:ff:ff:ff:ff'
- METADATA_IP = '169.254.169.254'
- class AWSRegionConstants[source]
Bases:
object- REGIONS = {'af-south-1': 'Africa (Cape Town)', 'ap-east-1': 'Asia Pacific (Hong Kong)', 'ap-northeast-1': 'Asia Pacific (Tokyo)', 'ap-northeast-2': 'Asia Pacific (Seoul)', 'ap-northeast-3': 'Asia Pacific (Osaka)', 'ap-south-1': 'Asia Pacific (Mumbai)', 'ap-southeast-1': 'Asia Pacific (Singapore)', 'ap-southeast-2': 'Asia Pacific (Sydney)', 'ca-central-1': 'Canada (Central)', 'eu-central-1': 'EU (Frankfurt)', 'eu-north-1': 'EU (Stockholm)', 'eu-south-1': 'EU (Milan)', 'eu-west-1': 'EU (Ireland)', 'eu-west-2': 'EU (London)', 'eu-west-3': 'EU (Paris)', 'me-south-1': 'Middle East (Bahrain)', 'sa-east-1': 'South America (São Paulo)', 'us-east-1': 'US East (N. Virginia)', 'us-east-2': 'US East (Ohio)', 'us-west-1': 'US West (N. California)', 'us-west-2': 'US West (Oregon)'}
- class GradeMappingConstants[source]
Bases:
object- GRADE_MAPPING = {'0x0': {'color': '[blue]\\[Main][/blue]', 'name': 'Main'}, '0x1': {'color': '[green]\\[Sub][/green]', 'name': 'Sub'}, '0x2': {'color': '[Cand]', 'name': 'Cand'}}
- class LoggingConstants[source]
Bases:
objectConstants related to logging levels and verbosity mappings.
- VERBOSE_LEVELS = {0: 30, 1: 20, 2: 10, 3: 5}
- VERBOSE_LEVEL_STRINGS = {0: 'WARNING', 1: 'INFO', 2: 'DEBUG', 3: 'TRACE'}
- LOG_LEVELS = {'CRITICAL': 50, 'DEBUG': 10, 'ERROR': 40, 'INFO': 20, 'TRACE': 5, 'WARNING': 30}
- LEVEL_NAMES = {5: 'TRACE', 10: 'DEBUG', 20: 'INFO', 30: 'WARNING', 40: 'ERROR', 50: 'CRITICAL'}
- class TerminalColor[source]
Bases:
objectExtended ANSI escape sequences for coloring terminal text with more color options.
- HEADER = '\x1b[95m'
- OKBLUE = '\x1b[94m'
- OKGREEN = '\x1b[92m'
- GREEN = '\x1b[32;40m'
- CYAN = '\x1b[96m'
- WARNING = '\x1b[93m'
- FAIL = '\x1b[91m'
- RESET = '\x1b[0m'
- ENDC = '\x1b[0m'
- BOLD = '\x1b[1m'
- ITALIC = '\x1b[1;3m'
- UNDERLINE = '\x1b[4m'
- WHITE = '\x1b[97m'
- DARK_GREY = '\x1b[38;5;243m'
- LIGHT_GREY = '\x1b[37m'
- RED = '\x1b[31m'
- BLUE = '\x1b[34m'
- YELLOW = '\x1b[33m'
- MAGENTA = '\x1b[35m'
- PURPLE = '\x1b[35;1m'
- ORANGE = '\x1b[38;5;214m'
- BRIGHT_GREEN = '\x1b[92;1m'
- BRIGHT_CYAN = '\x1b[96;1m'
- BRIGHT_MAGENTA = '\x1b[95;1m'
- DARK_BLUE = '\x1b[34;2m'
- LIGHT_BLUE = '\x1b[94;1m'
- LIGHT_YELLOW = '\x1b[93m'
- apply_terminal_color(text, color='WHITE', bold=False, underline=False, width=None)[source]
Apply the given color and style to the text and return the formatted string.
- Parameters:
text – The text to be styled.
color (optional) – The color to apply (e.g., ‘GREEN’, ‘RED’, etc.). |default|
'WHITE'bold (optional) – Whether to apply bold formatting. |default|
Falseunderline (optional) – Whether to apply underline formatting. |default|
Falsewidth (optional) – The width to center the text (optional). |default|
None
- Returns:
The styled text as a string.
- class HTTPMethodConstants[source]
Bases:
object- ALLOWS_HTTP_METHOD = ['GET', 'POST', 'PATCH', 'DELETE', 'HEAD', 'PUT', 'CONNECT', 'OPTIONS', 'TRACE']
- class OperatorConstants[source]
Bases:
object- ALLOW_OPERATOR = ['!=', '==', '>=', '<=', '>', '<', 'include', 'exclude']
- class SecretPatternConstants[source]
Bases:
objectConstants for detecting secret keys and tokens in text.
- SECRET_PATTERNS = {'aws_access_key': 'AKIA[0-9A-Z]{16}', 'aws_secret_key': '\\b[A-Za-z0-9+/]{40}\\b', 'db_connection_string': '(mysql|postgres|mongodb|redis)://[a-zA-Z0-9_]+:[a-zA-Z0-9_]+@[a-zA-Z0-9\\-.]+:\\d+(/[a-zA-Z0-9_]+)?', 'discord_bot_token': '[A-Za-z0-9]{24}\\.[A-Za-z0-9]{6}\\.[A-Za-z0-9-_]{27}', 'env_style_key': '[A-Z_]+_KEY=[A-Za-z0-9\\-]{20,}', 'general_api_key': '(?!hx|cx)[A-Za-z0-9]{32,64}', 'generic_key': '(?:key|token|secret)\\s*=\\s*[\'\\"]?[a-zA-Z0-9\\-]{20,}[\'\\"]?', 'github_pat': 'ghp_[0-9A-Za-z]{36}', 'google_api_key': 'AIza[0-9A-Za-z-_]{35}', 'jwt_token': 'eyJ[A-Za-z0-9-_]+\\.eyJ[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+', 'slack_token': 'xox[bp]-[0-9]{10,}-[a-zA-Z0-9]{20,}', 'ssh_private_key': '-----BEGIN (RSA|OPENSSH|EC) PRIVATE KEY-----[\\s\\S]+-----END (RSA|OPENSSH|EC) PRIVATE KEY-----', 'stripe_api_key': '(sk|pk|rk)_[live|test]_[0-9A-Za-z]{24}', 'twilio_api_key': 'SK[0-9a-f]{32}'}
- SECRET_DESCRIPTIONS = {'aws_access_key': 'AWS Access Key ID', 'aws_secret_key': 'AWS Secret Access Key', 'db_connection_string': 'Database Connection String (MySQL, PostgreSQL, MongoDB, Redis)', 'discord_bot_token': 'Discord Bot Token', 'env_style_key': 'Environment Variable Style Key (e.g., API_KEY=xxx)', 'general_api_key': 'General-purpose API Key (32-64 characters)', 'generic_key': 'Generic key, token, or secret pattern', 'github_pat': 'GitHub Personal Access Token', 'google_api_key': 'Google API Key', 'jwt_token': 'JSON Web Token (JWT)', 'slack_token': 'Slack API Token (Bot or User)', 'ssh_private_key': 'SSH Private Key (RSA, OpenSSH, or EC)', 'stripe_api_key': 'Stripe API Key (Secret, Publishable, or Restricted)', 'twilio_api_key': 'Twilio API Secret Key'}
- classmethod get_pattern(secret_type)[source]
Retrieve the regex pattern for the specified secret type. :type secret_type:
str:param secret_type: Type of secret (e.g., ‘slack_token’). :rtype:str:return: Regex pattern string.
- class AllConstants[source]
Bases:
ICONPRepStatus,ICONJailFlags,SpecialCharacterConstants,RegexPatternConstants,HTTPConstants,DateFormatConstants,StringConstants,FilePermissionConstants,TimeConstants,BooleanConstants,NumericConstants,UnitMultiplierConstants,AddressConstants,TimeStampDigits,ICONConstants,HAVAHConstants,CryptographicConstants,NetworkConstants,AWSRegionConstants,GradeMappingConstants,YesNoConstants,LoggingConstants,HTTPMethodConstants,OperatorConstants,SecretPatternConstants
pawnlib.typing.defines module
from pawnlib.typing import defines
- class Namespace(**kwargs)[source]
Bases:
_AttributeHolderSimple object for storing attributes.
Implements equality by attribute names and values, and provides a simple string representation.
Example
from pawnlib.typing import defines namespace = defines.Namespace(s=2323, sdsd="Sdsd") namespace.s # >> 2323 namespace.sdsd # >> 'Sdsd'
- set_namespace_default_value(namespace=None, key='', default='')[source]
Set a default value when a key in a namespace has no value
- Parameters:
- Returns:
Example
from pawnlib.config import pawn, pconf from pawnlib.typing import set_namespace_default_value pawn.set( data={"aaaa": "bbbb"} ) pawn.console.log(pconf()) undefined_key = set_namespace_default_value( namespace=pconf().data, key="cccc", default="ddddd" ) pawn.console.log(undefined_key)
- fill_required_data_arguments(required={})[source]
Fill the required data arguments.
- Parameters:
required (dict) – A dictionary of required arguments. |default|
{}- Returns:
The filled arguments.
- Return type:
argparse.Namespace
Example
required = {"arg1": "value1", "arg2": "value2"} args = fill_required_data_arguments(required) # args.arg1 == "value1" # args.arg2 == "value2"
- load_env_with_defaults(defaults=None, required_keys=None, force_reload=False, verbose=False, dotenv_path=None)[source]
Load environment variables from a .env file with additional features like defaults, required keys, reload options, and custom logging.
- Parameters:
defaults (dict) – A dictionary of default values for environment variables if they are not found in the .env file. Values can be static (e.g., ‘default_key’) or functions for dynamic defaults (e.g., lambda: ‘default’). |default|
Nonerequired_keys (list) – A list of environment variables that are required. If any of these are missing after loading, a warning or error message will be displayed. |default|
Noneforce_reload (bool) – If True, overwrites existing environment variables with values from the .env file. |default|
Falseverbose (bool) – If True, enables detailed logging for each loaded variable and missing required keys. |default|
Falsedotenv_path (str) – Optional path to the .env file. Defaults to the “.env” file in the current directory. |default|
None
Example usage:
Basic loading of environment variables from .env file:
>>> load_env_with_defaults()
Loading with default values for missing environment variables:
>>> defaults = { ... 'DATABASE_URL': 'sqlite:///default.db', ... 'API_KEY': 'default_key' ... } >>> load_env_with_defaults(defaults=defaults)
Loading required environment variables and checking for missing keys:
>>> required_keys = ['DATABASE_URL', 'API_KEY'] >>> load_env_with_defaults(required_keys=required_keys)
Forcing reload of .env variables even if they are already set in the environment:
>>> load_env_with_defaults(force_reload=True)
Enabling verbose logging to see detailed load progress:
>>> load_env_with_defaults(verbose=True)
Specifying a custom .env file path:
>>> load_env_with_defaults(dotenv_path='/custom/path/.env')
Combining multiple options:
>>> load_env_with_defaults(defaults=defaults, required_keys=required_keys, force_reload=True, verbose=True, dotenv_path='/custom/path/.env')
Notes
defaults: Use this to specify fallback values for environment variables not found in the .env file. You can provide static values or dynamic values as functions.
required_keys: If any keys in this list are missing after loading, they will be logged (if verbose=True) or raise an exception if required.
force_reload: Overwrites existing environment variables with .env file values if set to True.
verbose: Outputs detailed logs for each environment variable loaded, including defaults and any missing required keys.
dotenv_path: Allows specifying a custom .env file location, defaulting to the .env file in the current directory if not provided.
pawnlib.typing.generator module
from pawnlib.typing import generator
Generators which yield an id to include in a JSON-RPC request.
- class Null(*args, **kwargs)[source]
Bases:
objectA Null object class as part of the Null object design pattern.
Do nothing.
- class Counter(start=1, stop=10, step=1, convert_func=<class 'int'>, kwargs=None)[source]
Bases:
objectCount up
- Parameters:
start (
Union[float,int], optional) – Start Number ( float or int ) |default|1stop (
Union[float,int], optional) – Stop Number ( float or int ) |default|10step (
Union[float,int], optional) – Step Number ( float or int ) |default|1convert_func (
Callable, optional) – Functions to execute on increment |default|<class 'int'>kwargs (
Optional[Dict], optional) – Arguments to the function to be executed on increment |default|None
Example
from pawnlib.utils.generator import Counter, generate_hex for i in Counter(start=0, step=1, stop=4): pawn.console.log(f"Counter => {i}") # Counter => 0 # Counter => 1 # Counter => 2 # Counter => 3 for i in Counter(start=0, step=1, stop=10, convert_func=generate_hex, kwargs={"zfill": 10}): pawn.console.log(f"Hex Counter => {i}") # Hex Counter => 0000000000 # Hex Counter => 0000000001 # Hex Counter => 0000000002 # Hex Counter => 0000000003
- __init__(start=1, stop=10, step=1, convert_func=<class 'int'>, kwargs=None)[source]
Count up
- Parameters:
start (
Union[float,int], optional) – Start Number ( float or int ) |default|1stop (
Union[float,int], optional) – Stop Number ( float or int ) |default|10step (
Union[float,int], optional) – Step Number ( float or int ) |default|1convert_func (
Callable, optional) – Functions to execute on increment |default|<class 'int'>kwargs (
Optional[Dict], optional) – Arguments to the function to be executed on increment |default|None
Example
from pawnlib.utils.generator import Counter, generate_hex for i in Counter(start=0, step=1, stop=4): pawn.console.log(f"Counter => {i}") # Counter => 0 # Counter => 1 # Counter => 2 # Counter => 3 for i in Counter(start=0, step=1, stop=10, convert_func=generate_hex, kwargs={"zfill": 10}): pawn.console.log(f"Hex Counter => {i}") # Hex Counter => 0000000000 # Hex Counter => 0000000001 # Hex Counter => 0000000002 # Hex Counter => 0000000003
- class GenMultiMetrics(tags, measurement, is_flatten=True, is_debug=False, structure_types=None, ignore_fields=None, uid=None)[source]
Bases:
object
- generate_number_list(start=10000, count=100, convert_func=<class 'int'>)[source]
Generate a list of numbers based on the given parameters.
- Parameters:
- Returns:
(list) List of generated numbers
Example
# Generate a list of integers from 10000 to 10099 generate_number_list() # Generate a list of floats from 10000.0 to 10099.0 generate_number_list(start=10000.0, convert_func=float)
- id_generator(size=8, chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')[source]
this function will be generated random id
- Parameters:
- Returns:
:Example
# >> 00ZP5YRLRT1Y
- uuid_generator(size=8, count=4, separator='-')[source]
this function will be generated random uuid
- Parameters:
- Returns:
:Example
# >> KFXSYSVJHPE6-83KZTPKY9NL3-ZHRFUV7QRWWJ-GRWVPB6C5SM8
- decimal(start=1)[source]
Increments from start. e.g. 1, 2, 3, .. 9, 10, 11, etc.
- Parameters:
start (
int, optional) – start: The first value to start with. |default|1- Return type:
Iterator[int]- Returns:
- hexadecimal(start=1)[source]
Incremental hexadecimal numbers. e.g. 1, 2, 3, .. 9, a, b, etc.
- Parameters:
start (
int, optional) – The first value to start with. |default|1- Return type:
Iterator[str]
- uuid()[source]
Unique uuid ids.
- Return type:
Iterator[str]
Example
‘9bfe2c93-717e-4a45-b91b-55422c5af4ff’
- request_impure(id_generator_func, method, params=None, id='<NO_ID>')[source]
- Return type:
Dict[str,Any]
- json_rpc(method='', params=None, id='<NO_ID>', dumps=False)[source]
- Parameters:
- Returns:
Example
from pawnlib.typing import generator generator.json_rpc(method="icx_sendTransaction", params={"data": "ddddd"}) # > {'jsonrpc': '2.0', 'method': 'icx_sendTranscation', 'params': {'data': 'ddddd'}, 'id': 0} generator.json_rpc(method="icx_sendTransaction", params={"data": "ddddd"}) # > {'jsonrpc': '2.0', 'method': 'icx_sendTranscation', 'params': {'data': 'ddddd'}, 'id': 1}
- increase_hex(c=count(0), prefix='', zfill=0, remove_prefix=True)[source]
Returns increase hex value
- Parameters:
- Returns:
Example
from pawnlib.typing import generator generator.increase_hex() >> '0' generator.increase_hex() >> '1'
- increase_token_address(c=count(0), prefix='hx', zfill=40, remove_prefix=True)[source]
Returns increase token address
- Parameters:
Example
from pawnlib.typing import generator generator.increase_address() >> 'hx0000000000000000000000000000000000000000' generator.increase_address() >> 'hx0000000000000000000000000000000000000001'
- random_token_address(prefix='hx', nbytes=20)[source]
Return a random hx address for icon network
- Returns:
Example
from pawnlib.typing import generator generator.random_token_address() >>> 'hxa85cfbf976afba6fd5880c89372cf9f253c4a1c9'
- token_bytes(nbytes)[source]
Return a random byte string containing nbytes bytes. If nbytes is
Noneor not supplied, a reasonable default is used.- Parameters:
nbytes –
- Returns:
Example:
from pawnlib.typing import generator generator.token_bytes(16) >>> b'\xebr\x17D*t\xae\xd4\xe3S\xb6\xe2\xebP1\x8b'
- token_hex(nbytes)[source]
Return a random text string, in hexadecimal. The string has nbytes random bytes, each byte converted to two hex digits. If nbytes is
Noneor not supplied, a reasonable default is used.- Parameters:
nbytes –
- Returns:
Example
from pawnlib.typing import generator generator.token_hex(16) >>> 'f9bf78b9a18ce6d46a0cd2b0b86df9da'
- parse_regex_number_list(string)[source]
Parse the list of numbers with regex.
- Parameters:
string –
- Returns:
Example
from pawnlib.typing import generator generator.parse_regex_number_list("1-6") >>> [ 1, 2, 3, 4, 5, 6]
- request_natural(method: str, params: Dict[str, Any] | Tuple[Any, ...] | None = None, id: Any = '<NO_ID>') Dict[str, Any]
- generate_json_rpc(*a, **kw)