Package: vhelpers
vhelpersOften used functions in vladimirs-git projects.RequirementsPython >=3.8InstallationInstall the package from pypi.org releasepipinstallvhelpersor install the package from github.com releasepipinstallhttps://github.com/vladimirs-git/vhelpers/archive/refs/tags/0.1.18.tar.gzor install the package from github.com repositorypipinstallgit+https://github.com/vladimirs-git/vhelpersUsageFor easy navigation, functions are grouped by some key concept, mostly based on their return data type.
For more details, please refer to the./examplesdirectory where you will find numerous examples.ContentsvhelpersRequirementsInstallationUsagevdatedelta(start, end)delta_s(args, kwargs)vdictpop(key, data)pyproject_d(root)vintto_int(digit)vipip_prefixlen(address)ips_prefixlen(addresses)vlistdupl(items)flatten(items, ignore_types)is_in(items1, items2)no_dupl(items)replace(items, old, new)split(text, chars, ignore)to_list(items)to_lists(items, count)to_lstr(items)to_multi(items, count)vparamfrom_dict(params_d)to_dict(params)vpathget_files(root, ext)from_dict(params_d)vrebetween(text, start, end, w_start, w_end, strict)find1(pattern, string, flags)find2(pattern, string, flags)find3(pattern, string, flags)find4(pattern, string, flags)find1i(pattern, string, flags)find2i(pattern, string, flags)find1s(patterns, string, flags)ip(string)prefix(string)vstrrepr_info(args, kwargs)repr_params(args, kwargs)reverse(line)vymlhost_cmds(items)cmd_cmds(cmd, cmds)vdatedelta(start, end)Calculate the elapsed days, hours, minutes and seconds between two datetime objects.ParameterTypeDescriptionstartdatetimeThe starting datetime object.enddatetimeThe ending datetime object. If None, the current datetime is used.ReturnDIntA dictionary containing the elapsed hours, minutes, and seconds. If end is None, update data in object.fromdatetimeimportdatetimefromvhelpersimportvdatestart=datetime.strptime("2001-01-02 2:3:4","%Y-%m-%d%H:%M:%S")end=datetime.strptime("2002-02-03 3:4:5","%Y-%m-%d%H:%M:%S")print(vdate.delta(start,end))# {'hours': 9529, 'minutes': 1, 'seconds': 1}delta_s(args, kwargs)Calculate the elapsed time in the format %H:%M:%S.ParameterTypeDescriptionargsThe arguments for calculating the time delta.kwargsThe keyword arguments for calculating the time delta.ReturnstrThe elapsed time in the format %H:%M:%S.fromdatetimeimportdatetimefromvhelpersimportvdatestart=datetime.strptime("2001-01-02 2:3:4","%Y-%m-%d%H:%M:%S")end=datetime.strptime("2002-02-03 3:4:5","%Y-%m-%d%H:%M:%S")print(vdate.delta_s(start,end))# 9529:01:01vdictHelpers for dictionary processing.pop(key, data)Pop the specified item from the data by key.  If key is absent in data, do nothing and return None.ParameterTypeDescriptionkeystrThe key to be popped from the data.datadictThe data from which the key is to be popped.ReturnstrThe popped item if key is present in data, otherwise None.fromvhelpersimportvdict# Pop the specified item from the data by key.data={1:"a",2:"b"}assertvdict.pop(key=1,data=data)=="a"assertdata=={2:"b"}# If key is absent in data, do nothing and return None.assertvdict.pop(key=3,data=data)isNoneassertdata=={2:"b"}pyproject_d(root)Convert pyproject.toml to a dictionary.ParameterTypeDescriptionrootUnion[Path, str]The root directory or path to the pyproject.toml file.ReturnDict[str, Any]A dictionary containing the data from pyproject.toml.fromvhelpersimportvdictfrompathlibimportPathroot=Path(__file__).parent.parentdata=vdict.pyproject_d(root)assertdata["tool"]["poetry"]["name"]=="vhelpers"vintHelpers for int processing.to_int(digit)Convert string digit to integer.ParameterTypeDescriptiondigitUnion[int, str]Digit, string ot integer.ReturnintInteger or 0 if value is not digit.fromvhelpersimportvintassertvint.to_int(digit="1")==1assertvint.to_int(digit="a")==0vipHelpers for ip addresses processing.ip_prefixlen(address)Convert IPv4 address with mask to address with prefix length.ParameterTypeDescriptionaddressstrIP addresses with mask.ReturnstrIP addresses with prefix length.fromvhelpersimportvipassertvip.ip_prefixlen(address="10.0.0.1 255.255.255.0")=="10.0.0.1/24"ips_prefixlen(addresses)Convert IPv4 addresses with mask to addresses with prefix length.ParameterTypeDescriptionaddressesList[str]A list of IP addresses with mask.ReturnList[str]A list of IP addresses with prefix length.fromvhelpersimportvipassertvip.ips_prefixlen(addresses=["10.0.0.1 255.255.255.0"])==["10.0.0.1/24"]vlistHelpers for list processing.dupl(items)Find duplicates of the items.ParameterTypeDescriptionitemslistA list of items where need to find duplicates.ReturnlistA list of items with duplicates.fromvhelpersimportvlistassertvlist.dupl([1,2,1])==[1]assertvlist.dupl([{1},{2},{1}])==[{1}]flatten(items, ignore_types)Convert a multidimensional list to a flattened list.ParameterTypeDescriptionitemsSequenceThe list to be flattened.ignore_typesTuple[Type]Types to be ignored during flattening, defaults to (str, bytes)ReturnGeneratorA generator that yields the flattened list.fromvhelpersimportvlistassertvlist.flatten([1,[2,[3]],4,[5,[6]]])==[1,2,3,4,5,6]is_in(items1, items2)Check if any item in items1 is present in items2.ParameterTypeDescriptionitems1listA list of items.items2listA list of items.ReturnboolTrue if any item in items1 is present in items2, False otherwise.no_dupl(items)Remove duplicates from a list of items.ParameterTypeDescriptionitemslistA list of items.ReturnlistA list of items without duplicates.fromvhelpersimportvlist# Remove duplicates from a list of items.assertvlist.no_dupl(items=[1,2,1])==[1,2]replace(items, old, new)Replace one item with another.ParameterTypeDescriptionitemslistThe list of items where need replace item.oldAnyThe item to be replaced.newAnyThe item to replace with.ReturnNoneUpdate items.fromvhelpersimportvlistassertvlist.replace(items=[1,2,3],old=2,new=4)==[1,4,3]split(text, chars, ignore)Split string by punctuation chars.ParameterTypeDescriptiontextstrText to split by punctuation.charsstrExtra punctuation chars.ignorestrIgnore punctuation chars.ReturnList[str]Values without punctuation.fromvhelpersimportvlistassertvlist.split(text="1; 2_3-4X5,6",chars="_X",ignore=",")==["1","2","3","4","5,6"]to_list(items)Convert the input items from any into a list.
If items is a list, set or tuple, simply change its type to list.
Otherwise, create a list with the value as its first item.
If items is None return an empty list.ParameterTypeDescriptionitemslistThe items to be converted into a list.ReturnlistThe converted list.fromvhelpersimportvlist# Convert the input items into a list.#  If items is a list, set or tuple, simply change its type to listassertvlist.to_list(items=(1,2))==[1,2]# Otherwise, create a list with the value as its first item.assertvlist.to_list(items=1)==[1]# If items is None return an empty list.assertvlist.to_list(items=None)==[]to_lists(items, count)Convert a flat list into a multidimensional list with a fixed number of inner lists.ParameterTypeDescriptionitemslistThe flat list to convert.countintThe number of inner lists.ReturnList[List[Any]A multidimensional list.fromvhelpersimportvlist# Convert a flat list into a multidimensional list with a fixed number of inner lists.assertvlist.to_lists(items=[1,2,3,4,5],count=2)==[[1,2,3],[4,5]]assertvlist.to_lists(items=(1,2,3,4,5),count=3)==[[1,2],[3,4],[5]]to_lstr(items)Convert the input items from any into a list of string.
If items is a list, set or tuple, simply change its type to list.
If items is None or empty string return an empty list.ParameterTypeDescriptionitemsAnyThe items to be converted into a list of string.ReturnlistThe converted list.fromvhelpersimportvlist# Convert the input items from any into a list of string.assertvlist.to_lstr(items=[1,"2"])==["1","2"]assertvlist.to_lstr(1)==["1"]assertvlist.to_lstr("")==[]to_multi(items, count)Convert a flat list into a multidimensional list. Convert a list with the specified number of items
in each inner list.ParameterTypeDescriptionitemslistThe flat list to convert.countintThe number of items to include in each inner list.ReturnLLAnyA multidimensional list with the specified number of items in each inner list.fromvhelpersimportvlistassertvlist.to_multi(items=[1,2,3,4,5],count=2)==[[1,2],[3,4],[5]]vparamHelpers for parameters processing.
Parameters are typically included in the query string of a URL,
which is the part of a URL that comes after the question mark “?” character.from_dict(params_d)Convert a dictionary to a list of parameters.ParameterTypeDescriptionparams_ddictA dictionary with keys and values.Returnlist[tuple[str, Any]]A list of parameters. If params_d is empty, returns an empty list.fromvhelpersimportvparam# Convert a dictionary to a list of parameters.assertvparam.from_dict(params_d={"a":[1,1]})==[("a",1),("a",1)]to_dict(params)Convert a list of parameters to a dictionary.ParameterTypeDescriptionparamslist[tuple[str, Any]]A list of parameters.ReturndictA dictionary where key is param name.vpathHelpers for path processing.get_files(root, ext)Get paths to files with interested extension in root directory.ParameterTypeDescriptionrootstrRoot directory to search for files with required extension.extstrExtension, end of file name.ReturnList[str]A list of paths with required extension.from_dict(params_d)Convert a dictionary to a list of parameters.vreHelpers for regex processing.between(text, start, end, w_start, w_end, strict)Find all substrings between the start and end regexes.ParameterTypeDescriptiontextstrText where need to find start and end.startstrRegex of start.endstrRegex of end.w_startboolTrue  - Returns text with matched start text, False - (default) Returns text without matched start text.w_endboolTrue  - Returns text with matched end text, False - (default) Returns text without matched end text.strictboolTrue  - Raises ValueError if absent start or end, False - Returns empty string if absent start or end.ReturnstrText between start and end.fromvhelpersimportvreTEXT="a1\nb2\nc3\nd4"assertvre.between(text=TEXT,start="b2",end="c3",w_start=True,w_end=True)=="b2\nc3"find1(pattern, string, flags)Parse 1 item using findall. 1 group with parentheses in pattern is required. If nothing is found,
return 1 empty string.ParameterTypeDescriptionpatternstrThe regular expression pattern to search for.stringstrThe string to search within.flagsintOptional flags to modify the behavior of the search.ReturnstrThe interested substring, or an empty string if nothing is found.fromvhelpersimportvreassertvre.find1(pattern="a(b)cde",string="abcde")=="b"assertvre.find1(pattern="a(b)cde",string="acde")==""find2(pattern, string, flags)Parse 2 items using findall. 2 groups with parentheses in pattern is required. If nothing is found,
return 2 empty strings.ParameterTypeDescriptionpatternstrThe regular expression pattern.stringstrThe string to search within.flagsintOptional flags to modify the behavior of the search.ReturnTuple[str, str]A tuple with two interested substrings, or empty strings if nothing is found.fromvhelpersimportvreassertvre.find2(pattern="a(b)(c)de",string="abcde")==("b","c")assertvre.find2(pattern="a(b)(c)de",string="acde")==("","")find3(pattern, string, flags)Parse 3 items using findall. 3 groups with parentheses in pattern is required. If nothing is found,
returns 3 empty strings.ParameterTypeDescriptionpatternstrThe regular expression pattern.stringstrThe string to search within.flagsintOptional flags to modify the behavior of the search.ReturnTuple[str, str, str]A tuple with three interested substrings, or empty strings if nothing is found.fromvhelpersimportvreassertvre.find3(pattern="a(b)(c)(d)e",string="abcde")==("b","c","d")assertvre.find3(pattern="a(b)(c)(d)e",string="acde")==("","","")find4(pattern, string, flags)Parse 4 items using findall. 4 groups with parentheses in pattern is required. If nothing is found,
return 4 empty strings.ParameterTypeDescriptionpatternstrThe regular expression pattern.stringstrThe string to search within.flagsintOptional flags to modify the behavior of the search.ReturnTuple[str, str, str, str]A tuple with three interested substrings, or empty strings if nothing is found.fromvhelpersimportvreassertvre.find4(pattern="a(b)(c)(d)(e)",string="abcde")==("b","c","d","e")assertvre.find4(pattern="a(b)(c)(d)(e)",string="acde")==("","","","")find1i(pattern, string, flags)Parse 1 digit using findall. 1 group with parentheses in pattern is required. If nothing is found,
return 0.ParameterTypeDescriptionpatternstrThe regular expression pattern to search for.stringstrThe string to search within.flagsintOptional flags to modify the behavior of the search.ReturnintThe interested integer, or 0 if nothing is found.fromvhelpersimportvreassertvre.find1i(pattern="a([0-9]+)b",string="a123b")==123assertvre.find1i(pattern="a([0-9]+)b",string="ab")==0find2i(pattern, string, flags)Parse 2 digits using findall. 2 groups with parentheses in pattern is required. If nothing is found,
return tuple of 0.ParameterTypeDescriptionpatternstrThe regular expression pattern to search for.stringstrThe string to search within.flagsintOptional flags to modify the behavior of the search.ReturnT2IntThe interested integers, or tuple of 0 if nothing is found.fromvhelpersimportvreassertvre.find2i(pattern="a([0-9])b([0-9])c",string="a1b2c")==(1,2)assertvre.find2i(pattern="a([0-9])b([0-9])c",string="a1bc")==(0,0)find1s(patterns, string, flags)Parse 1st item that match one of regex in patterns. 1 group with parentheses in pattern is required.
If nothing is found, return 1 empty string.ParameterTypeDescriptionpatternsSeqStrThe list of regular expression patterns to search for.stringstrThe string to search within.flagsintOptional flags to modify the behavior of the search.ReturnstrThe interested substring, or an empty string if nothing is found.fromvhelpersimportvreassertvre.find1s(patterns=["a(a)cde","a(b)cde"],string="abcde")=="b"ip(string)Parse 1st IP address from string. If nothing is found, returns an empty string.ParameterTypeDescriptionstringstrString where need to find IP address.ReturnstrIP address.fromvhelpersimportvreassertvre.ip("text 10.0.0.1/24 10.0.0.2/24 text")=="10.0.0.1"prefix(string)Parse 1st prefix from string. If nothing is found, returns an empty string.ParameterTypeDescriptionstringstrString where need to find prefix.ReturnstrPrefix.fromvhelpersimportvreassertvre.prefix("text 10.0.0.1/24 10.0.0.2/24 text")=="10.0.0.1/24"vstrrepr_info(args, kwargs)Create info without qutes for the __repr__() method.ParameterTypeDescriptionargsThe positional arguments.kwargsThe keyword arguments.ReturnstrA string representation of the parameters.fromvhelpersimportvstrassertvstr.repr_params("a","b",c="c",d="d")=="a, b, c=c, d=d"repr_params(args, kwargs)Create parameters for the __repr__() method.ParameterTypeDescriptionargsThe positional arguments.kwargsThe keyword arguments.ReturnstrA string representation of the parameters.fromvhelpersimportvstrassertvstr.repr_params("a","b",c="c",d="d")=="'a', 'b', c='c', d='d'"reverse(line)Reverse the characters in a string.ParameterTypeDescriptionlinestrThe input string.ReturnstrThe reversed string.fromvhelpersimportvstrassertvstr.reverse("abc")=="cba"vymlHelpers for YAML processing.host_cmds(items)Create commands in YAML format. Where the hostname is the key and the list of commands is the value.ParameterTypeDescriptionitemsList[Tuple[str, str, Union[str, List]List of tuples that contain: hostname, parent command, children commands.ReturnstrYAML formatted commands.fromvhelpersimportvyml# Create commands in YAML format.items=[("router1","interface Ethernet1/1",["description text","shutdown"])]result="""
---
router1: |
 interface Ethernet1/1
  description text
  shutdown
""".strip()assertvyml.host_cmds(items)==resultcmd_cmds(cmd, cmds)Join parent command and children commands using indentation.ParameterTypeDescriptioncmdstrParent command.cmdsUnion[str, List]Children commands.ReturnstrYAML formatted commands with indentation.fromvhelpersimportvymlresult=""" interface Ethernet1/1\ndescription text\nshutdown"""assertvyml.cmd_cmds(cmd="interface Ethernet1/1",cmds=["description text","shutdown"])==result